repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
globality-corp/microcosm-flask
microcosm_flask/conventions/alias.py
configure_alias
def configure_alias(graph, ns, mappings): """ Register Alias endpoints for a resource object. """ convention = AliasConvention(graph) convention.configure(ns, mappings)
python
def configure_alias(graph, ns, mappings): """ Register Alias endpoints for a resource object. """ convention = AliasConvention(graph) convention.configure(ns, mappings)
[ "def", "configure_alias", "(", "graph", ",", "ns", ",", "mappings", ")", ":", "convention", "=", "AliasConvention", "(", "graph", ")", "convention", ".", "configure", "(", "ns", ",", "mappings", ")" ]
Register Alias endpoints for a resource object.
[ "Register", "Alias", "endpoints", "for", "a", "resource", "object", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/alias.py#L54-L60
train
26,300
globality-corp/microcosm-flask
microcosm_flask/conventions/alias.py
AliasConvention.configure_alias
def configure_alias(self, ns, definition): """ Register an alias endpoint which will redirect to a resource's retrieve endpoint. Note that the retrieve endpoint MUST be registered prior to the alias endpoint. The definition's func should be a retrieve function, which must: - accept kwargs for path data - return a resource :param ns: the namespace :param definition: the endpoint definition """ @self.add_route(ns.alias_path, Operation.Alias, ns) @qs(definition.request_schema) @wraps(definition.func) def retrieve(**path_data): # request_schema is optional for Alias request_data = ( load_query_string_data(definition.request_schema) if definition.request_schema else dict() ) resource = definition.func(**merge_data(path_data, request_data)) kwargs = dict() identifier = "{}_id".format(name_for(ns.subject)) kwargs[identifier] = resource.id url = ns.url_for(Operation.Retrieve, **kwargs) return redirect(url) retrieve.__doc__ = "Alias a {} by name".format(ns.subject_name)
python
def configure_alias(self, ns, definition): """ Register an alias endpoint which will redirect to a resource's retrieve endpoint. Note that the retrieve endpoint MUST be registered prior to the alias endpoint. The definition's func should be a retrieve function, which must: - accept kwargs for path data - return a resource :param ns: the namespace :param definition: the endpoint definition """ @self.add_route(ns.alias_path, Operation.Alias, ns) @qs(definition.request_schema) @wraps(definition.func) def retrieve(**path_data): # request_schema is optional for Alias request_data = ( load_query_string_data(definition.request_schema) if definition.request_schema else dict() ) resource = definition.func(**merge_data(path_data, request_data)) kwargs = dict() identifier = "{}_id".format(name_for(ns.subject)) kwargs[identifier] = resource.id url = ns.url_for(Operation.Retrieve, **kwargs) return redirect(url) retrieve.__doc__ = "Alias a {} by name".format(ns.subject_name)
[ "def", "configure_alias", "(", "self", ",", "ns", ",", "definition", ")", ":", "@", "self", ".", "add_route", "(", "ns", ".", "alias_path", ",", "Operation", ".", "Alias", ",", "ns", ")", "@", "qs", "(", "definition", ".", "request_schema", ")", "@", ...
Register an alias endpoint which will redirect to a resource's retrieve endpoint. Note that the retrieve endpoint MUST be registered prior to the alias endpoint. The definition's func should be a retrieve function, which must: - accept kwargs for path data - return a resource :param ns: the namespace :param definition: the endpoint definition
[ "Register", "an", "alias", "endpoint", "which", "will", "redirect", "to", "a", "resource", "s", "retrieve", "endpoint", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/alias.py#L18-L51
train
26,301
globality-corp/microcosm-flask
microcosm_flask/conventions/encoding.py
encode_id_header
def encode_id_header(resource): """ Generate a header for a newly created resource. Assume `id` attribute convention. """ if not hasattr(resource, "id"): return {} return { "X-{}-Id".format( camelize(name_for(resource)) ): str(resource.id), }
python
def encode_id_header(resource): """ Generate a header for a newly created resource. Assume `id` attribute convention. """ if not hasattr(resource, "id"): return {} return { "X-{}-Id".format( camelize(name_for(resource)) ): str(resource.id), }
[ "def", "encode_id_header", "(", "resource", ")", ":", "if", "not", "hasattr", "(", "resource", ",", "\"id\"", ")", ":", "return", "{", "}", "return", "{", "\"X-{}-Id\"", ".", "format", "(", "camelize", "(", "name_for", "(", "resource", ")", ")", ")", "...
Generate a header for a newly created resource. Assume `id` attribute convention.
[ "Generate", "a", "header", "for", "a", "newly", "created", "resource", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L33-L47
train
26,302
globality-corp/microcosm-flask
microcosm_flask/conventions/encoding.py
load_request_data
def load_request_data(request_schema, partial=False): """ Load request data as JSON using the given schema. Forces JSON decoding even if the client not specify the `Content-Type` header properly. This is friendlier to client and test software, even at the cost of not distinguishing HTTP 400 and 415 errors. """ try: json_data = request.get_json(force=True) or {} except Exception: # if `simplpejson` is installed, simplejson.scanner.JSONDecodeError will be raised # on malformed JSON, where as built-in `json` returns None json_data = {} request_data = request_schema.load(json_data, partial=partial) if request_data.errors: # pass the validation errors back in the context raise with_context( UnprocessableEntity("Validation error"), [{ "message": "Could not validate field: {}".format(field), "field": field, "reasons": reasons } for field, reasons in request_data.errors.items()], ) return request_data.data
python
def load_request_data(request_schema, partial=False): """ Load request data as JSON using the given schema. Forces JSON decoding even if the client not specify the `Content-Type` header properly. This is friendlier to client and test software, even at the cost of not distinguishing HTTP 400 and 415 errors. """ try: json_data = request.get_json(force=True) or {} except Exception: # if `simplpejson` is installed, simplejson.scanner.JSONDecodeError will be raised # on malformed JSON, where as built-in `json` returns None json_data = {} request_data = request_schema.load(json_data, partial=partial) if request_data.errors: # pass the validation errors back in the context raise with_context( UnprocessableEntity("Validation error"), [{ "message": "Could not validate field: {}".format(field), "field": field, "reasons": reasons } for field, reasons in request_data.errors.items()], ) return request_data.data
[ "def", "load_request_data", "(", "request_schema", ",", "partial", "=", "False", ")", ":", "try", ":", "json_data", "=", "request", ".", "get_json", "(", "force", "=", "True", ")", "or", "{", "}", "except", "Exception", ":", "# if `simplpejson` is installed, s...
Load request data as JSON using the given schema. Forces JSON decoding even if the client not specify the `Content-Type` header properly. This is friendlier to client and test software, even at the cost of not distinguishing HTTP 400 and 415 errors.
[ "Load", "request", "data", "as", "JSON", "using", "the", "given", "schema", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L58-L84
train
26,303
globality-corp/microcosm-flask
microcosm_flask/conventions/encoding.py
load_query_string_data
def load_query_string_data(request_schema, query_string_data=None): """ Load query string data using the given schema. Schemas are assumed to be compatible with the `PageSchema`. """ if query_string_data is None: query_string_data = request.args request_data = request_schema.load(query_string_data) if request_data.errors: # pass the validation errors back in the context raise with_context(UnprocessableEntity("Validation error"), dict(errors=request_data.errors)) return request_data.data
python
def load_query_string_data(request_schema, query_string_data=None): """ Load query string data using the given schema. Schemas are assumed to be compatible with the `PageSchema`. """ if query_string_data is None: query_string_data = request.args request_data = request_schema.load(query_string_data) if request_data.errors: # pass the validation errors back in the context raise with_context(UnprocessableEntity("Validation error"), dict(errors=request_data.errors)) return request_data.data
[ "def", "load_query_string_data", "(", "request_schema", ",", "query_string_data", "=", "None", ")", ":", "if", "query_string_data", "is", "None", ":", "query_string_data", "=", "request", ".", "args", "request_data", "=", "request_schema", ".", "load", "(", "query...
Load query string data using the given schema. Schemas are assumed to be compatible with the `PageSchema`.
[ "Load", "query", "string", "data", "using", "the", "given", "schema", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L87-L101
train
26,304
globality-corp/microcosm-flask
microcosm_flask/conventions/encoding.py
dump_response_data
def dump_response_data(response_schema, response_data, status_code=200, headers=None, response_format=None): """ Dumps response data as JSON using the given schema. Forces JSON encoding even if the client did not specify the `Accept` header properly. This is friendlier to client and test software, even at the cost of not distinguishing HTTP 400 and 406 errors. """ if response_schema: response_data = response_schema.dump(response_data).data return make_response(response_data, response_schema, response_format, status_code, headers)
python
def dump_response_data(response_schema, response_data, status_code=200, headers=None, response_format=None): """ Dumps response data as JSON using the given schema. Forces JSON encoding even if the client did not specify the `Accept` header properly. This is friendlier to client and test software, even at the cost of not distinguishing HTTP 400 and 406 errors. """ if response_schema: response_data = response_schema.dump(response_data).data return make_response(response_data, response_schema, response_format, status_code, headers)
[ "def", "dump_response_data", "(", "response_schema", ",", "response_data", ",", "status_code", "=", "200", ",", "headers", "=", "None", ",", "response_format", "=", "None", ")", ":", "if", "response_schema", ":", "response_data", "=", "response_schema", ".", "du...
Dumps response data as JSON using the given schema. Forces JSON encoding even if the client did not specify the `Accept` header properly. This is friendlier to client and test software, even at the cost of not distinguishing HTTP 400 and 406 errors.
[ "Dumps", "response", "data", "as", "JSON", "using", "the", "given", "schema", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L116-L133
train
26,305
globality-corp/microcosm-flask
microcosm_flask/conventions/encoding.py
merge_data
def merge_data(path_data, request_data): """ Merge data from the URI path and the request. Path data wins. """ merged = request_data.copy() if request_data else {} merged.update(path_data or {}) return merged
python
def merge_data(path_data, request_data): """ Merge data from the URI path and the request. Path data wins. """ merged = request_data.copy() if request_data else {} merged.update(path_data or {}) return merged
[ "def", "merge_data", "(", "path_data", ",", "request_data", ")", ":", "merged", "=", "request_data", ".", "copy", "(", ")", "if", "request_data", "else", "{", "}", "merged", ".", "update", "(", "path_data", "or", "{", "}", ")", "return", "merged" ]
Merge data from the URI path and the request. Path data wins.
[ "Merge", "data", "from", "the", "URI", "path", "and", "the", "request", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L157-L166
train
26,306
globality-corp/microcosm-flask
microcosm_flask/conventions/encoding.py
find_response_format
def find_response_format(allowed_response_formats): """ Basic content negotiation logic. If the 'Accept' header doesn't exactly match a format we can handle, we return JSON """ # allowed formats default to [] before this if not allowed_response_formats: allowed_response_formats = [ResponseFormats.JSON] content_type = request.headers.get("Accept") if content_type is None: # Nothing specified, default to endpoint definition if allowed_response_formats: return allowed_response_formats[0] # Finally, default to JSON return ResponseFormats.JSON for response_format in ResponseFormats.prioritized(): if response_format not in allowed_response_formats: continue if response_format.matches(content_type): return response_format # fallback for previous behavior return ResponseFormats.JSON
python
def find_response_format(allowed_response_formats): """ Basic content negotiation logic. If the 'Accept' header doesn't exactly match a format we can handle, we return JSON """ # allowed formats default to [] before this if not allowed_response_formats: allowed_response_formats = [ResponseFormats.JSON] content_type = request.headers.get("Accept") if content_type is None: # Nothing specified, default to endpoint definition if allowed_response_formats: return allowed_response_formats[0] # Finally, default to JSON return ResponseFormats.JSON for response_format in ResponseFormats.prioritized(): if response_format not in allowed_response_formats: continue if response_format.matches(content_type): return response_format # fallback for previous behavior return ResponseFormats.JSON
[ "def", "find_response_format", "(", "allowed_response_formats", ")", ":", "# allowed formats default to [] before this", "if", "not", "allowed_response_formats", ":", "allowed_response_formats", "=", "[", "ResponseFormats", ".", "JSON", "]", "content_type", "=", "request", ...
Basic content negotiation logic. If the 'Accept' header doesn't exactly match a format we can handle, we return JSON
[ "Basic", "content", "negotiation", "logic", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L184-L210
train
26,307
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
build_swagger
def build_swagger(graph, ns, operations): """ Build out the top-level swagger definition. """ base_path = graph.build_route_path(ns.path, ns.prefix) schema = swagger.Swagger( swagger="2.0", info=swagger.Info( title=graph.metadata.name, version=ns.version, ), consumes=swagger.MediaTypeList([ swagger.MimeType("application/json"), ]), produces=swagger.MediaTypeList([ swagger.MimeType("application/json"), ]), basePath=base_path, paths=swagger.Paths(), definitions=swagger.Definitions(), ) add_paths(schema.paths, base_path, operations) add_definitions(schema.definitions, operations) try: schema.validate() except Exception: logger.exception("Swagger definition did not validate against swagger schema") raise return schema
python
def build_swagger(graph, ns, operations): """ Build out the top-level swagger definition. """ base_path = graph.build_route_path(ns.path, ns.prefix) schema = swagger.Swagger( swagger="2.0", info=swagger.Info( title=graph.metadata.name, version=ns.version, ), consumes=swagger.MediaTypeList([ swagger.MimeType("application/json"), ]), produces=swagger.MediaTypeList([ swagger.MimeType("application/json"), ]), basePath=base_path, paths=swagger.Paths(), definitions=swagger.Definitions(), ) add_paths(schema.paths, base_path, operations) add_definitions(schema.definitions, operations) try: schema.validate() except Exception: logger.exception("Swagger definition did not validate against swagger schema") raise return schema
[ "def", "build_swagger", "(", "graph", ",", "ns", ",", "operations", ")", ":", "base_path", "=", "graph", ".", "build_route_path", "(", "ns", ".", "path", ",", "ns", ".", "prefix", ")", "schema", "=", "swagger", ".", "Swagger", "(", "swagger", "=", "\"2...
Build out the top-level swagger definition.
[ "Build", "out", "the", "top", "-", "level", "swagger", "definition", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L40-L70
train
26,308
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
add_paths
def add_paths(paths, base_path, operations): """ Add paths to swagger. """ for operation, ns, rule, func in operations: path = build_path(operation, ns) if not path.startswith(base_path): continue method = operation.value.method.lower() # If there is no version number or prefix, we'd expect the base path to be "" # However, OpenAPI requires the minimal base path to be "/" # This means we need branching logic for that special case suffix_start = 0 if len(base_path) == 1 else len(base_path) paths.setdefault( path[suffix_start:], swagger.PathItem(), )[method] = build_operation(operation, ns, rule, func)
python
def add_paths(paths, base_path, operations): """ Add paths to swagger. """ for operation, ns, rule, func in operations: path = build_path(operation, ns) if not path.startswith(base_path): continue method = operation.value.method.lower() # If there is no version number or prefix, we'd expect the base path to be "" # However, OpenAPI requires the minimal base path to be "/" # This means we need branching logic for that special case suffix_start = 0 if len(base_path) == 1 else len(base_path) paths.setdefault( path[suffix_start:], swagger.PathItem(), )[method] = build_operation(operation, ns, rule, func)
[ "def", "add_paths", "(", "paths", ",", "base_path", ",", "operations", ")", ":", "for", "operation", ",", "ns", ",", "rule", ",", "func", "in", "operations", ":", "path", "=", "build_path", "(", "operation", ",", "ns", ")", "if", "not", "path", ".", ...
Add paths to swagger.
[ "Add", "paths", "to", "swagger", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L73-L90
train
26,309
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
add_definitions
def add_definitions(definitions, operations): """ Add definitions to swagger. """ for definition_schema in iter_definitions(definitions, operations): if definition_schema is None: continue if isinstance(definition_schema, str): continue for name, schema in iter_schemas(definition_schema): definitions.setdefault(name, swagger.Schema(schema))
python
def add_definitions(definitions, operations): """ Add definitions to swagger. """ for definition_schema in iter_definitions(definitions, operations): if definition_schema is None: continue if isinstance(definition_schema, str): continue for name, schema in iter_schemas(definition_schema): definitions.setdefault(name, swagger.Schema(schema))
[ "def", "add_definitions", "(", "definitions", ",", "operations", ")", ":", "for", "definition_schema", "in", "iter_definitions", "(", "definitions", ",", "operations", ")", ":", "if", "definition_schema", "is", "None", ":", "continue", "if", "isinstance", "(", "...
Add definitions to swagger.
[ "Add", "definitions", "to", "swagger", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L93-L105
train
26,310
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
iter_definitions
def iter_definitions(definitions, operations): """ Generate definitions to be converted to swagger schema. """ # general error schema per errors.py for error_schema_class in [ErrorSchema, ErrorContextSchema, SubErrorSchema]: yield error_schema_class() # add all request and response schemas for operation, obj, rule, func in operations: yield get_request_schema(func) yield get_response_schema(func)
python
def iter_definitions(definitions, operations): """ Generate definitions to be converted to swagger schema. """ # general error schema per errors.py for error_schema_class in [ErrorSchema, ErrorContextSchema, SubErrorSchema]: yield error_schema_class() # add all request and response schemas for operation, obj, rule, func in operations: yield get_request_schema(func) yield get_response_schema(func)
[ "def", "iter_definitions", "(", "definitions", ",", "operations", ")", ":", "# general error schema per errors.py", "for", "error_schema_class", "in", "[", "ErrorSchema", ",", "ErrorContextSchema", ",", "SubErrorSchema", "]", ":", "yield", "error_schema_class", "(", ")"...
Generate definitions to be converted to swagger schema.
[ "Generate", "definitions", "to", "be", "converted", "to", "swagger", "schema", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L108-L120
train
26,311
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
build_path
def build_path(operation, ns): """ Build a path URI for an operation. """ try: return ns.url_for(operation, _external=False) except BuildError as error: # we are missing some URI path parameters uri_templates = { argument: "{{{}}}".format(argument) for argument in error.suggested.arguments } # flask will sometimes try to quote '{' and '}' characters return unquote(ns.url_for(operation, _external=False, **uri_templates))
python
def build_path(operation, ns): """ Build a path URI for an operation. """ try: return ns.url_for(operation, _external=False) except BuildError as error: # we are missing some URI path parameters uri_templates = { argument: "{{{}}}".format(argument) for argument in error.suggested.arguments } # flask will sometimes try to quote '{' and '}' characters return unquote(ns.url_for(operation, _external=False, **uri_templates))
[ "def", "build_path", "(", "operation", ",", "ns", ")", ":", "try", ":", "return", "ns", ".", "url_for", "(", "operation", ",", "_external", "=", "False", ")", "except", "BuildError", "as", "error", ":", "# we are missing some URI path parameters", "uri_templates...
Build a path URI for an operation.
[ "Build", "a", "path", "URI", "for", "an", "operation", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L123-L137
train
26,312
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
header_param
def header_param(name, required=False, param_type="string"): """ Build a header parameter definition. """ return swagger.HeaderParameterSubSchema(**{ "name": name, "in": "header", "required": required, "type": param_type, })
python
def header_param(name, required=False, param_type="string"): """ Build a header parameter definition. """ return swagger.HeaderParameterSubSchema(**{ "name": name, "in": "header", "required": required, "type": param_type, })
[ "def", "header_param", "(", "name", ",", "required", "=", "False", ",", "param_type", "=", "\"string\"", ")", ":", "return", "swagger", ".", "HeaderParameterSubSchema", "(", "*", "*", "{", "\"name\"", ":", "name", ",", "\"in\"", ":", "\"header\"", ",", "\"...
Build a header parameter definition.
[ "Build", "a", "header", "parameter", "definition", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L150-L160
train
26,313
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
query_param
def query_param(name, field, required=False): """ Build a query parameter definition. """ parameter = build_parameter(field) parameter["name"] = name parameter["in"] = "query" parameter["required"] = False return swagger.QueryParameterSubSchema(**parameter)
python
def query_param(name, field, required=False): """ Build a query parameter definition. """ parameter = build_parameter(field) parameter["name"] = name parameter["in"] = "query" parameter["required"] = False return swagger.QueryParameterSubSchema(**parameter)
[ "def", "query_param", "(", "name", ",", "field", ",", "required", "=", "False", ")", ":", "parameter", "=", "build_parameter", "(", "field", ")", "parameter", "[", "\"name\"", "]", "=", "name", "parameter", "[", "\"in\"", "]", "=", "\"query\"", "parameter"...
Build a query parameter definition.
[ "Build", "a", "query", "parameter", "definition", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L163-L173
train
26,314
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
path_param
def path_param(name, ns): """ Build a path parameter definition. """ if ns.identifier_type == "uuid": param_type = "string" param_format = "uuid" else: param_type = "string" param_format = None kwargs = { "name": name, "in": "path", "required": True, "type": param_type, } if param_format: kwargs["format"] = param_format return swagger.PathParameterSubSchema(**kwargs)
python
def path_param(name, ns): """ Build a path parameter definition. """ if ns.identifier_type == "uuid": param_type = "string" param_format = "uuid" else: param_type = "string" param_format = None kwargs = { "name": name, "in": "path", "required": True, "type": param_type, } if param_format: kwargs["format"] = param_format return swagger.PathParameterSubSchema(**kwargs)
[ "def", "path_param", "(", "name", ",", "ns", ")", ":", "if", "ns", ".", "identifier_type", "==", "\"uuid\"", ":", "param_type", "=", "\"string\"", "param_format", "=", "\"uuid\"", "else", ":", "param_type", "=", "\"string\"", "param_format", "=", "None", "kw...
Build a path parameter definition.
[ "Build", "a", "path", "parameter", "definition", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L176-L196
train
26,315
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
build_operation
def build_operation(operation, ns, rule, func): """ Build an operation definition. """ swagger_operation = swagger.Operation( operationId=operation_name(operation, ns), parameters=swagger.ParametersList([ ]), responses=swagger.Responses(), tags=[ns.subject_name], ) # custom header parameter swagger_operation.parameters.append( header_param("X-Response-Skip-Null") ) # path parameters swagger_operation.parameters.extend([ path_param(argument, ns) for argument in rule.arguments ]) # query string parameters qs_schema = get_qs_schema(func) if qs_schema: swagger_operation.parameters.extend([ query_param(name, field) for name, field in qs_schema.fields.items() ]) # body parameter request_schema = get_request_schema(func) if request_schema: swagger_operation.parameters.append( body_param(request_schema) ) # sort parameters for predictable output swagger_operation.parameters.sort(key=lambda parameter: parameter["name"]) add_responses(swagger_operation, operation, ns, func) return swagger_operation
python
def build_operation(operation, ns, rule, func): """ Build an operation definition. """ swagger_operation = swagger.Operation( operationId=operation_name(operation, ns), parameters=swagger.ParametersList([ ]), responses=swagger.Responses(), tags=[ns.subject_name], ) # custom header parameter swagger_operation.parameters.append( header_param("X-Response-Skip-Null") ) # path parameters swagger_operation.parameters.extend([ path_param(argument, ns) for argument in rule.arguments ]) # query string parameters qs_schema = get_qs_schema(func) if qs_schema: swagger_operation.parameters.extend([ query_param(name, field) for name, field in qs_schema.fields.items() ]) # body parameter request_schema = get_request_schema(func) if request_schema: swagger_operation.parameters.append( body_param(request_schema) ) # sort parameters for predictable output swagger_operation.parameters.sort(key=lambda parameter: parameter["name"]) add_responses(swagger_operation, operation, ns, func) return swagger_operation
[ "def", "build_operation", "(", "operation", ",", "ns", ",", "rule", ",", "func", ")", ":", "swagger_operation", "=", "swagger", ".", "Operation", "(", "operationId", "=", "operation_name", "(", "operation", ",", "ns", ")", ",", "parameters", "=", "swagger", ...
Build an operation definition.
[ "Build", "an", "operation", "definition", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L199-L242
train
26,316
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
add_responses
def add_responses(swagger_operation, operation, ns, func): """ Add responses to an operation. """ # default error swagger_operation.responses["default"] = build_response( description="An error occurred", resource=type_name(name_for(ErrorSchema())), ) if getattr(func, "__doc__", None): description = func.__doc__.strip().splitlines()[0] else: description = "{} {}".format(operation.value.name, ns.subject_name) if operation in (Operation.Upload, Operation.UploadFor): swagger_operation.consumes = [ "multipart/form-data" ] # resource request request_resource = get_request_schema(func) if isinstance(request_resource, str): if not hasattr(swagger_operation, "consumes"): swagger_operation.consumes = [] swagger_operation.consumes.append(request_resource) # resources response response_resource = get_response_schema(func) if isinstance(response_resource, str): if not hasattr(swagger_operation, "produces"): swagger_operation.produces = [] swagger_operation.produces.append(response_resource) elif not response_resource: response_code = ( 204 if operation.value.default_code == 200 else operation.value.default_code ) swagger_operation.responses[str(response_code)] = build_response( description=description, ) else: swagger_operation.responses[str(operation.value.default_code)] = build_response( description=description, resource=response_resource, )
python
def add_responses(swagger_operation, operation, ns, func): """ Add responses to an operation. """ # default error swagger_operation.responses["default"] = build_response( description="An error occurred", resource=type_name(name_for(ErrorSchema())), ) if getattr(func, "__doc__", None): description = func.__doc__.strip().splitlines()[0] else: description = "{} {}".format(operation.value.name, ns.subject_name) if operation in (Operation.Upload, Operation.UploadFor): swagger_operation.consumes = [ "multipart/form-data" ] # resource request request_resource = get_request_schema(func) if isinstance(request_resource, str): if not hasattr(swagger_operation, "consumes"): swagger_operation.consumes = [] swagger_operation.consumes.append(request_resource) # resources response response_resource = get_response_schema(func) if isinstance(response_resource, str): if not hasattr(swagger_operation, "produces"): swagger_operation.produces = [] swagger_operation.produces.append(response_resource) elif not response_resource: response_code = ( 204 if operation.value.default_code == 200 else operation.value.default_code ) swagger_operation.responses[str(response_code)] = build_response( description=description, ) else: swagger_operation.responses[str(operation.value.default_code)] = build_response( description=description, resource=response_resource, )
[ "def", "add_responses", "(", "swagger_operation", ",", "operation", ",", "ns", ",", "func", ")", ":", "# default error", "swagger_operation", ".", "responses", "[", "\"default\"", "]", "=", "build_response", "(", "description", "=", "\"An error occurred\"", ",", "...
Add responses to an operation.
[ "Add", "responses", "to", "an", "operation", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L245-L292
train
26,317
globality-corp/microcosm-flask
microcosm_flask/swagger/definitions.py
build_response
def build_response(description, resource=None): """ Build a response definition. """ response = swagger.Response( description=description, ) if resource is not None: response.schema = swagger.JsonReference({ "$ref": "#/definitions/{}".format(type_name(name_for(resource))), }) return response
python
def build_response(description, resource=None): """ Build a response definition. """ response = swagger.Response( description=description, ) if resource is not None: response.schema = swagger.JsonReference({ "$ref": "#/definitions/{}".format(type_name(name_for(resource))), }) return response
[ "def", "build_response", "(", "description", ",", "resource", "=", "None", ")", ":", "response", "=", "swagger", ".", "Response", "(", "description", "=", "description", ",", ")", "if", "resource", "is", "not", "None", ":", "response", ".", "schema", "=", ...
Build a response definition.
[ "Build", "a", "response", "definition", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L295-L307
train
26,318
globality-corp/microcosm-flask
microcosm_flask/conventions/registry.py
iter_endpoints
def iter_endpoints(graph, match_func): """ Iterate through matching endpoints. The `match_func` is expected to have a signature of: def matches(operation, ns, rule): return True :returns: a generator over (`Operation`, `Namespace`, rule, func) tuples. """ for rule in graph.flask.url_map.iter_rules(): try: operation, ns = Namespace.parse_endpoint(rule.endpoint, get_converter(rule)) except (IndexError, ValueError, InternalServerError): # operation follows a different convention (e.g. "static") continue else: # match_func gets access to rule to support path version filtering if match_func(operation, ns, rule): func = graph.flask.view_functions[rule.endpoint] yield operation, ns, rule, func
python
def iter_endpoints(graph, match_func): """ Iterate through matching endpoints. The `match_func` is expected to have a signature of: def matches(operation, ns, rule): return True :returns: a generator over (`Operation`, `Namespace`, rule, func) tuples. """ for rule in graph.flask.url_map.iter_rules(): try: operation, ns = Namespace.parse_endpoint(rule.endpoint, get_converter(rule)) except (IndexError, ValueError, InternalServerError): # operation follows a different convention (e.g. "static") continue else: # match_func gets access to rule to support path version filtering if match_func(operation, ns, rule): func = graph.flask.view_functions[rule.endpoint] yield operation, ns, rule, func
[ "def", "iter_endpoints", "(", "graph", ",", "match_func", ")", ":", "for", "rule", "in", "graph", ".", "flask", ".", "url_map", ".", "iter_rules", "(", ")", ":", "try", ":", "operation", ",", "ns", "=", "Namespace", ".", "parse_endpoint", "(", "rule", ...
Iterate through matching endpoints. The `match_func` is expected to have a signature of: def matches(operation, ns, rule): return True :returns: a generator over (`Operation`, `Namespace`, rule, func) tuples.
[ "Iterate", "through", "matching", "endpoints", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L16-L38
train
26,319
globality-corp/microcosm-flask
microcosm_flask/conventions/registry.py
get_converter
def get_converter(rule): """ Parse rule will extract the converter from the rule as a generator We iterate through the parse_rule results to find the converter parse_url returns the static rule part in the first iteration parse_url returns the dynamic rule part in the second iteration if its dynamic """ for converter, _, _ in parse_rule(str(rule)): if converter is not None: return converter return None
python
def get_converter(rule): """ Parse rule will extract the converter from the rule as a generator We iterate through the parse_rule results to find the converter parse_url returns the static rule part in the first iteration parse_url returns the dynamic rule part in the second iteration if its dynamic """ for converter, _, _ in parse_rule(str(rule)): if converter is not None: return converter return None
[ "def", "get_converter", "(", "rule", ")", ":", "for", "converter", ",", "_", ",", "_", "in", "parse_rule", "(", "str", "(", "rule", ")", ")", ":", "if", "converter", "is", "not", "None", ":", "return", "converter", "return", "None" ]
Parse rule will extract the converter from the rule as a generator We iterate through the parse_rule results to find the converter parse_url returns the static rule part in the first iteration parse_url returns the dynamic rule part in the second iteration if its dynamic
[ "Parse", "rule", "will", "extract", "the", "converter", "from", "the", "rule", "as", "a", "generator" ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L41-L53
train
26,320
globality-corp/microcosm-flask
microcosm_flask/conventions/registry.py
request
def request(schema): """ Decorate a function with a request schema. """ def wrapper(func): setattr(func, REQUEST, schema) return func return wrapper
python
def request(schema): """ Decorate a function with a request schema. """ def wrapper(func): setattr(func, REQUEST, schema) return func return wrapper
[ "def", "request", "(", "schema", ")", ":", "def", "wrapper", "(", "func", ")", ":", "setattr", "(", "func", ",", "REQUEST", ",", "schema", ")", "return", "func", "return", "wrapper" ]
Decorate a function with a request schema.
[ "Decorate", "a", "function", "with", "a", "request", "schema", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L56-L64
train
26,321
globality-corp/microcosm-flask
microcosm_flask/conventions/registry.py
response
def response(schema): """ Decorate a function with a response schema. """ def wrapper(func): setattr(func, RESPONSE, schema) return func return wrapper
python
def response(schema): """ Decorate a function with a response schema. """ def wrapper(func): setattr(func, RESPONSE, schema) return func return wrapper
[ "def", "response", "(", "schema", ")", ":", "def", "wrapper", "(", "func", ")", ":", "setattr", "(", "func", ",", "RESPONSE", ",", "schema", ")", "return", "func", "return", "wrapper" ]
Decorate a function with a response schema.
[ "Decorate", "a", "function", "with", "a", "response", "schema", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L67-L75
train
26,322
globality-corp/microcosm-flask
microcosm_flask/conventions/registry.py
qs
def qs(schema): """ Decorate a function with a query string schema. """ def wrapper(func): setattr(func, QS, schema) return func return wrapper
python
def qs(schema): """ Decorate a function with a query string schema. """ def wrapper(func): setattr(func, QS, schema) return func return wrapper
[ "def", "qs", "(", "schema", ")", ":", "def", "wrapper", "(", "func", ")", ":", "setattr", "(", "func", ",", "QS", ",", "schema", ")", "return", "func", "return", "wrapper" ]
Decorate a function with a query string schema.
[ "Decorate", "a", "function", "with", "a", "query", "string", "schema", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L78-L86
train
26,323
globality-corp/microcosm-flask
microcosm_flask/audit.py
should_skip_logging
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
python
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
[ "def", "should_skip_logging", "(", "func", ")", ":", "disabled", "=", "strtobool", "(", "request", ".", "headers", ".", "get", "(", "\"x-request-nolog\"", ",", "\"false\"", ")", ")", "return", "disabled", "or", "getattr", "(", "func", ",", "SKIP_LOGGING", ",...
Should we skip logging for this handler?
[ "Should", "we", "skip", "logging", "for", "this", "handler?" ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L59-L65
train
26,324
globality-corp/microcosm-flask
microcosm_flask/audit.py
logging_levels
def logging_levels(): """ Context manager to conditionally set logging levels. Supports setting per-request debug logging using the `X-Request-Debug` header. """ enabled = strtobool(request.headers.get("x-request-debug", "false")) level = None try: if enabled: level = getLogger().getEffectiveLevel() getLogger().setLevel(DEBUG) yield finally: if enabled: getLogger().setLevel(level)
python
def logging_levels(): """ Context manager to conditionally set logging levels. Supports setting per-request debug logging using the `X-Request-Debug` header. """ enabled = strtobool(request.headers.get("x-request-debug", "false")) level = None try: if enabled: level = getLogger().getEffectiveLevel() getLogger().setLevel(DEBUG) yield finally: if enabled: getLogger().setLevel(level)
[ "def", "logging_levels", "(", ")", ":", "enabled", "=", "strtobool", "(", "request", ".", "headers", ".", "get", "(", "\"x-request-debug\"", ",", "\"false\"", ")", ")", "level", "=", "None", "try", ":", "if", "enabled", ":", "level", "=", "getLogger", "(...
Context manager to conditionally set logging levels. Supports setting per-request debug logging using the `X-Request-Debug` header.
[ "Context", "manager", "to", "conditionally", "set", "logging", "levels", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L69-L85
train
26,325
globality-corp/microcosm-flask
microcosm_flask/audit.py
audit
def audit(func): """ Record a Flask route function in the audit log. Generates a JSON record in the Flask log for every request. """ @wraps(func) def wrapper(*args, **kwargs): options = AuditOptions( include_request_body=DEFAULT_INCLUDE_REQUEST_BODY, include_response_body=DEFAULT_INCLUDE_RESPONSE_BODY, include_path=True, include_query_string=True, ) with logging_levels(): return _audit_request(options, func, None, *args, **kwargs) return wrapper
python
def audit(func): """ Record a Flask route function in the audit log. Generates a JSON record in the Flask log for every request. """ @wraps(func) def wrapper(*args, **kwargs): options = AuditOptions( include_request_body=DEFAULT_INCLUDE_REQUEST_BODY, include_response_body=DEFAULT_INCLUDE_RESPONSE_BODY, include_path=True, include_query_string=True, ) with logging_levels(): return _audit_request(options, func, None, *args, **kwargs) return wrapper
[ "def", "audit", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "options", "=", "AuditOptions", "(", "include_request_body", "=", "DEFAULT_INCLUDE_REQUEST_BODY", ",", "include_re...
Record a Flask route function in the audit log. Generates a JSON record in the Flask log for every request.
[ "Record", "a", "Flask", "route", "function", "in", "the", "audit", "log", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L88-L106
train
26,326
globality-corp/microcosm-flask
microcosm_flask/audit.py
_audit_request
def _audit_request(options, func, request_context, *args, **kwargs): # noqa: C901 """ Run a request function under audit. """ logger = getLogger("audit") request_info = RequestInfo(options, func, request_context) response = None request_info.capture_request() try: # process the request with elapsed_time(request_info.timing): response = func(*args, **kwargs) except Exception as error: request_info.capture_error(error) raise else: request_info.capture_response(response) return response finally: if not should_skip_logging(func): request_info.log(logger)
python
def _audit_request(options, func, request_context, *args, **kwargs): # noqa: C901 """ Run a request function under audit. """ logger = getLogger("audit") request_info = RequestInfo(options, func, request_context) response = None request_info.capture_request() try: # process the request with elapsed_time(request_info.timing): response = func(*args, **kwargs) except Exception as error: request_info.capture_error(error) raise else: request_info.capture_response(response) return response finally: if not should_skip_logging(func): request_info.log(logger)
[ "def", "_audit_request", "(", "options", ",", "func", ",", "request_context", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# noqa: C901", "logger", "=", "getLogger", "(", "\"audit\"", ")", "request_info", "=", "RequestInfo", "(", "options", ",", "...
Run a request function under audit.
[ "Run", "a", "request", "function", "under", "audit", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L309-L332
train
26,327
globality-corp/microcosm-flask
microcosm_flask/audit.py
parse_response
def parse_response(response): """ Parse a Flask response into a body, a status code, and headers The returned value from a Flask view could be: * a tuple of (response, status) or (response, status, headers) * a Response object * a string """ if isinstance(response, tuple): if len(response) > 2: return response[0], response[1], response[2] elif len(response) > 1: return response[0], response[1], {} try: return response.data, response.status_code, response.headers except AttributeError: return response, 200, {}
python
def parse_response(response): """ Parse a Flask response into a body, a status code, and headers The returned value from a Flask view could be: * a tuple of (response, status) or (response, status, headers) * a Response object * a string """ if isinstance(response, tuple): if len(response) > 2: return response[0], response[1], response[2] elif len(response) > 1: return response[0], response[1], {} try: return response.data, response.status_code, response.headers except AttributeError: return response, 200, {}
[ "def", "parse_response", "(", "response", ")", ":", "if", "isinstance", "(", "response", ",", "tuple", ")", ":", "if", "len", "(", "response", ")", ">", "2", ":", "return", "response", "[", "0", "]", ",", "response", "[", "1", "]", ",", "response", ...
Parse a Flask response into a body, a status code, and headers The returned value from a Flask view could be: * a tuple of (response, status) or (response, status, headers) * a Response object * a string
[ "Parse", "a", "Flask", "response", "into", "a", "body", "a", "status", "code", "and", "headers" ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L335-L352
train
26,328
globality-corp/microcosm-flask
microcosm_flask/audit.py
configure_audit_decorator
def configure_audit_decorator(graph): """ Configure the audit decorator. Example Usage: @graph.audit def login(username, password): ... """ include_request_body = int(graph.config.audit.include_request_body) include_response_body = int(graph.config.audit.include_response_body) include_path = strtobool(graph.config.audit.include_path) include_query_string = strtobool(graph.config.audit.include_query_string) def _audit(func): @wraps(func) def wrapper(*args, **kwargs): options = AuditOptions( include_request_body=include_request_body, include_response_body=include_response_body, include_path=include_path, include_query_string=include_query_string, ) return _audit_request(options, func, graph.request_context, *args, **kwargs) return wrapper return _audit
python
def configure_audit_decorator(graph): """ Configure the audit decorator. Example Usage: @graph.audit def login(username, password): ... """ include_request_body = int(graph.config.audit.include_request_body) include_response_body = int(graph.config.audit.include_response_body) include_path = strtobool(graph.config.audit.include_path) include_query_string = strtobool(graph.config.audit.include_query_string) def _audit(func): @wraps(func) def wrapper(*args, **kwargs): options = AuditOptions( include_request_body=include_request_body, include_response_body=include_response_body, include_path=include_path, include_query_string=include_query_string, ) return _audit_request(options, func, graph.request_context, *args, **kwargs) return wrapper return _audit
[ "def", "configure_audit_decorator", "(", "graph", ")", ":", "include_request_body", "=", "int", "(", "graph", ".", "config", ".", "audit", ".", "include_request_body", ")", "include_response_body", "=", "int", "(", "graph", ".", "config", ".", "audit", ".", "i...
Configure the audit decorator. Example Usage: @graph.audit def login(username, password): ...
[ "Configure", "the", "audit", "decorator", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L361-L387
train
26,329
globality-corp/microcosm-flask
microcosm_flask/routing.py
configure_route_decorator
def configure_route_decorator(graph): """ Configure a flask route decorator that operates on `Operation` and `Namespace` objects. By default, enables CORS support, assuming that service APIs are not exposed directly to browsers except when using API browsing tools. Usage: @graph.route(ns.collection_path, Operation.Search, ns) def search_foo(): pass """ enable_audit = graph.config.route.enable_audit enable_basic_auth = graph.config.route.enable_basic_auth enable_context_logger = graph.config.route.enable_context_logger enable_cors = graph.config.route.enable_cors # routes depends on converters graph.use(*graph.config.route.converters) def route(path, operation, ns): """ :param path: a URI path, possibly derived from a property of the `ns` :param operation: an `Operation` enum value :param ns: a `Namespace` instance """ def decorator(func): endpoint = ns.endpoint_for(operation) endpoint_path = graph.build_route_path(path, ns.prefix) if enable_cors: func = cross_origin(supports_credentials=True)(func) if enable_basic_auth or ns.enable_basic_auth: func = graph.basic_auth.required(func) if enable_context_logger and ns.controller is not None: func = context_logger( graph.request_context, func, parent=ns.controller, ) # set the opaque component data_func to look at the flask request context func = graph.opaque.initialize(graph.request_context)(func) if graph.route_metrics.enabled: func = graph.route_metrics(endpoint)(func) # keep audit decoration last (before registering the route) so that # errors raised by other decorators are captured in the audit trail if enable_audit: func = graph.audit(func) graph.app.route( endpoint_path, endpoint=endpoint, methods=[operation.value.method], )(func) return func return decorator return route
python
def configure_route_decorator(graph): """ Configure a flask route decorator that operates on `Operation` and `Namespace` objects. By default, enables CORS support, assuming that service APIs are not exposed directly to browsers except when using API browsing tools. Usage: @graph.route(ns.collection_path, Operation.Search, ns) def search_foo(): pass """ enable_audit = graph.config.route.enable_audit enable_basic_auth = graph.config.route.enable_basic_auth enable_context_logger = graph.config.route.enable_context_logger enable_cors = graph.config.route.enable_cors # routes depends on converters graph.use(*graph.config.route.converters) def route(path, operation, ns): """ :param path: a URI path, possibly derived from a property of the `ns` :param operation: an `Operation` enum value :param ns: a `Namespace` instance """ def decorator(func): endpoint = ns.endpoint_for(operation) endpoint_path = graph.build_route_path(path, ns.prefix) if enable_cors: func = cross_origin(supports_credentials=True)(func) if enable_basic_auth or ns.enable_basic_auth: func = graph.basic_auth.required(func) if enable_context_logger and ns.controller is not None: func = context_logger( graph.request_context, func, parent=ns.controller, ) # set the opaque component data_func to look at the flask request context func = graph.opaque.initialize(graph.request_context)(func) if graph.route_metrics.enabled: func = graph.route_metrics(endpoint)(func) # keep audit decoration last (before registering the route) so that # errors raised by other decorators are captured in the audit trail if enable_audit: func = graph.audit(func) graph.app.route( endpoint_path, endpoint=endpoint, methods=[operation.value.method], )(func) return func return decorator return route
[ "def", "configure_route_decorator", "(", "graph", ")", ":", "enable_audit", "=", "graph", ".", "config", ".", "route", ".", "enable_audit", "enable_basic_auth", "=", "graph", ".", "config", ".", "route", ".", "enable_basic_auth", "enable_context_logger", "=", "gra...
Configure a flask route decorator that operates on `Operation` and `Namespace` objects. By default, enables CORS support, assuming that service APIs are not exposed directly to browsers except when using API browsing tools. Usage: @graph.route(ns.collection_path, Operation.Search, ns) def search_foo(): pass
[ "Configure", "a", "flask", "route", "decorator", "that", "operates", "on", "Operation", "and", "Namespace", "objects", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/routing.py#L22-L86
train
26,330
globality-corp/microcosm-flask
microcosm_flask/errors.py
extract_status_code
def extract_status_code(error): """ Extract an error code from a message. """ try: return int(error.code) except (AttributeError, TypeError, ValueError): try: return int(error.status_code) except (AttributeError, TypeError, ValueError): try: return int(error.errno) except (AttributeError, TypeError, ValueError): return 500
python
def extract_status_code(error): """ Extract an error code from a message. """ try: return int(error.code) except (AttributeError, TypeError, ValueError): try: return int(error.status_code) except (AttributeError, TypeError, ValueError): try: return int(error.errno) except (AttributeError, TypeError, ValueError): return 500
[ "def", "extract_status_code", "(", "error", ")", ":", "try", ":", "return", "int", "(", "error", ".", "code", ")", "except", "(", "AttributeError", ",", "TypeError", ",", "ValueError", ")", ":", "try", ":", "return", "int", "(", "error", ".", "status_cod...
Extract an error code from a message.
[ "Extract", "an", "error", "code", "from", "a", "message", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L42-L56
train
26,331
globality-corp/microcosm-flask
microcosm_flask/errors.py
extract_error_message
def extract_error_message(error): """ Extract a useful message from an error. Prefer the description attribute, then the message attribute, then the errors string conversion. In each case, fall back to the error class's name in the event that the attribute value was set to a uselessly empty string. """ try: return error.description or error.__class__.__name__ except AttributeError: try: return str(error.message) or error.__class__.__name__ except AttributeError: return str(error) or error.__class__.__name__
python
def extract_error_message(error): """ Extract a useful message from an error. Prefer the description attribute, then the message attribute, then the errors string conversion. In each case, fall back to the error class's name in the event that the attribute value was set to a uselessly empty string. """ try: return error.description or error.__class__.__name__ except AttributeError: try: return str(error.message) or error.__class__.__name__ except AttributeError: return str(error) or error.__class__.__name__
[ "def", "extract_error_message", "(", "error", ")", ":", "try", ":", "return", "error", ".", "description", "or", "error", ".", "__class__", ".", "__name__", "except", "AttributeError", ":", "try", ":", "return", "str", "(", "error", ".", "message", ")", "o...
Extract a useful message from an error. Prefer the description attribute, then the message attribute, then the errors string conversion. In each case, fall back to the error class's name in the event that the attribute value was set to a uselessly empty string.
[ "Extract", "a", "useful", "message", "from", "an", "error", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L59-L74
train
26,332
globality-corp/microcosm-flask
microcosm_flask/errors.py
make_json_error
def make_json_error(error): """ Handle errors by logging and """ message = extract_error_message(error) status_code = extract_status_code(error) context = extract_context(error) retryable = extract_retryable(error) headers = extract_headers(error) # Flask will not log user exception (fortunately), but will log an error # for exceptions that escape out of the application entirely (e.g. if the # error handler raises an error) error_logger.debug("Handling {} error: {}".format( status_code, message, )) # Serialize into JSON response response_data = { "code": status_code, "context": context, "message": message, "retryable": retryable, } # Don't pass in the error schema because it will suppress any extra fields return dump_response_data(None, response_data, status_code, headers)
python
def make_json_error(error): """ Handle errors by logging and """ message = extract_error_message(error) status_code = extract_status_code(error) context = extract_context(error) retryable = extract_retryable(error) headers = extract_headers(error) # Flask will not log user exception (fortunately), but will log an error # for exceptions that escape out of the application entirely (e.g. if the # error handler raises an error) error_logger.debug("Handling {} error: {}".format( status_code, message, )) # Serialize into JSON response response_data = { "code": status_code, "context": context, "message": message, "retryable": retryable, } # Don't pass in the error schema because it will suppress any extra fields return dump_response_data(None, response_data, status_code, headers)
[ "def", "make_json_error", "(", "error", ")", ":", "message", "=", "extract_error_message", "(", "error", ")", "status_code", "=", "extract_status_code", "(", "error", ")", "context", "=", "extract_context", "(", "error", ")", "retryable", "=", "extract_retryable",...
Handle errors by logging and
[ "Handle", "errors", "by", "logging", "and" ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L121-L147
train
26,333
globality-corp/microcosm-flask
microcosm_flask/errors.py
configure_error_handlers
def configure_error_handlers(graph): """ Register error handlers. """ # override all of the werkzeug HTTPExceptions for code in default_exceptions.keys(): graph.flask.register_error_handler(code, make_json_error) # register catch all for user exceptions graph.flask.register_error_handler(Exception, make_json_error)
python
def configure_error_handlers(graph): """ Register error handlers. """ # override all of the werkzeug HTTPExceptions for code in default_exceptions.keys(): graph.flask.register_error_handler(code, make_json_error) # register catch all for user exceptions graph.flask.register_error_handler(Exception, make_json_error)
[ "def", "configure_error_handlers", "(", "graph", ")", ":", "# override all of the werkzeug HTTPExceptions", "for", "code", "in", "default_exceptions", ".", "keys", "(", ")", ":", "graph", ".", "flask", ".", "register_error_handler", "(", "code", ",", "make_json_error"...
Register error handlers.
[ "Register", "error", "handlers", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L150-L160
train
26,334
GetmeUK/MongoFrames
mongoframes/frames.py
_BaseFrame.to_json_type
def to_json_type(self): """ Return a dictionary for the document with values converted to JSON safe types. """ document_dict = self._json_safe(self._document) self._remove_keys(document_dict, self._private_fields) return document_dict
python
def to_json_type(self): """ Return a dictionary for the document with values converted to JSON safe types. """ document_dict = self._json_safe(self._document) self._remove_keys(document_dict, self._private_fields) return document_dict
[ "def", "to_json_type", "(", "self", ")", ":", "document_dict", "=", "self", ".", "_json_safe", "(", "self", ".", "_document", ")", "self", ".", "_remove_keys", "(", "document_dict", ",", "self", ".", "_private_fields", ")", "return", "document_dict" ]
Return a dictionary for the document with values converted to JSON safe types.
[ "Return", "a", "dictionary", "for", "the", "document", "with", "values", "converted", "to", "JSON", "safe", "types", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L56-L63
train
26,335
GetmeUK/MongoFrames
mongoframes/frames.py
_BaseFrame._json_safe
def _json_safe(cls, value): """Return a JSON safe value""" # Date if type(value) == date: return str(value) # Datetime elif type(value) == datetime: return value.strftime('%Y-%m-%d %H:%M:%S') # Object Id elif isinstance(value, ObjectId): return str(value) # Frame elif isinstance(value, _BaseFrame): return value.to_json_type() # Lists elif isinstance(value, (list, tuple)): return [cls._json_safe(v) for v in value] # Dictionaries elif isinstance(value, dict): return {k:cls._json_safe(v) for k, v in value.items()} return value
python
def _json_safe(cls, value): """Return a JSON safe value""" # Date if type(value) == date: return str(value) # Datetime elif type(value) == datetime: return value.strftime('%Y-%m-%d %H:%M:%S') # Object Id elif isinstance(value, ObjectId): return str(value) # Frame elif isinstance(value, _BaseFrame): return value.to_json_type() # Lists elif isinstance(value, (list, tuple)): return [cls._json_safe(v) for v in value] # Dictionaries elif isinstance(value, dict): return {k:cls._json_safe(v) for k, v in value.items()} return value
[ "def", "_json_safe", "(", "cls", ",", "value", ")", ":", "# Date", "if", "type", "(", "value", ")", "==", "date", ":", "return", "str", "(", "value", ")", "# Datetime", "elif", "type", "(", "value", ")", "==", "datetime", ":", "return", "value", ".",...
Return a JSON safe value
[ "Return", "a", "JSON", "safe", "value" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L66-L92
train
26,336
GetmeUK/MongoFrames
mongoframes/frames.py
_BaseFrame._path_to_keys
def _path_to_keys(cls, path): """Return a list of keys for a given path""" # Paths are cached for performance keys = _BaseFrame._path_to_keys_cache.get(path) if keys is None: keys = _BaseFrame._path_to_keys_cache[path] = path.split('.') return keys
python
def _path_to_keys(cls, path): """Return a list of keys for a given path""" # Paths are cached for performance keys = _BaseFrame._path_to_keys_cache.get(path) if keys is None: keys = _BaseFrame._path_to_keys_cache[path] = path.split('.') return keys
[ "def", "_path_to_keys", "(", "cls", ",", "path", ")", ":", "# Paths are cached for performance", "keys", "=", "_BaseFrame", ".", "_path_to_keys_cache", ".", "get", "(", "path", ")", "if", "keys", "is", "None", ":", "keys", "=", "_BaseFrame", ".", "_path_to_key...
Return a list of keys for a given path
[ "Return", "a", "list", "of", "keys", "for", "a", "given", "path" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L95-L103
train
26,337
GetmeUK/MongoFrames
mongoframes/frames.py
_BaseFrame._path_to_value
def _path_to_value(cls, path, parent_dict): """Return a value from a dictionary at the given path""" keys = cls._path_to_keys(path) # Traverse to the tip of the path child_dict = parent_dict for key in keys[:-1]: child_dict = child_dict.get(key) if child_dict is None: return return child_dict.get(keys[-1])
python
def _path_to_value(cls, path, parent_dict): """Return a value from a dictionary at the given path""" keys = cls._path_to_keys(path) # Traverse to the tip of the path child_dict = parent_dict for key in keys[:-1]: child_dict = child_dict.get(key) if child_dict is None: return return child_dict.get(keys[-1])
[ "def", "_path_to_value", "(", "cls", ",", "path", ",", "parent_dict", ")", ":", "keys", "=", "cls", ".", "_path_to_keys", "(", "path", ")", "# Traverse to the tip of the path", "child_dict", "=", "parent_dict", "for", "key", "in", "keys", "[", ":", "-", "1",...
Return a value from a dictionary at the given path
[ "Return", "a", "value", "from", "a", "dictionary", "at", "the", "given", "path" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L106-L117
train
26,338
GetmeUK/MongoFrames
mongoframes/frames.py
_BaseFrame._remove_keys
def _remove_keys(cls, parent_dict, paths): """ Remove a list of keys from a dictionary. Keys are specified as a series of `.` separated paths for keys in child dictionaries, e.g 'parent_key.child_key.grandchild_key'. """ for path in paths: keys = cls._path_to_keys(path) # Traverse to the tip of the path child_dict = parent_dict for key in keys[:-1]: child_dict = child_dict.get(key) if child_dict is None: break if child_dict is None: continue # Remove the key if keys[-1] in child_dict: child_dict.pop(keys[-1])
python
def _remove_keys(cls, parent_dict, paths): """ Remove a list of keys from a dictionary. Keys are specified as a series of `.` separated paths for keys in child dictionaries, e.g 'parent_key.child_key.grandchild_key'. """ for path in paths: keys = cls._path_to_keys(path) # Traverse to the tip of the path child_dict = parent_dict for key in keys[:-1]: child_dict = child_dict.get(key) if child_dict is None: break if child_dict is None: continue # Remove the key if keys[-1] in child_dict: child_dict.pop(keys[-1])
[ "def", "_remove_keys", "(", "cls", ",", "parent_dict", ",", "paths", ")", ":", "for", "path", "in", "paths", ":", "keys", "=", "cls", ".", "_path_to_keys", "(", "path", ")", "# Traverse to the tip of the path", "child_dict", "=", "parent_dict", "for", "key", ...
Remove a list of keys from a dictionary. Keys are specified as a series of `.` separated paths for keys in child dictionaries, e.g 'parent_key.child_key.grandchild_key'.
[ "Remove", "a", "list", "of", "keys", "from", "a", "dictionary", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L120-L144
train
26,339
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.insert
def insert(self): """Insert this document""" from mongoframes.queries import to_refs # Send insert signal signal('insert').send(self.__class__, frames=[self]) # Prepare the document to be inserted document = to_refs(self._document) # Insert the document and update the Id self._id = self.get_collection().insert_one(document).inserted_id # Send inserted signal signal('inserted').send(self.__class__, frames=[self])
python
def insert(self): """Insert this document""" from mongoframes.queries import to_refs # Send insert signal signal('insert').send(self.__class__, frames=[self]) # Prepare the document to be inserted document = to_refs(self._document) # Insert the document and update the Id self._id = self.get_collection().insert_one(document).inserted_id # Send inserted signal signal('inserted').send(self.__class__, frames=[self])
[ "def", "insert", "(", "self", ")", ":", "from", "mongoframes", ".", "queries", "import", "to_refs", "# Send insert signal", "signal", "(", "'insert'", ")", ".", "send", "(", "self", ".", "__class__", ",", "frames", "=", "[", "self", "]", ")", "# Prepare th...
Insert this document
[ "Insert", "this", "document" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L218-L232
train
26,340
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.update
def update(self, *fields): """ Update this document. Optionally a specific list of fields to update can be specified. """ from mongoframes.queries import to_refs assert '_id' in self._document, "Can't update documents without `_id`" # Send update signal signal('update').send(self.__class__, frames=[self]) # Check for selective updates if len(fields) > 0: document = {} for field in fields: document[field] = self._path_to_value(field, self._document) else: document = self._document # Prepare the document to be updated document = to_refs(document) document.pop('_id', None) # Update the document self.get_collection().update_one({'_id': self._id}, {'$set': document}) # Send updated signal signal('updated').send(self.__class__, frames=[self])
python
def update(self, *fields): """ Update this document. Optionally a specific list of fields to update can be specified. """ from mongoframes.queries import to_refs assert '_id' in self._document, "Can't update documents without `_id`" # Send update signal signal('update').send(self.__class__, frames=[self]) # Check for selective updates if len(fields) > 0: document = {} for field in fields: document[field] = self._path_to_value(field, self._document) else: document = self._document # Prepare the document to be updated document = to_refs(document) document.pop('_id', None) # Update the document self.get_collection().update_one({'_id': self._id}, {'$set': document}) # Send updated signal signal('updated').send(self.__class__, frames=[self])
[ "def", "update", "(", "self", ",", "*", "fields", ")", ":", "from", "mongoframes", ".", "queries", "import", "to_refs", "assert", "'_id'", "in", "self", ".", "_document", ",", "\"Can't update documents without `_id`\"", "# Send update signal", "signal", "(", "'upd...
Update this document. Optionally a specific list of fields to update can be specified.
[ "Update", "this", "document", ".", "Optionally", "a", "specific", "list", "of", "fields", "to", "update", "can", "be", "specified", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L234-L262
train
26,341
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.upsert
def upsert(self, *fields): """ Update or Insert this document depending on whether it exists or not. The presense of an `_id` value in the document is used to determine if the document exists. NOTE: This method is not the same as specifying the `upsert` flag when calling MongoDB. When called for a document with an `_id` value, this method will call the database to see if a record with that Id exists, if not it will call `insert`, if so it will call `update`. This operation is therefore not atomic and much slower than the equivalent MongoDB operation (due to the extra call). """ # If no `_id` is provided then we insert the document if not self._id: return self.insert() # If an `_id` is provided then we need to check if it exists before # performing the `upsert`. # if self.count({'_id': self._id}) == 0: self.insert() else: self.update(*fields)
python
def upsert(self, *fields): """ Update or Insert this document depending on whether it exists or not. The presense of an `_id` value in the document is used to determine if the document exists. NOTE: This method is not the same as specifying the `upsert` flag when calling MongoDB. When called for a document with an `_id` value, this method will call the database to see if a record with that Id exists, if not it will call `insert`, if so it will call `update`. This operation is therefore not atomic and much slower than the equivalent MongoDB operation (due to the extra call). """ # If no `_id` is provided then we insert the document if not self._id: return self.insert() # If an `_id` is provided then we need to check if it exists before # performing the `upsert`. # if self.count({'_id': self._id}) == 0: self.insert() else: self.update(*fields)
[ "def", "upsert", "(", "self", ",", "*", "fields", ")", ":", "# If no `_id` is provided then we insert the document", "if", "not", "self", ".", "_id", ":", "return", "self", ".", "insert", "(", ")", "# If an `_id` is provided then we need to check if it exists before", "...
Update or Insert this document depending on whether it exists or not. The presense of an `_id` value in the document is used to determine if the document exists. NOTE: This method is not the same as specifying the `upsert` flag when calling MongoDB. When called for a document with an `_id` value, this method will call the database to see if a record with that Id exists, if not it will call `insert`, if so it will call `update`. This operation is therefore not atomic and much slower than the equivalent MongoDB operation (due to the extra call).
[ "Update", "or", "Insert", "this", "document", "depending", "on", "whether", "it", "exists", "or", "not", ".", "The", "presense", "of", "an", "_id", "value", "in", "the", "document", "is", "used", "to", "determine", "if", "the", "document", "exists", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L264-L288
train
26,342
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.delete
def delete(self): """Delete this document""" assert '_id' in self._document, "Can't delete documents without `_id`" # Send delete signal signal('delete').send(self.__class__, frames=[self]) # Delete the document self.get_collection().delete_one({'_id': self._id}) # Send deleted signal signal('deleted').send(self.__class__, frames=[self])
python
def delete(self): """Delete this document""" assert '_id' in self._document, "Can't delete documents without `_id`" # Send delete signal signal('delete').send(self.__class__, frames=[self]) # Delete the document self.get_collection().delete_one({'_id': self._id}) # Send deleted signal signal('deleted').send(self.__class__, frames=[self])
[ "def", "delete", "(", "self", ")", ":", "assert", "'_id'", "in", "self", ".", "_document", ",", "\"Can't delete documents without `_id`\"", "# Send delete signal", "signal", "(", "'delete'", ")", ".", "send", "(", "self", ".", "__class__", ",", "frames", "=", ...
Delete this document
[ "Delete", "this", "document" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L290-L302
train
26,343
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.insert_many
def insert_many(cls, documents): """Insert a list of documents""" from mongoframes.queries import to_refs # Ensure all documents have been converted to frames frames = cls._ensure_frames(documents) # Send insert signal signal('insert').send(cls, frames=frames) # Prepare the documents to be inserted documents = [to_refs(f._document) for f in frames] # Bulk insert ids = cls.get_collection().insert_many(documents).inserted_ids # Apply the Ids to the frames for i, id in enumerate(ids): frames[i]._id = id # Send inserted signal signal('inserted').send(cls, frames=frames) return frames
python
def insert_many(cls, documents): """Insert a list of documents""" from mongoframes.queries import to_refs # Ensure all documents have been converted to frames frames = cls._ensure_frames(documents) # Send insert signal signal('insert').send(cls, frames=frames) # Prepare the documents to be inserted documents = [to_refs(f._document) for f in frames] # Bulk insert ids = cls.get_collection().insert_many(documents).inserted_ids # Apply the Ids to the frames for i, id in enumerate(ids): frames[i]._id = id # Send inserted signal signal('inserted').send(cls, frames=frames) return frames
[ "def", "insert_many", "(", "cls", ",", "documents", ")", ":", "from", "mongoframes", ".", "queries", "import", "to_refs", "# Ensure all documents have been converted to frames", "frames", "=", "cls", ".", "_ensure_frames", "(", "documents", ")", "# Send insert signal", ...
Insert a list of documents
[ "Insert", "a", "list", "of", "documents" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L305-L328
train
26,344
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.update_many
def update_many(cls, documents, *fields): """ Update multiple documents. Optionally a specific list of fields to update can be specified. """ from mongoframes.queries import to_refs # Ensure all documents have been converted to frames frames = cls._ensure_frames(documents) all_count = len(documents) assert len([f for f in frames if '_id' in f._document]) == all_count, \ "Can't update documents without `_id`s" # Send update signal signal('update').send(cls, frames=frames) # Prepare the documents to be updated # Check for selective updates if len(fields) > 0: documents = [] for frame in frames: document = {'_id': frame._id} for field in fields: document[field] = cls._path_to_value( field, frame._document ) documents.append(to_refs(document)) else: documents = [to_refs(f._document) for f in frames] # Update the documents for document in documents: _id = document.pop('_id') cls.get_collection().update( {'_id': _id}, {'$set': document}) # Send updated signal signal('updated').send(cls, frames=frames)
python
def update_many(cls, documents, *fields): """ Update multiple documents. Optionally a specific list of fields to update can be specified. """ from mongoframes.queries import to_refs # Ensure all documents have been converted to frames frames = cls._ensure_frames(documents) all_count = len(documents) assert len([f for f in frames if '_id' in f._document]) == all_count, \ "Can't update documents without `_id`s" # Send update signal signal('update').send(cls, frames=frames) # Prepare the documents to be updated # Check for selective updates if len(fields) > 0: documents = [] for frame in frames: document = {'_id': frame._id} for field in fields: document[field] = cls._path_to_value( field, frame._document ) documents.append(to_refs(document)) else: documents = [to_refs(f._document) for f in frames] # Update the documents for document in documents: _id = document.pop('_id') cls.get_collection().update( {'_id': _id}, {'$set': document}) # Send updated signal signal('updated').send(cls, frames=frames)
[ "def", "update_many", "(", "cls", ",", "documents", ",", "*", "fields", ")", ":", "from", "mongoframes", ".", "queries", "import", "to_refs", "# Ensure all documents have been converted to frames", "frames", "=", "cls", ".", "_ensure_frames", "(", "documents", ")", ...
Update multiple documents. Optionally a specific list of fields to update can be specified.
[ "Update", "multiple", "documents", ".", "Optionally", "a", "specific", "list", "of", "fields", "to", "update", "can", "be", "specified", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L331-L371
train
26,345
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.delete_many
def delete_many(cls, documents): """Delete multiple documents""" # Ensure all documents have been converted to frames frames = cls._ensure_frames(documents) all_count = len(documents) assert len([f for f in frames if '_id' in f._document]) == all_count, \ "Can't delete documents without `_id`s" # Send delete signal signal('delete').send(cls, frames=frames) # Prepare the documents to be deleted ids = [f._id for f in frames] # Delete the documents cls.get_collection().delete_many({'_id': {'$in': ids}}) # Send deleted signal signal('deleted').send(cls, frames=frames)
python
def delete_many(cls, documents): """Delete multiple documents""" # Ensure all documents have been converted to frames frames = cls._ensure_frames(documents) all_count = len(documents) assert len([f for f in frames if '_id' in f._document]) == all_count, \ "Can't delete documents without `_id`s" # Send delete signal signal('delete').send(cls, frames=frames) # Prepare the documents to be deleted ids = [f._id for f in frames] # Delete the documents cls.get_collection().delete_many({'_id': {'$in': ids}}) # Send deleted signal signal('deleted').send(cls, frames=frames)
[ "def", "delete_many", "(", "cls", ",", "documents", ")", ":", "# Ensure all documents have been converted to frames", "frames", "=", "cls", ".", "_ensure_frames", "(", "documents", ")", "all_count", "=", "len", "(", "documents", ")", "assert", "len", "(", "[", "...
Delete multiple documents
[ "Delete", "multiple", "documents" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L374-L394
train
26,346
GetmeUK/MongoFrames
mongoframes/frames.py
Frame._ensure_frames
def _ensure_frames(cls, documents): """ Ensure all items in a list are frames by converting those that aren't. """ frames = [] for document in documents: if not isinstance(document, Frame): frames.append(cls(document)) else: frames.append(document) return frames
python
def _ensure_frames(cls, documents): """ Ensure all items in a list are frames by converting those that aren't. """ frames = [] for document in documents: if not isinstance(document, Frame): frames.append(cls(document)) else: frames.append(document) return frames
[ "def", "_ensure_frames", "(", "cls", ",", "documents", ")", ":", "frames", "=", "[", "]", "for", "document", "in", "documents", ":", "if", "not", "isinstance", "(", "document", ",", "Frame", ")", ":", "frames", ".", "append", "(", "cls", "(", "document...
Ensure all items in a list are frames by converting those that aren't.
[ "Ensure", "all", "items", "in", "a", "list", "are", "frames", "by", "converting", "those", "that", "aren", "t", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L397-L407
train
26,347
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.reload
def reload(self, **kwargs): """Reload the document""" frame = self.one({'_id': self._id}, **kwargs) self._document = frame._document
python
def reload(self, **kwargs): """Reload the document""" frame = self.one({'_id': self._id}, **kwargs) self._document = frame._document
[ "def", "reload", "(", "self", ",", "*", "*", "kwargs", ")", ":", "frame", "=", "self", ".", "one", "(", "{", "'_id'", ":", "self", ".", "_id", "}", ",", "*", "*", "kwargs", ")", "self", ".", "_document", "=", "frame", ".", "_document" ]
Reload the document
[ "Reload", "the", "document" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L411-L414
train
26,348
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.count
def count(cls, filter=None, **kwargs): """Return a count of documents matching the filter""" from mongoframes.queries import Condition, Group, to_refs if isinstance(filter, (Condition, Group)): filter = filter.to_dict() return cls.get_collection().count(to_refs(filter), **kwargs)
python
def count(cls, filter=None, **kwargs): """Return a count of documents matching the filter""" from mongoframes.queries import Condition, Group, to_refs if isinstance(filter, (Condition, Group)): filter = filter.to_dict() return cls.get_collection().count(to_refs(filter), **kwargs)
[ "def", "count", "(", "cls", ",", "filter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "mongoframes", ".", "queries", "import", "Condition", ",", "Group", ",", "to_refs", "if", "isinstance", "(", "filter", ",", "(", "Condition", ",", "Group...
Return a count of documents matching the filter
[ "Return", "a", "count", "of", "documents", "matching", "the", "filter" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L422-L429
train
26,349
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.ids
def ids(cls, filter=None, **kwargs): """Return a list of Ids for documents matching the filter""" from mongoframes.queries import Condition, Group, to_refs # Find the documents if isinstance(filter, (Condition, Group)): filter = filter.to_dict() documents = cls.get_collection().find( to_refs(filter), projection={'_id': True}, **kwargs ) return [d['_id'] for d in list(documents)]
python
def ids(cls, filter=None, **kwargs): """Return a list of Ids for documents matching the filter""" from mongoframes.queries import Condition, Group, to_refs # Find the documents if isinstance(filter, (Condition, Group)): filter = filter.to_dict() documents = cls.get_collection().find( to_refs(filter), projection={'_id': True}, **kwargs ) return [d['_id'] for d in list(documents)]
[ "def", "ids", "(", "cls", ",", "filter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "mongoframes", ".", "queries", "import", "Condition", ",", "Group", ",", "to_refs", "# Find the documents", "if", "isinstance", "(", "filter", ",", "(", "Con...
Return a list of Ids for documents matching the filter
[ "Return", "a", "list", "of", "Ids", "for", "documents", "matching", "the", "filter" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L432-L446
train
26,350
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.one
def one(cls, filter=None, **kwargs): """Return the first document matching the filter""" from mongoframes.queries import Condition, Group, to_refs # Flatten the projection kwargs['projection'], references, subs = \ cls._flatten_projection( kwargs.get('projection', cls._default_projection) ) # Find the document if isinstance(filter, (Condition, Group)): filter = filter.to_dict() document = cls.get_collection().find_one(to_refs(filter), **kwargs) # Make sure we found a document if not document: return # Dereference the document (if required) if references: cls._dereference([document], references) # Add sub-frames to the document (if required) if subs: cls._apply_sub_frames([document], subs) return cls(document)
python
def one(cls, filter=None, **kwargs): """Return the first document matching the filter""" from mongoframes.queries import Condition, Group, to_refs # Flatten the projection kwargs['projection'], references, subs = \ cls._flatten_projection( kwargs.get('projection', cls._default_projection) ) # Find the document if isinstance(filter, (Condition, Group)): filter = filter.to_dict() document = cls.get_collection().find_one(to_refs(filter), **kwargs) # Make sure we found a document if not document: return # Dereference the document (if required) if references: cls._dereference([document], references) # Add sub-frames to the document (if required) if subs: cls._apply_sub_frames([document], subs) return cls(document)
[ "def", "one", "(", "cls", ",", "filter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "mongoframes", ".", "queries", "import", "Condition", ",", "Group", ",", "to_refs", "# Flatten the projection", "kwargs", "[", "'projection'", "]", ",", "refer...
Return the first document matching the filter
[ "Return", "the", "first", "document", "matching", "the", "filter" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L449-L477
train
26,351
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.many
def many(cls, filter=None, **kwargs): """Return a list of documents matching the filter""" from mongoframes.queries import Condition, Group, to_refs # Flatten the projection kwargs['projection'], references, subs = \ cls._flatten_projection( kwargs.get('projection', cls._default_projection) ) # Find the documents if isinstance(filter, (Condition, Group)): filter = filter.to_dict() documents = list(cls.get_collection().find(to_refs(filter), **kwargs)) # Dereference the documents (if required) if references: cls._dereference(documents, references) # Add sub-frames to the documents (if required) if subs: cls._apply_sub_frames(documents, subs) return [cls(d) for d in documents]
python
def many(cls, filter=None, **kwargs): """Return a list of documents matching the filter""" from mongoframes.queries import Condition, Group, to_refs # Flatten the projection kwargs['projection'], references, subs = \ cls._flatten_projection( kwargs.get('projection', cls._default_projection) ) # Find the documents if isinstance(filter, (Condition, Group)): filter = filter.to_dict() documents = list(cls.get_collection().find(to_refs(filter), **kwargs)) # Dereference the documents (if required) if references: cls._dereference(documents, references) # Add sub-frames to the documents (if required) if subs: cls._apply_sub_frames(documents, subs) return [cls(d) for d in documents]
[ "def", "many", "(", "cls", ",", "filter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "mongoframes", ".", "queries", "import", "Condition", ",", "Group", ",", "to_refs", "# Flatten the projection", "kwargs", "[", "'projection'", "]", ",", "refe...
Return a list of documents matching the filter
[ "Return", "a", "list", "of", "documents", "matching", "the", "filter" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L480-L504
train
26,352
GetmeUK/MongoFrames
mongoframes/frames.py
Frame._apply_sub_frames
def _apply_sub_frames(cls, documents, subs): """Convert embedded documents to sub-frames for one or more documents""" # Dereference each reference for path, projection in subs.items(): # Get the SubFrame class we'll use to wrap the embedded document sub = None expect_map = False if '$sub' in projection: sub = projection.pop('$sub') elif '$sub.' in projection: sub = projection.pop('$sub.') expect_map = True else: continue # Add sub-frames to the documents raw_subs = [] for document in documents: value = cls._path_to_value(path, document) if value is None: continue if isinstance(value, dict): if expect_map: # Dictionary of embedded documents raw_subs += value.values() for k, v in value.items(): if isinstance(v ,list): value[k] = [ sub(u) for u in v if isinstance(u, dict)] else: value[k] = sub(v) # Single embedded document else: raw_subs.append(value) value = sub(value) elif isinstance(value, list): # List of embedded documents raw_subs += value value = [sub(v) for v in value if isinstance(v, dict)] else: raise TypeError('Not a supported sub-frame type') child_document = document keys = cls._path_to_keys(path) for key in keys[:-1]: child_document = child_document[key] child_document[keys[-1]] = value # Apply the projection to the list of sub frames if projection: sub._apply_projection(raw_subs, projection)
python
def _apply_sub_frames(cls, documents, subs): """Convert embedded documents to sub-frames for one or more documents""" # Dereference each reference for path, projection in subs.items(): # Get the SubFrame class we'll use to wrap the embedded document sub = None expect_map = False if '$sub' in projection: sub = projection.pop('$sub') elif '$sub.' in projection: sub = projection.pop('$sub.') expect_map = True else: continue # Add sub-frames to the documents raw_subs = [] for document in documents: value = cls._path_to_value(path, document) if value is None: continue if isinstance(value, dict): if expect_map: # Dictionary of embedded documents raw_subs += value.values() for k, v in value.items(): if isinstance(v ,list): value[k] = [ sub(u) for u in v if isinstance(u, dict)] else: value[k] = sub(v) # Single embedded document else: raw_subs.append(value) value = sub(value) elif isinstance(value, list): # List of embedded documents raw_subs += value value = [sub(v) for v in value if isinstance(v, dict)] else: raise TypeError('Not a supported sub-frame type') child_document = document keys = cls._path_to_keys(path) for key in keys[:-1]: child_document = child_document[key] child_document[keys[-1]] = value # Apply the projection to the list of sub frames if projection: sub._apply_projection(raw_subs, projection)
[ "def", "_apply_sub_frames", "(", "cls", ",", "documents", ",", "subs", ")", ":", "# Dereference each reference", "for", "path", ",", "projection", "in", "subs", ".", "items", "(", ")", ":", "# Get the SubFrame class we'll use to wrap the embedded document", "sub", "="...
Convert embedded documents to sub-frames for one or more documents
[ "Convert", "embedded", "documents", "to", "sub", "-", "frames", "for", "one", "or", "more", "documents" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L507-L563
train
26,353
GetmeUK/MongoFrames
mongoframes/frames.py
Frame._dereference
def _dereference(cls, documents, references): """Dereference one or more documents""" # Dereference each reference for path, projection in references.items(): # Check there is a $ref in the projection, else skip it if '$ref' not in projection: continue # Collect Ids of documents to dereference ids = set() for document in documents: value = cls._path_to_value(path, document) if not value: continue if isinstance(value, list): ids.update(value) elif isinstance(value, dict): ids.update(value.values()) else: ids.add(value) # Find the referenced documents ref = projection.pop('$ref') frames = ref.many( {'_id': {'$in': list(ids)}}, projection=projection ) frames = {f._id: f for f in frames} # Add dereferenced frames to the document for document in documents: value = cls._path_to_value(path, document) if not value: continue if isinstance(value, list): # List of references value = [frames[id] for id in value if id in frames] elif isinstance(value, dict): # Dictionary of references value = {key: frames.get(id) for key, id in value.items()} else: value = frames.get(value, None) child_document = document keys = cls._path_to_keys(path) for key in keys[:-1]: child_document = child_document[key] child_document[keys[-1]] = value
python
def _dereference(cls, documents, references): """Dereference one or more documents""" # Dereference each reference for path, projection in references.items(): # Check there is a $ref in the projection, else skip it if '$ref' not in projection: continue # Collect Ids of documents to dereference ids = set() for document in documents: value = cls._path_to_value(path, document) if not value: continue if isinstance(value, list): ids.update(value) elif isinstance(value, dict): ids.update(value.values()) else: ids.add(value) # Find the referenced documents ref = projection.pop('$ref') frames = ref.many( {'_id': {'$in': list(ids)}}, projection=projection ) frames = {f._id: f for f in frames} # Add dereferenced frames to the document for document in documents: value = cls._path_to_value(path, document) if not value: continue if isinstance(value, list): # List of references value = [frames[id] for id in value if id in frames] elif isinstance(value, dict): # Dictionary of references value = {key: frames.get(id) for key, id in value.items()} else: value = frames.get(value, None) child_document = document keys = cls._path_to_keys(path) for key in keys[:-1]: child_document = child_document[key] child_document[keys[-1]] = value
[ "def", "_dereference", "(", "cls", ",", "documents", ",", "references", ")", ":", "# Dereference each reference", "for", "path", ",", "projection", "in", "references", ".", "items", "(", ")", ":", "# Check there is a $ref in the projection, else skip it", "if", "'$ref...
Dereference one or more documents
[ "Dereference", "one", "or", "more", "documents" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L566-L621
train
26,354
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.listen
def listen(cls, event, func): """Add a callback for a signal against the class""" signal(event).connect(func, sender=cls)
python
def listen(cls, event, func): """Add a callback for a signal against the class""" signal(event).connect(func, sender=cls)
[ "def", "listen", "(", "cls", ",", "event", ",", "func", ")", ":", "signal", "(", "event", ")", ".", "connect", "(", "func", ",", "sender", "=", "cls", ")" ]
Add a callback for a signal against the class
[ "Add", "a", "callback", "for", "a", "signal", "against", "the", "class" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L754-L756
train
26,355
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.stop_listening
def stop_listening(cls, event, func): """Remove a callback for a signal against the class""" signal(event).disconnect(func, sender=cls)
python
def stop_listening(cls, event, func): """Remove a callback for a signal against the class""" signal(event).disconnect(func, sender=cls)
[ "def", "stop_listening", "(", "cls", ",", "event", ",", "func", ")", ":", "signal", "(", "event", ")", ".", "disconnect", "(", "func", ",", "sender", "=", "cls", ")" ]
Remove a callback for a signal against the class
[ "Remove", "a", "callback", "for", "a", "signal", "against", "the", "class" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L759-L761
train
26,356
GetmeUK/MongoFrames
mongoframes/frames.py
Frame.get_db
def get_db(cls): """Return the database for the collection""" if cls._db: return getattr(cls._client, cls._db) return cls._client.get_default_database()
python
def get_db(cls): """Return the database for the collection""" if cls._db: return getattr(cls._client, cls._db) return cls._client.get_default_database()
[ "def", "get_db", "(", "cls", ")", ":", "if", "cls", ".", "_db", ":", "return", "getattr", "(", "cls", ".", "_client", ",", "cls", ".", "_db", ")", "return", "cls", ".", "_client", ".", "get_default_database", "(", ")" ]
Return the database for the collection
[ "Return", "the", "database", "for", "the", "collection" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L771-L775
train
26,357
GetmeUK/MongoFrames
mongoframes/factory/makers/images.py
ImageURL._default_service_formatter
def _default_service_formatter( service_url, width, height, background, foreground, options ): """Generate an image URL for a service""" # Build the base URL image_tmp = '{service_url}/{width}x{height}/{background}/{foreground}/' image_url = image_tmp.format( service_url=service_url, width=width, height=height, background=background, foreground=foreground ) # Add any options if options: image_url += '?' + urlencode(options) return image_url
python
def _default_service_formatter( service_url, width, height, background, foreground, options ): """Generate an image URL for a service""" # Build the base URL image_tmp = '{service_url}/{width}x{height}/{background}/{foreground}/' image_url = image_tmp.format( service_url=service_url, width=width, height=height, background=background, foreground=foreground ) # Add any options if options: image_url += '?' + urlencode(options) return image_url
[ "def", "_default_service_formatter", "(", "service_url", ",", "width", ",", "height", ",", "background", ",", "foreground", ",", "options", ")", ":", "# Build the base URL", "image_tmp", "=", "'{service_url}/{width}x{height}/{background}/{foreground}/'", "image_url", "=", ...
Generate an image URL for a service
[ "Generate", "an", "image", "URL", "for", "a", "service" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/images.py#L55-L79
train
26,358
GetmeUK/MongoFrames
mongoframes/factory/makers/text.py
Markov._body
def _body(self, paragraphs): """Generate a body of text""" body = [] for i in range(paragraphs): paragraph = self._paragraph(random.randint(1, 10)) body.append(paragraph) return '\n'.join(body)
python
def _body(self, paragraphs): """Generate a body of text""" body = [] for i in range(paragraphs): paragraph = self._paragraph(random.randint(1, 10)) body.append(paragraph) return '\n'.join(body)
[ "def", "_body", "(", "self", ",", "paragraphs", ")", ":", "body", "=", "[", "]", "for", "i", "in", "range", "(", "paragraphs", ")", ":", "paragraph", "=", "self", ".", "_paragraph", "(", "random", ".", "randint", "(", "1", ",", "10", ")", ")", "b...
Generate a body of text
[ "Generate", "a", "body", "of", "text" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/text.py#L193-L200
train
26,359
GetmeUK/MongoFrames
mongoframes/factory/makers/text.py
Markov._paragraph
def _paragraph(self, sentences): """Generate a paragraph""" paragraph = [] for i in range(sentences): sentence = self._sentence(random.randint(5, 16)) paragraph.append(sentence) return ' '.join(paragraph)
python
def _paragraph(self, sentences): """Generate a paragraph""" paragraph = [] for i in range(sentences): sentence = self._sentence(random.randint(5, 16)) paragraph.append(sentence) return ' '.join(paragraph)
[ "def", "_paragraph", "(", "self", ",", "sentences", ")", ":", "paragraph", "=", "[", "]", "for", "i", "in", "range", "(", "sentences", ")", ":", "sentence", "=", "self", ".", "_sentence", "(", "random", ".", "randint", "(", "5", ",", "16", ")", ")"...
Generate a paragraph
[ "Generate", "a", "paragraph" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/text.py#L202-L209
train
26,360
GetmeUK/MongoFrames
mongoframes/factory/makers/text.py
Markov._sentence
def _sentence(self, words): """Generate a sentence""" db = self.database # Generate 2 words to start a sentence with seed = random.randint(0, db['word_count'] - 3) seed_word, next_word = db['words'][seed], db['words'][seed + 1] w1, w2 = seed_word, next_word # Generate the complete sentence sentence = [] for i in range(0, words - 1): sentence.append(w1) w1, w2 = w2, random.choice(db['freqs'][(w1, w2)]) sentence.append(w2) # Make the sentence respectable sentence = ' '.join(sentence) # Capitalize the sentence sentence = sentence.capitalize() # Remove additional sentence ending puntuation sentence = sentence.replace('.', '') sentence = sentence.replace('!', '') sentence = sentence.replace('?', '') sentence = sentence.replace(':', '') # Remove quote tags sentence = sentence.replace('.', '') sentence = sentence.replace('!', '') sentence = sentence.replace('?', '') sentence = sentence.replace(':', '') sentence = sentence.replace('"', '') # If the last character is not an alphanumeric remove it sentence = re.sub('[^a-zA-Z0-9]$', '', sentence) # Remove excess space sentence = re.sub('\s+', ' ', sentence) # Add a full stop sentence += '.' return sentence
python
def _sentence(self, words): """Generate a sentence""" db = self.database # Generate 2 words to start a sentence with seed = random.randint(0, db['word_count'] - 3) seed_word, next_word = db['words'][seed], db['words'][seed + 1] w1, w2 = seed_word, next_word # Generate the complete sentence sentence = [] for i in range(0, words - 1): sentence.append(w1) w1, w2 = w2, random.choice(db['freqs'][(w1, w2)]) sentence.append(w2) # Make the sentence respectable sentence = ' '.join(sentence) # Capitalize the sentence sentence = sentence.capitalize() # Remove additional sentence ending puntuation sentence = sentence.replace('.', '') sentence = sentence.replace('!', '') sentence = sentence.replace('?', '') sentence = sentence.replace(':', '') # Remove quote tags sentence = sentence.replace('.', '') sentence = sentence.replace('!', '') sentence = sentence.replace('?', '') sentence = sentence.replace(':', '') sentence = sentence.replace('"', '') # If the last character is not an alphanumeric remove it sentence = re.sub('[^a-zA-Z0-9]$', '', sentence) # Remove excess space sentence = re.sub('\s+', ' ', sentence) # Add a full stop sentence += '.' return sentence
[ "def", "_sentence", "(", "self", ",", "words", ")", ":", "db", "=", "self", ".", "database", "# Generate 2 words to start a sentence with", "seed", "=", "random", ".", "randint", "(", "0", ",", "db", "[", "'word_count'", "]", "-", "3", ")", "seed_word", ",...
Generate a sentence
[ "Generate", "a", "sentence" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/text.py#L211-L255
train
26,361
GetmeUK/MongoFrames
mongoframes/factory/makers/text.py
Markov.init_word_db
def init_word_db(cls, name, text): """Initialize a database of words for the maker with the given name""" # Prep the words text = text.replace('\n', ' ').replace('\r', ' ') words = [w.strip() for w in text.split(' ') if w.strip()] assert len(words) > 2, \ 'Database text sources must contain 3 or more words.' # Build the database freqs = {} for i in range(len(words) - 2): # Create a triplet from the current word w1 = words[i] w2 = words[i + 1] w3 = words[i + 2] # Add the triplet to the database key = (w1, w2) if key in freqs: freqs[key].append(w3) else: freqs[key] = [w3] # Store the database so it can be used cls._dbs[name] = { 'freqs': freqs, 'words': words, 'word_count': len(words) - 2 }
python
def init_word_db(cls, name, text): """Initialize a database of words for the maker with the given name""" # Prep the words text = text.replace('\n', ' ').replace('\r', ' ') words = [w.strip() for w in text.split(' ') if w.strip()] assert len(words) > 2, \ 'Database text sources must contain 3 or more words.' # Build the database freqs = {} for i in range(len(words) - 2): # Create a triplet from the current word w1 = words[i] w2 = words[i + 1] w3 = words[i + 2] # Add the triplet to the database key = (w1, w2) if key in freqs: freqs[key].append(w3) else: freqs[key] = [w3] # Store the database so it can be used cls._dbs[name] = { 'freqs': freqs, 'words': words, 'word_count': len(words) - 2 }
[ "def", "init_word_db", "(", "cls", ",", "name", ",", "text", ")", ":", "# Prep the words", "text", "=", "text", ".", "replace", "(", "'\\n'", ",", "' '", ")", ".", "replace", "(", "'\\r'", ",", "' '", ")", "words", "=", "[", "w", ".", "strip", "(",...
Initialize a database of words for the maker with the given name
[ "Initialize", "a", "database", "of", "words", "for", "the", "maker", "with", "the", "given", "name" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/text.py#L258-L288
train
26,362
GetmeUK/MongoFrames
mongoframes/factory/makers/selections.py
SomeOf.p
def p(i, sample_size, weights): """ Given a weighted set and sample size return the probabilty that the weight `i` will be present in the sample. Created to test the output of the `SomeOf` maker class. The math was provided by Andy Blackshaw - thank you dad :) """ # Determine the initial pick values weight_i = weights[i] weights_sum = sum(weights) # Build a list of weights that don't contain the weight `i`. This list will # be used to build the possible picks before weight `i`. other_weights = list(weights) del other_weights[i] # Calculate the probability probability_of_i = 0 for picks in range(0, sample_size): # Build the list of possible permutations for this pick in the sample permutations = list(itertools.permutations(other_weights, picks)) # Calculate the probability for this permutation permutation_probabilities = [] for permutation in permutations: # Calculate the probability for each pick in the permutation pick_probabilities = [] pick_weight_sum = weights_sum for pick in permutation: pick_probabilities.append(pick / pick_weight_sum) # Each time we pick we update the sum of the weight the next # pick is from. pick_weight_sum -= pick # Add the probability of picking i as the last pick pick_probabilities += [weight_i / pick_weight_sum] # Multiply all the probabilities for the permutation together permutation_probability = reduce( lambda x, y: x * y, pick_probabilities ) permutation_probabilities.append(permutation_probability) # Add together all the probabilities for all permutations together probability_of_i += sum(permutation_probabilities) return probability_of_i
python
def p(i, sample_size, weights): """ Given a weighted set and sample size return the probabilty that the weight `i` will be present in the sample. Created to test the output of the `SomeOf` maker class. The math was provided by Andy Blackshaw - thank you dad :) """ # Determine the initial pick values weight_i = weights[i] weights_sum = sum(weights) # Build a list of weights that don't contain the weight `i`. This list will # be used to build the possible picks before weight `i`. other_weights = list(weights) del other_weights[i] # Calculate the probability probability_of_i = 0 for picks in range(0, sample_size): # Build the list of possible permutations for this pick in the sample permutations = list(itertools.permutations(other_weights, picks)) # Calculate the probability for this permutation permutation_probabilities = [] for permutation in permutations: # Calculate the probability for each pick in the permutation pick_probabilities = [] pick_weight_sum = weights_sum for pick in permutation: pick_probabilities.append(pick / pick_weight_sum) # Each time we pick we update the sum of the weight the next # pick is from. pick_weight_sum -= pick # Add the probability of picking i as the last pick pick_probabilities += [weight_i / pick_weight_sum] # Multiply all the probabilities for the permutation together permutation_probability = reduce( lambda x, y: x * y, pick_probabilities ) permutation_probabilities.append(permutation_probability) # Add together all the probabilities for all permutations together probability_of_i += sum(permutation_probabilities) return probability_of_i
[ "def", "p", "(", "i", ",", "sample_size", ",", "weights", ")", ":", "# Determine the initial pick values", "weight_i", "=", "weights", "[", "i", "]", "weights_sum", "=", "sum", "(", "weights", ")", "# Build a list of weights that don't contain the weight `i`. This list ...
Given a weighted set and sample size return the probabilty that the weight `i` will be present in the sample. Created to test the output of the `SomeOf` maker class. The math was provided by Andy Blackshaw - thank you dad :)
[ "Given", "a", "weighted", "set", "and", "sample", "size", "return", "the", "probabilty", "that", "the", "weight", "i", "will", "be", "present", "in", "the", "sample", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/selections.py#L231-L283
train
26,363
GetmeUK/MongoFrames
mongoframes/factory/makers/__init__.py
Faker.get_fake
def get_fake(locale=None): """Return a shared faker factory used to generate fake data""" if locale is None: locale = Faker.default_locale if not hasattr(Maker, '_fake_' + locale): Faker._fake = faker.Factory.create(locale) return Faker._fake
python
def get_fake(locale=None): """Return a shared faker factory used to generate fake data""" if locale is None: locale = Faker.default_locale if not hasattr(Maker, '_fake_' + locale): Faker._fake = faker.Factory.create(locale) return Faker._fake
[ "def", "get_fake", "(", "locale", "=", "None", ")", ":", "if", "locale", "is", "None", ":", "locale", "=", "Faker", ".", "default_locale", "if", "not", "hasattr", "(", "Maker", ",", "'_fake_'", "+", "locale", ")", ":", "Faker", ".", "_fake", "=", "fa...
Return a shared faker factory used to generate fake data
[ "Return", "a", "shared", "faker", "factory", "used", "to", "generate", "fake", "data" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/__init__.py#L127-L134
train
26,364
GetmeUK/MongoFrames
mongoframes/factory/makers/__init__.py
Unique._get_unique
def _get_unique(self, *args): """Generate a unique value using the assigned maker""" # Generate a unique values value = '' attempts = 0 while True: attempts += 1 value = self._maker(*args) if value not in self._used_values: break assert attempts < self._max_attempts, \ 'Too many attempts to generate a unique value' # Add the value to the set of used values self._used_values.add(value) return value
python
def _get_unique(self, *args): """Generate a unique value using the assigned maker""" # Generate a unique values value = '' attempts = 0 while True: attempts += 1 value = self._maker(*args) if value not in self._used_values: break assert attempts < self._max_attempts, \ 'Too many attempts to generate a unique value' # Add the value to the set of used values self._used_values.add(value) return value
[ "def", "_get_unique", "(", "self", ",", "*", "args", ")", ":", "# Generate a unique values", "value", "=", "''", "attempts", "=", "0", "while", "True", ":", "attempts", "+=", "1", "value", "=", "self", ".", "_maker", "(", "*", "args", ")", "if", "value...
Generate a unique value using the assigned maker
[ "Generate", "a", "unique", "value", "using", "the", "assigned", "maker" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/makers/__init__.py#L300-L318
train
26,365
GetmeUK/MongoFrames
mongoframes/factory/blueprints.py
Blueprint.assemble
def assemble(cls): """Assemble a single document using the blueprint""" document = {} for field_name, maker in cls._instructions.items(): with maker.target(document): document[field_name] = maker() return document
python
def assemble(cls): """Assemble a single document using the blueprint""" document = {} for field_name, maker in cls._instructions.items(): with maker.target(document): document[field_name] = maker() return document
[ "def", "assemble", "(", "cls", ")", ":", "document", "=", "{", "}", "for", "field_name", ",", "maker", "in", "cls", ".", "_instructions", ".", "items", "(", ")", ":", "with", "maker", ".", "target", "(", "document", ")", ":", "document", "[", "field_...
Assemble a single document using the blueprint
[ "Assemble", "a", "single", "document", "using", "the", "blueprint" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/blueprints.py#L75-L81
train
26,366
GetmeUK/MongoFrames
mongoframes/factory/blueprints.py
Blueprint.finish
def finish(cls, document): """ Take a assembled document and convert all assembled values to finished values. """ target_document = {} document_copy = {} for field_name, value in document.items(): maker = cls._instructions[field_name] target_document = document.copy() with maker.target(target_document): document_copy[field_name] = maker(value) target_document[field_name] = document_copy[field_name] return document_copy
python
def finish(cls, document): """ Take a assembled document and convert all assembled values to finished values. """ target_document = {} document_copy = {} for field_name, value in document.items(): maker = cls._instructions[field_name] target_document = document.copy() with maker.target(target_document): document_copy[field_name] = maker(value) target_document[field_name] = document_copy[field_name] return document_copy
[ "def", "finish", "(", "cls", ",", "document", ")", ":", "target_document", "=", "{", "}", "document_copy", "=", "{", "}", "for", "field_name", ",", "value", "in", "document", ".", "items", "(", ")", ":", "maker", "=", "cls", ".", "_instructions", "[", ...
Take a assembled document and convert all assembled values to finished values.
[ "Take", "a", "assembled", "document", "and", "convert", "all", "assembled", "values", "to", "finished", "values", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/blueprints.py#L84-L97
train
26,367
GetmeUK/MongoFrames
mongoframes/factory/blueprints.py
Blueprint.reassemble
def reassemble(cls, fields, document): """ Take a previously assembled document and reassemble the given set of fields for it in place. """ for field_name in cls._instructions: if field_name in fields: maker = cls._instructions[field_name] with maker.target(document): document[field_name] = maker()
python
def reassemble(cls, fields, document): """ Take a previously assembled document and reassemble the given set of fields for it in place. """ for field_name in cls._instructions: if field_name in fields: maker = cls._instructions[field_name] with maker.target(document): document[field_name] = maker()
[ "def", "reassemble", "(", "cls", ",", "fields", ",", "document", ")", ":", "for", "field_name", "in", "cls", ".", "_instructions", ":", "if", "field_name", "in", "fields", ":", "maker", "=", "cls", ".", "_instructions", "[", "field_name", "]", "with", "m...
Take a previously assembled document and reassemble the given set of fields for it in place.
[ "Take", "a", "previously", "assembled", "document", "and", "reassemble", "the", "given", "set", "of", "fields", "for", "it", "in", "place", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/blueprints.py#L100-L109
train
26,368
GetmeUK/MongoFrames
snippets/comparable.py
ChangeLogEntry.is_diff
def is_diff(self): """Return True if there are any differences logged""" if not isinstance(self.details, dict): return False for key in ['additions', 'updates', 'deletions']: if self.details.get(key, None): return True return False
python
def is_diff(self): """Return True if there are any differences logged""" if not isinstance(self.details, dict): return False for key in ['additions', 'updates', 'deletions']: if self.details.get(key, None): return True return False
[ "def", "is_diff", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "details", ",", "dict", ")", ":", "return", "False", "for", "key", "in", "[", "'additions'", ",", "'updates'", ",", "'deletions'", "]", ":", "if", "self", ".", "det...
Return True if there are any differences logged
[ "Return", "True", "if", "there", "are", "any", "differences", "logged" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L73-L82
train
26,369
GetmeUK/MongoFrames
snippets/comparable.py
ChangeLogEntry.diff_to_html
def diff_to_html(cls, details): """Return an entry's details in HTML format""" changes = [] # Check that there are details to convert to HMTL if not details: return '' def _frame(value): """ Handle converted `Frame` references where the human identifier is stored against the `_str` key. """ if isinstance(value, dict) and '_str' in value: return value['_str'] elif isinstance(value, list): return ', '.join([_frame(v) for v in value]) return str(value) # Additions fields = sorted(details.get('additions', {})) for field in fields: new_value = _frame(details['additions'][field]) if isinstance(new_value, list): new_value = ', '.join([_frame(v) for v in new_value]) change = cls._templates['add'].format( field=field, new_value=new_value ) changes.append(change) # Updates fields = sorted(details.get('updates', {})) for field in fields: original_value = _frame(details['updates'][field][0]) if isinstance(original_value, list): original_value = ', '.join([_frame(v) for v in original_value]) new_value = _frame(details['updates'][field][1]) if isinstance(new_value, list): new_value = ', '.join([_frame(v) for v in new_value]) change = cls._templates['update'].format( field=field, original_value=original_value, new_value=new_value ) changes.append(change) # Deletions fields = sorted(details.get('deletions', {})) for field in fields: original_value = _frame(details['deletions'][field]) if isinstance(original_value, list): original_value = ', '.join([_frame(v) for v in original_value]) change = cls._templates['delete'].format( field=field, original_value=original_value ) changes.append(change) return '\n'.join(changes)
python
def diff_to_html(cls, details): """Return an entry's details in HTML format""" changes = [] # Check that there are details to convert to HMTL if not details: return '' def _frame(value): """ Handle converted `Frame` references where the human identifier is stored against the `_str` key. """ if isinstance(value, dict) and '_str' in value: return value['_str'] elif isinstance(value, list): return ', '.join([_frame(v) for v in value]) return str(value) # Additions fields = sorted(details.get('additions', {})) for field in fields: new_value = _frame(details['additions'][field]) if isinstance(new_value, list): new_value = ', '.join([_frame(v) for v in new_value]) change = cls._templates['add'].format( field=field, new_value=new_value ) changes.append(change) # Updates fields = sorted(details.get('updates', {})) for field in fields: original_value = _frame(details['updates'][field][0]) if isinstance(original_value, list): original_value = ', '.join([_frame(v) for v in original_value]) new_value = _frame(details['updates'][field][1]) if isinstance(new_value, list): new_value = ', '.join([_frame(v) for v in new_value]) change = cls._templates['update'].format( field=field, original_value=original_value, new_value=new_value ) changes.append(change) # Deletions fields = sorted(details.get('deletions', {})) for field in fields: original_value = _frame(details['deletions'][field]) if isinstance(original_value, list): original_value = ', '.join([_frame(v) for v in original_value]) change = cls._templates['delete'].format( field=field, original_value=original_value ) changes.append(change) return '\n'.join(changes)
[ "def", "diff_to_html", "(", "cls", ",", "details", ")", ":", "changes", "=", "[", "]", "# Check that there are details to convert to HMTL", "if", "not", "details", ":", "return", "''", "def", "_frame", "(", "value", ")", ":", "\"\"\"\n Handle converted `F...
Return an entry's details in HTML format
[ "Return", "an", "entry", "s", "details", "in", "HTML", "format" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L151-L214
train
26,370
GetmeUK/MongoFrames
snippets/comparable.py
ChangeLogEntry.diff_safe
def diff_safe(cls, value): """Return a value that can be safely stored as a diff""" if isinstance(value, Frame): return {'_str': str(value), '_id': value._id} elif isinstance(value, (list, tuple)): return [cls.diff_safe(v) for v in value] return value
python
def diff_safe(cls, value): """Return a value that can be safely stored as a diff""" if isinstance(value, Frame): return {'_str': str(value), '_id': value._id} elif isinstance(value, (list, tuple)): return [cls.diff_safe(v) for v in value] return value
[ "def", "diff_safe", "(", "cls", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Frame", ")", ":", "return", "{", "'_str'", ":", "str", "(", "value", ")", ",", "'_id'", ":", "value", ".", "_id", "}", "elif", "isinstance", "(", "value...
Return a value that can be safely stored as a diff
[ "Return", "a", "value", "that", "can", "be", "safely", "stored", "as", "a", "diff" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L217-L223
train
26,371
GetmeUK/MongoFrames
snippets/comparable.py
ComparableFrame.comparable
def comparable(self): """Return a dictionary that can be compared""" document_dict = self.compare_safe(self._document) # Remove uncompared fields self._remove_keys(document_dict, self._uncompared_fields) # Remove any empty values clean_document_dict = {} for k, v in document_dict.items(): if not v and not isinstance(v, (int, float)): continue clean_document_dict[k] = v # Convert any referenced fields to Frames for ref_field, ref_cls in self._compared_refs.items(): ref = getattr(self, ref_field) if not ref: continue # Check for fields which contain a list of references if isinstance(ref, list): if isinstance(ref[0], Frame): continue # Dereference the list of reference IDs setattr( clean_document_dict, ref_field, ref_cls.many(In(Q._id, ref)) ) else: if isinstance(ref, Frame): continue # Dereference the reference ID setattr( clean_document_dict, ref_field, ref_cls.byId(ref) ) return clean_document_dict
python
def comparable(self): """Return a dictionary that can be compared""" document_dict = self.compare_safe(self._document) # Remove uncompared fields self._remove_keys(document_dict, self._uncompared_fields) # Remove any empty values clean_document_dict = {} for k, v in document_dict.items(): if not v and not isinstance(v, (int, float)): continue clean_document_dict[k] = v # Convert any referenced fields to Frames for ref_field, ref_cls in self._compared_refs.items(): ref = getattr(self, ref_field) if not ref: continue # Check for fields which contain a list of references if isinstance(ref, list): if isinstance(ref[0], Frame): continue # Dereference the list of reference IDs setattr( clean_document_dict, ref_field, ref_cls.many(In(Q._id, ref)) ) else: if isinstance(ref, Frame): continue # Dereference the reference ID setattr( clean_document_dict, ref_field, ref_cls.byId(ref) ) return clean_document_dict
[ "def", "comparable", "(", "self", ")", ":", "document_dict", "=", "self", ".", "compare_safe", "(", "self", ".", "_document", ")", "# Remove uncompared fields", "self", ".", "_remove_keys", "(", "document_dict", ",", "self", ".", "_uncompared_fields", ")", "# Re...
Return a dictionary that can be compared
[ "Return", "a", "dictionary", "that", "can", "be", "compared" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L265-L308
train
26,372
GetmeUK/MongoFrames
snippets/comparable.py
ComparableFrame.logged_delete
def logged_delete(self, user): """Delete the document and log the event in the change log""" self.delete() # Log the change entry = ChangeLogEntry({ 'type': 'DELETED', 'documents': [self], 'user': user }) entry.insert() return entry
python
def logged_delete(self, user): """Delete the document and log the event in the change log""" self.delete() # Log the change entry = ChangeLogEntry({ 'type': 'DELETED', 'documents': [self], 'user': user }) entry.insert() return entry
[ "def", "logged_delete", "(", "self", ",", "user", ")", ":", "self", ".", "delete", "(", ")", "# Log the change", "entry", "=", "ChangeLogEntry", "(", "{", "'type'", ":", "'DELETED'", ",", "'documents'", ":", "[", "self", "]", ",", "'user'", ":", "user", ...
Delete the document and log the event in the change log
[ "Delete", "the", "document", "and", "log", "the", "event", "in", "the", "change", "log" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L310-L323
train
26,373
GetmeUK/MongoFrames
snippets/comparable.py
ComparableFrame.logged_insert
def logged_insert(self, user): """Create and insert the document and log the event in the change log""" # Insert the frame's document self.insert() # Log the insert entry = ChangeLogEntry({ 'type': 'ADDED', 'documents': [self], 'user': user }) entry.insert() return entry
python
def logged_insert(self, user): """Create and insert the document and log the event in the change log""" # Insert the frame's document self.insert() # Log the insert entry = ChangeLogEntry({ 'type': 'ADDED', 'documents': [self], 'user': user }) entry.insert() return entry
[ "def", "logged_insert", "(", "self", ",", "user", ")", ":", "# Insert the frame's document", "self", ".", "insert", "(", ")", "# Log the insert", "entry", "=", "ChangeLogEntry", "(", "{", "'type'", ":", "'ADDED'", ",", "'documents'", ":", "[", "self", "]", "...
Create and insert the document and log the event in the change log
[ "Create", "and", "insert", "the", "document", "and", "log", "the", "event", "in", "the", "change", "log" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L325-L339
train
26,374
GetmeUK/MongoFrames
snippets/comparable.py
ComparableFrame.logged_update
def logged_update(self, user, data, *fields): """ Update the document with the dictionary of data provided and log the event in the change log. """ # Get a copy of the frames comparable data before the update original = self.comparable # Update the frame _fields = fields if len(fields) == 0: _fields = data.keys() for field in _fields: if field in data: setattr(self, field, data[field]) self.update(*fields) # Create an entry and perform a diff entry = ChangeLogEntry({ 'type': 'UPDATED', 'documents': [self], 'user': user }) entry.add_diff(original, self.comparable) # Check there's a change to apply/log if not entry.is_diff: return entry.insert() return entry
python
def logged_update(self, user, data, *fields): """ Update the document with the dictionary of data provided and log the event in the change log. """ # Get a copy of the frames comparable data before the update original = self.comparable # Update the frame _fields = fields if len(fields) == 0: _fields = data.keys() for field in _fields: if field in data: setattr(self, field, data[field]) self.update(*fields) # Create an entry and perform a diff entry = ChangeLogEntry({ 'type': 'UPDATED', 'documents': [self], 'user': user }) entry.add_diff(original, self.comparable) # Check there's a change to apply/log if not entry.is_diff: return entry.insert() return entry
[ "def", "logged_update", "(", "self", ",", "user", ",", "data", ",", "*", "fields", ")", ":", "# Get a copy of the frames comparable data before the update", "original", "=", "self", ".", "comparable", "# Update the frame", "_fields", "=", "fields", "if", "len", "(",...
Update the document with the dictionary of data provided and log the event in the change log.
[ "Update", "the", "document", "with", "the", "dictionary", "of", "data", "provided", "and", "log", "the", "event", "in", "the", "change", "log", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L341-L374
train
26,375
GetmeUK/MongoFrames
snippets/comparable.py
ComparableFrame.compare_safe
def compare_safe(cls, value): """Return a value that can be safely compared""" # Date if type(value) == date: return str(value) # Lists elif isinstance(value, (list, tuple)): return [cls.compare_safe(v) for v in value] # Dictionaries elif isinstance(value, dict): return {k: cls.compare_safe(v) for k, v in value.items()} return value
python
def compare_safe(cls, value): """Return a value that can be safely compared""" # Date if type(value) == date: return str(value) # Lists elif isinstance(value, (list, tuple)): return [cls.compare_safe(v) for v in value] # Dictionaries elif isinstance(value, dict): return {k: cls.compare_safe(v) for k, v in value.items()} return value
[ "def", "compare_safe", "(", "cls", ",", "value", ")", ":", "# Date", "if", "type", "(", "value", ")", "==", "date", ":", "return", "str", "(", "value", ")", "# Lists", "elif", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":...
Return a value that can be safely compared
[ "Return", "a", "value", "that", "can", "be", "safely", "compared" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L377-L392
train
26,376
GetmeUK/MongoFrames
mongoframes/queries.py
ElemMatch
def ElemMatch(q, *conditions): """ The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. """ new_condition = {} for condition in conditions: deep_merge(condition.to_dict(), new_condition) return Condition(q._path, new_condition, '$elemMatch')
python
def ElemMatch(q, *conditions): """ The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. """ new_condition = {} for condition in conditions: deep_merge(condition.to_dict(), new_condition) return Condition(q._path, new_condition, '$elemMatch')
[ "def", "ElemMatch", "(", "q", ",", "*", "conditions", ")", ":", "new_condition", "=", "{", "}", "for", "condition", "in", "conditions", ":", "deep_merge", "(", "condition", ".", "to_dict", "(", ")", ",", "new_condition", ")", "return", "Condition", "(", ...
The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
[ "The", "ElemMatch", "operator", "matches", "documents", "that", "contain", "an", "array", "field", "with", "at", "least", "one", "element", "that", "matches", "all", "the", "specified", "query", "criteria", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/queries.py#L135-L144
train
26,377
GetmeUK/MongoFrames
mongoframes/queries.py
SortBy
def SortBy(*qs): """Convert a list of Q objects into list of sort instructions""" sort = [] for q in qs: if q._path.endswith('.desc'): sort.append((q._path[:-5], DESCENDING)) else: sort.append((q._path, ASCENDING)) return sort
python
def SortBy(*qs): """Convert a list of Q objects into list of sort instructions""" sort = [] for q in qs: if q._path.endswith('.desc'): sort.append((q._path[:-5], DESCENDING)) else: sort.append((q._path, ASCENDING)) return sort
[ "def", "SortBy", "(", "*", "qs", ")", ":", "sort", "=", "[", "]", "for", "q", "in", "qs", ":", "if", "q", ".", "_path", ".", "endswith", "(", "'.desc'", ")", ":", "sort", ".", "append", "(", "(", "q", ".", "_path", "[", ":", "-", "5", "]", ...
Convert a list of Q objects into list of sort instructions
[ "Convert", "a", "list", "of", "Q", "objects", "into", "list", "of", "sort", "instructions" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/queries.py#L249-L258
train
26,378
GetmeUK/MongoFrames
mongoframes/queries.py
deep_merge
def deep_merge(source, dest): """ Deep merges source dict into dest dict. This code was taken directly from the mongothon project: https://github.com/gamechanger/mongothon/tree/master/mongothon """ for key, value in source.items(): if key in dest: if isinstance(value, dict) and isinstance(dest[key], dict): deep_merge(value, dest[key]) continue elif isinstance(value, list) and isinstance(dest[key], list): for item in value: if item not in dest[key]: dest[key].append(item) continue dest[key] = value
python
def deep_merge(source, dest): """ Deep merges source dict into dest dict. This code was taken directly from the mongothon project: https://github.com/gamechanger/mongothon/tree/master/mongothon """ for key, value in source.items(): if key in dest: if isinstance(value, dict) and isinstance(dest[key], dict): deep_merge(value, dest[key]) continue elif isinstance(value, list) and isinstance(dest[key], list): for item in value: if item not in dest[key]: dest[key].append(item) continue dest[key] = value
[ "def", "deep_merge", "(", "source", ",", "dest", ")", ":", "for", "key", ",", "value", "in", "source", ".", "items", "(", ")", ":", "if", "key", "in", "dest", ":", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "isinstance", "(", "dest"...
Deep merges source dict into dest dict. This code was taken directly from the mongothon project: https://github.com/gamechanger/mongothon/tree/master/mongothon
[ "Deep", "merges", "source", "dict", "into", "dest", "dict", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/queries.py#L263-L280
train
26,379
GetmeUK/MongoFrames
mongoframes/queries.py
to_refs
def to_refs(value): """Convert all Frame instances within the given value to Ids""" from mongoframes.frames import Frame, SubFrame # Frame if isinstance(value, Frame): return value._id # SubFrame elif isinstance(value, SubFrame): return to_refs(value._document) # Lists elif isinstance(value, (list, tuple)): return [to_refs(v) for v in value] # Dictionaries elif isinstance(value, dict): return {k: to_refs(v) for k, v in value.items()} return value
python
def to_refs(value): """Convert all Frame instances within the given value to Ids""" from mongoframes.frames import Frame, SubFrame # Frame if isinstance(value, Frame): return value._id # SubFrame elif isinstance(value, SubFrame): return to_refs(value._document) # Lists elif isinstance(value, (list, tuple)): return [to_refs(v) for v in value] # Dictionaries elif isinstance(value, dict): return {k: to_refs(v) for k, v in value.items()} return value
[ "def", "to_refs", "(", "value", ")", ":", "from", "mongoframes", ".", "frames", "import", "Frame", ",", "SubFrame", "# Frame", "if", "isinstance", "(", "value", ",", "Frame", ")", ":", "return", "value", ".", "_id", "# SubFrame", "elif", "isinstance", "(",...
Convert all Frame instances within the given value to Ids
[ "Convert", "all", "Frame", "instances", "within", "the", "given", "value", "to", "Ids" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/queries.py#L282-L302
train
26,380
GetmeUK/MongoFrames
mongoframes/factory/__init__.py
Factory.assemble
def assemble(self, blueprint, quota): """Assemble a quota of documents""" # Reset the blueprint blueprint.reset() # Assemble the documents documents = [] for i in range(0, int(quota)): documents.append(blueprint.assemble()) return documents
python
def assemble(self, blueprint, quota): """Assemble a quota of documents""" # Reset the blueprint blueprint.reset() # Assemble the documents documents = [] for i in range(0, int(quota)): documents.append(blueprint.assemble()) return documents
[ "def", "assemble", "(", "self", ",", "blueprint", ",", "quota", ")", ":", "# Reset the blueprint", "blueprint", ".", "reset", "(", ")", "# Assemble the documents", "documents", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "int", "(", "quota", ...
Assemble a quota of documents
[ "Assemble", "a", "quota", "of", "documents" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/__init__.py#L39-L50
train
26,381
GetmeUK/MongoFrames
mongoframes/factory/__init__.py
Factory.finish
def finish(self, blueprint, documents): """Finish a list of pre-assembled documents""" # Reset the blueprint blueprint.reset() # Finish the documents finished = [] for document in documents: finished.append(blueprint.finish(document)) return finished
python
def finish(self, blueprint, documents): """Finish a list of pre-assembled documents""" # Reset the blueprint blueprint.reset() # Finish the documents finished = [] for document in documents: finished.append(blueprint.finish(document)) return finished
[ "def", "finish", "(", "self", ",", "blueprint", ",", "documents", ")", ":", "# Reset the blueprint", "blueprint", ".", "reset", "(", ")", "# Finish the documents", "finished", "=", "[", "]", "for", "document", "in", "documents", ":", "finished", ".", "append",...
Finish a list of pre-assembled documents
[ "Finish", "a", "list", "of", "pre", "-", "assembled", "documents" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/__init__.py#L52-L63
train
26,382
GetmeUK/MongoFrames
mongoframes/factory/__init__.py
Factory.populate
def populate(self, blueprint, documents): """Populate the database with documents""" # Finish the documents documents = self.finish(blueprint, documents) # Convert the documents to frame instances frames = [] for document in documents: # Separate out any meta fields meta_document = {} for field_name in blueprint._meta_fields: meta_document[field_name] = document[field_name] document.pop(field_name) # Initialize the frame frame = blueprint.get_frame_cls()(document) # Apply any meta fields for key, value in meta_document.items(): setattr(frame, key, value) frames.append(frame) # Insert the documents blueprint.on_fake(frames) frames = blueprint.get_frame_cls().insert_many(frames) blueprint.on_faked(frames) return frames
python
def populate(self, blueprint, documents): """Populate the database with documents""" # Finish the documents documents = self.finish(blueprint, documents) # Convert the documents to frame instances frames = [] for document in documents: # Separate out any meta fields meta_document = {} for field_name in blueprint._meta_fields: meta_document[field_name] = document[field_name] document.pop(field_name) # Initialize the frame frame = blueprint.get_frame_cls()(document) # Apply any meta fields for key, value in meta_document.items(): setattr(frame, key, value) frames.append(frame) # Insert the documents blueprint.on_fake(frames) frames = blueprint.get_frame_cls().insert_many(frames) blueprint.on_faked(frames) return frames
[ "def", "populate", "(", "self", ",", "blueprint", ",", "documents", ")", ":", "# Finish the documents", "documents", "=", "self", ".", "finish", "(", "blueprint", ",", "documents", ")", "# Convert the documents to frame instances", "frames", "=", "[", "]", "for", ...
Populate the database with documents
[ "Populate", "the", "database", "with", "documents" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/__init__.py#L65-L94
train
26,383
GetmeUK/MongoFrames
mongoframes/factory/__init__.py
Factory.reassemble
def reassemble(self, blueprint, fields, documents): """ Reassemble the given set of fields for a list of pre-assembed documents. NOTE: Reassembly is done in place, since the data you send the method should be JSON type safe, if you need to retain the existing document it is recommended that you copy them using `copy.deepcopy`. """ # Reset the blueprint blueprint.reset() # Reassemble the documents for document in documents: blueprint.reassemble(fields, document)
python
def reassemble(self, blueprint, fields, documents): """ Reassemble the given set of fields for a list of pre-assembed documents. NOTE: Reassembly is done in place, since the data you send the method should be JSON type safe, if you need to retain the existing document it is recommended that you copy them using `copy.deepcopy`. """ # Reset the blueprint blueprint.reset() # Reassemble the documents for document in documents: blueprint.reassemble(fields, document)
[ "def", "reassemble", "(", "self", ",", "blueprint", ",", "fields", ",", "documents", ")", ":", "# Reset the blueprint", "blueprint", ".", "reset", "(", ")", "# Reassemble the documents", "for", "document", "in", "documents", ":", "blueprint", ".", "reassemble", ...
Reassemble the given set of fields for a list of pre-assembed documents. NOTE: Reassembly is done in place, since the data you send the method should be JSON type safe, if you need to retain the existing document it is recommended that you copy them using `copy.deepcopy`.
[ "Reassemble", "the", "given", "set", "of", "fields", "for", "a", "list", "of", "pre", "-", "assembed", "documents", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/__init__.py#L96-L110
train
26,384
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.can_publish
def can_publish(self): """ Return True if there is a draft version of the document that's ready to be published. """ with self.published_context(): published = self.one( Q._uid == self._uid, projection={'revision': True} ) if not published: return True with self.draft_context(): draft = self.one(Q._uid == self._uid, projection={'revision': True}) return draft.revision > published.revision
python
def can_publish(self): """ Return True if there is a draft version of the document that's ready to be published. """ with self.published_context(): published = self.one( Q._uid == self._uid, projection={'revision': True} ) if not published: return True with self.draft_context(): draft = self.one(Q._uid == self._uid, projection={'revision': True}) return draft.revision > published.revision
[ "def", "can_publish", "(", "self", ")", ":", "with", "self", ".", "published_context", "(", ")", ":", "published", "=", "self", ".", "one", "(", "Q", ".", "_uid", "==", "self", ".", "_uid", ",", "projection", "=", "{", "'revision'", ":", "True", "}",...
Return True if there is a draft version of the document that's ready to be published.
[ "Return", "True", "if", "there", "is", "a", "draft", "version", "of", "the", "document", "that", "s", "ready", "to", "be", "published", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L29-L46
train
26,385
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.can_revert
def can_revert(self): """ Return True if we can revert the draft version of the document to the currently published version. """ if self.can_publish: with self.published_context(): return self.count(Q._uid == self._uid) > 0 return False
python
def can_revert(self): """ Return True if we can revert the draft version of the document to the currently published version. """ if self.can_publish: with self.published_context(): return self.count(Q._uid == self._uid) > 0 return False
[ "def", "can_revert", "(", "self", ")", ":", "if", "self", ".", "can_publish", ":", "with", "self", ".", "published_context", "(", ")", ":", "return", "self", ".", "count", "(", "Q", ".", "_uid", "==", "self", ".", "_uid", ")", ">", "0", "return", "...
Return True if we can revert the draft version of the document to the currently published version.
[ "Return", "True", "if", "we", "can", "revert", "the", "draft", "version", "of", "the", "document", "to", "the", "currently", "published", "version", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L49-L59
train
26,386
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.get_publisher_doc
def get_publisher_doc(self): """Return a publish safe version of the frame's document""" with self.draft_context(): # Select the draft document from the database draft = self.one(Q._uid == self._uid) publisher_doc = draft._document # Remove any keys from the document that should not be transferred # when publishing. self._remove_keys(publisher_doc, self._unpublished_fields) return publisher_doc
python
def get_publisher_doc(self): """Return a publish safe version of the frame's document""" with self.draft_context(): # Select the draft document from the database draft = self.one(Q._uid == self._uid) publisher_doc = draft._document # Remove any keys from the document that should not be transferred # when publishing. self._remove_keys(publisher_doc, self._unpublished_fields) return publisher_doc
[ "def", "get_publisher_doc", "(", "self", ")", ":", "with", "self", ".", "draft_context", "(", ")", ":", "# Select the draft document from the database", "draft", "=", "self", ".", "one", "(", "Q", ".", "_uid", "==", "self", ".", "_uid", ")", "publisher_doc", ...
Return a publish safe version of the frame's document
[ "Return", "a", "publish", "safe", "version", "of", "the", "frame", "s", "document" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L61-L72
train
26,387
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.publish
def publish(self): """ Publish the current document. NOTE: You must have saved any changes to the draft version of the document before publishing, unsaved changes wont be published. """ publisher_doc = self.get_publisher_doc() with self.published_context(): # Select the published document published = self.one(Q._uid == self._uid) # If there's no published version of the document create one if not published: published = self.__class__() # Update the document for field, value in publisher_doc.items(): setattr(published, field, value) # Save published version published.upsert() # Set the revisions number for draft/published version, we use PyMongo # directly as it's more convienent to use the shared `_uid`. now = datetime.now() with self.draft_context(): self.get_collection().update( {'_uid': self._uid}, {'$set': {'revision': now}} ) with self.published_context(): self.get_collection().update( {'_uid': self._uid}, {'$set': {'revision': now}} )
python
def publish(self): """ Publish the current document. NOTE: You must have saved any changes to the draft version of the document before publishing, unsaved changes wont be published. """ publisher_doc = self.get_publisher_doc() with self.published_context(): # Select the published document published = self.one(Q._uid == self._uid) # If there's no published version of the document create one if not published: published = self.__class__() # Update the document for field, value in publisher_doc.items(): setattr(published, field, value) # Save published version published.upsert() # Set the revisions number for draft/published version, we use PyMongo # directly as it's more convienent to use the shared `_uid`. now = datetime.now() with self.draft_context(): self.get_collection().update( {'_uid': self._uid}, {'$set': {'revision': now}} ) with self.published_context(): self.get_collection().update( {'_uid': self._uid}, {'$set': {'revision': now}} )
[ "def", "publish", "(", "self", ")", ":", "publisher_doc", "=", "self", ".", "get_publisher_doc", "(", ")", "with", "self", ".", "published_context", "(", ")", ":", "# Select the published document", "published", "=", "self", ".", "one", "(", "Q", ".", "_uid"...
Publish the current document. NOTE: You must have saved any changes to the draft version of the document before publishing, unsaved changes wont be published.
[ "Publish", "the", "current", "document", "." ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L74-L112
train
26,388
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.new_revision
def new_revision(self, *fields): """Save a new revision of the document""" # Ensure this document is a draft if not self._id: assert g.get('draft'), \ 'Only draft documents can be assigned new revisions' else: with self.draft_context(): assert self.count(Q._id == self._id) == 1, \ 'Only draft documents can be assigned new revisions' # Set the revision if len(fields) > 0: fields.append('revision') self.revision = datetime.now() # Update the document self.upsert(*fields)
python
def new_revision(self, *fields): """Save a new revision of the document""" # Ensure this document is a draft if not self._id: assert g.get('draft'), \ 'Only draft documents can be assigned new revisions' else: with self.draft_context(): assert self.count(Q._id == self._id) == 1, \ 'Only draft documents can be assigned new revisions' # Set the revision if len(fields) > 0: fields.append('revision') self.revision = datetime.now() # Update the document self.upsert(*fields)
[ "def", "new_revision", "(", "self", ",", "*", "fields", ")", ":", "# Ensure this document is a draft", "if", "not", "self", ".", "_id", ":", "assert", "g", ".", "get", "(", "'draft'", ")", ",", "'Only draft documents can be assigned new revisions'", "else", ":", ...
Save a new revision of the document
[ "Save", "a", "new", "revision", "of", "the", "document" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L114-L133
train
26,389
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.delete
def delete(self): """Delete this document and any counterpart document""" with self.draft_context(): draft = self.one(Q._uid == self._uid) if draft: super(PublisherFrame, draft).delete() with self.published_context(): published = self.one(Q._uid == self._uid) if published: super(PublisherFrame, published).delete()
python
def delete(self): """Delete this document and any counterpart document""" with self.draft_context(): draft = self.one(Q._uid == self._uid) if draft: super(PublisherFrame, draft).delete() with self.published_context(): published = self.one(Q._uid == self._uid) if published: super(PublisherFrame, published).delete()
[ "def", "delete", "(", "self", ")", ":", "with", "self", ".", "draft_context", "(", ")", ":", "draft", "=", "self", ".", "one", "(", "Q", ".", "_uid", "==", "self", ".", "_uid", ")", "if", "draft", ":", "super", "(", "PublisherFrame", ",", "draft", ...
Delete this document and any counterpart document
[ "Delete", "this", "document", "and", "any", "counterpart", "document" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L135-L146
train
26,390
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.revert
def revert(self): """Revert the document to currently published version""" with self.draft_context(): draft = self.one(Q._uid == self._uid) with self.published_context(): published = self.one(Q._uid == self._uid) for field, value in draft._document.items(): if field in self._unpublished_fields: continue setattr(draft, field, getattr(published, field)) # Revert the revision draft.revision = published.revision draft.update()
python
def revert(self): """Revert the document to currently published version""" with self.draft_context(): draft = self.one(Q._uid == self._uid) with self.published_context(): published = self.one(Q._uid == self._uid) for field, value in draft._document.items(): if field in self._unpublished_fields: continue setattr(draft, field, getattr(published, field)) # Revert the revision draft.revision = published.revision draft.update()
[ "def", "revert", "(", "self", ")", ":", "with", "self", ".", "draft_context", "(", ")", ":", "draft", "=", "self", ".", "one", "(", "Q", ".", "_uid", "==", "self", ".", "_uid", ")", "with", "self", ".", "published_context", "(", ")", ":", "publishe...
Revert the document to currently published version
[ "Revert", "the", "document", "to", "currently", "published", "version" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L148-L165
train
26,391
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.get_collection
def get_collection(cls): """Return a reference to the database collection for the class""" # By default the collection returned will be the published collection, # however if the `draft` flag has been set against the global context # (e.g `g`) then the collection returned will contain draft documents. if g.get('draft'): return getattr( cls.get_db(), '{collection}_draft'.format(collection=cls._collection) ) return getattr(cls.get_db(), cls._collection)
python
def get_collection(cls): """Return a reference to the database collection for the class""" # By default the collection returned will be the published collection, # however if the `draft` flag has been set against the global context # (e.g `g`) then the collection returned will contain draft documents. if g.get('draft'): return getattr( cls.get_db(), '{collection}_draft'.format(collection=cls._collection) ) return getattr(cls.get_db(), cls._collection)
[ "def", "get_collection", "(", "cls", ")", ":", "# By default the collection returned will be the published collection,", "# however if the `draft` flag has been set against the global context", "# (e.g `g`) then the collection returned will contain draft documents.", "if", "g", ".", "get", ...
Return a reference to the database collection for the class
[ "Return", "a", "reference", "to", "the", "database", "collection", "for", "the", "class" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L168-L181
train
26,392
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.draft_context
def draft_context(cls): """Set the context to draft""" previous_state = g.get('draft') try: g.draft = True yield finally: g.draft = previous_state
python
def draft_context(cls): """Set the context to draft""" previous_state = g.get('draft') try: g.draft = True yield finally: g.draft = previous_state
[ "def", "draft_context", "(", "cls", ")", ":", "previous_state", "=", "g", ".", "get", "(", "'draft'", ")", "try", ":", "g", ".", "draft", "=", "True", "yield", "finally", ":", "g", ".", "draft", "=", "previous_state" ]
Set the context to draft
[ "Set", "the", "context", "to", "draft" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L187-L194
train
26,393
GetmeUK/MongoFrames
snippets/publishing.py
PublisherFrame.published_context
def published_context(cls): """Set the context to published""" previous_state = g.get('draft') try: g.draft = False yield finally: g.draft = previous_state
python
def published_context(cls): """Set the context to published""" previous_state = g.get('draft') try: g.draft = False yield finally: g.draft = previous_state
[ "def", "published_context", "(", "cls", ")", ":", "previous_state", "=", "g", ".", "get", "(", "'draft'", ")", "try", ":", "g", ".", "draft", "=", "False", "yield", "finally", ":", "g", ".", "draft", "=", "previous_state" ]
Set the context to published
[ "Set", "the", "context", "to", "published" ]
7d2bd792235dfa77a9deecab5366f5f73480823d
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/publishing.py#L198-L205
train
26,394
src-d/modelforge
modelforge/registry.py
initialize_registry
def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Initialize the registry and the index. :param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None """ try: backend.reset(args.force) except ExistingBackendError: return 1 log.info("Resetting the index ...") backend.index.reset() try: backend.index.upload("reset", {}) except ValueError: return 1 log.info("Successfully initialized")
python
def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Initialize the registry and the index. :param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None """ try: backend.reset(args.force) except ExistingBackendError: return 1 log.info("Resetting the index ...") backend.index.reset() try: backend.index.upload("reset", {}) except ValueError: return 1 log.info("Successfully initialized")
[ "def", "initialize_registry", "(", "args", ":", "argparse", ".", "Namespace", ",", "backend", ":", "StorageBackend", ",", "log", ":", "logging", ".", "Logger", ")", ":", "try", ":", "backend", ".", "reset", "(", "args", ".", "force", ")", "except", "Exis...
Initialize the registry and the index. :param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None
[ "Initialize", "the", "registry", "and", "the", "index", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/registry.py#L17-L37
train
26,395
src-d/modelforge
modelforge/registry.py
publish_model
def publish_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Push the model to Google Cloud Storage and updates the index file. :param args: :class:`argparse.Namespace` with "model", "backend", "args", "force", "meta" \ "update_default", "username", "password", "remote_repo", "template_model", \ "template_readme" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None if successful, 1 otherwise. """ path = os.path.abspath(args.model) try: model = GenericModel(source=path, dummy=True) except ValueError as e: log.critical('"model" must be a path: %s', e) return 1 except Exception as e: log.critical("Failed to load the model: %s: %s" % (type(e).__name__, e)) return 1 base_meta = model.meta try: model_url = backend.upload_model(path, base_meta, args.force) except ModelAlreadyExistsError: return 1 log.info("Uploaded as %s", model_url) with open(os.path.join(args.meta), encoding="utf-8") as _in: extra_meta = json.load(_in) model_type, model_uuid = base_meta["model"], base_meta["uuid"] meta = extract_model_meta(base_meta, extra_meta, model_url) log.info("Updating the models index...") try: template_model = backend.index.load_template(args.template_model) template_readme = backend.index.load_template(args.template_readme) except ValueError: return 1 backend.index.add_model(model_type, model_uuid, meta, template_model, args.update_default) backend.index.update_readme(template_readme) try: backend.index.upload("add", {"model": model_type, "uuid": model_uuid}) except ValueError: # TODO: replace with PorcelainError, see related TODO in index.py:181 return 1 log.info("Successfully published.")
python
def publish_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Push the model to Google Cloud Storage and updates the index file. :param args: :class:`argparse.Namespace` with "model", "backend", "args", "force", "meta" \ "update_default", "username", "password", "remote_repo", "template_model", \ "template_readme" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None if successful, 1 otherwise. """ path = os.path.abspath(args.model) try: model = GenericModel(source=path, dummy=True) except ValueError as e: log.critical('"model" must be a path: %s', e) return 1 except Exception as e: log.critical("Failed to load the model: %s: %s" % (type(e).__name__, e)) return 1 base_meta = model.meta try: model_url = backend.upload_model(path, base_meta, args.force) except ModelAlreadyExistsError: return 1 log.info("Uploaded as %s", model_url) with open(os.path.join(args.meta), encoding="utf-8") as _in: extra_meta = json.load(_in) model_type, model_uuid = base_meta["model"], base_meta["uuid"] meta = extract_model_meta(base_meta, extra_meta, model_url) log.info("Updating the models index...") try: template_model = backend.index.load_template(args.template_model) template_readme = backend.index.load_template(args.template_readme) except ValueError: return 1 backend.index.add_model(model_type, model_uuid, meta, template_model, args.update_default) backend.index.update_readme(template_readme) try: backend.index.upload("add", {"model": model_type, "uuid": model_uuid}) except ValueError: # TODO: replace with PorcelainError, see related TODO in index.py:181 return 1 log.info("Successfully published.")
[ "def", "publish_model", "(", "args", ":", "argparse", ".", "Namespace", ",", "backend", ":", "StorageBackend", ",", "log", ":", "logging", ".", "Logger", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "model", ")", "try", ...
Push the model to Google Cloud Storage and updates the index file. :param args: :class:`argparse.Namespace` with "model", "backend", "args", "force", "meta" \ "update_default", "username", "password", "remote_repo", "template_model", \ "template_readme" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None if successful, 1 otherwise.
[ "Push", "the", "model", "to", "Google", "Cloud", "Storage", "and", "updates", "the", "index", "file", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/registry.py#L41-L84
train
26,396
src-d/modelforge
modelforge/registry.py
list_models
def list_models(args: argparse.Namespace): """ Output the list of known models in the registry. :param args: :class:`argparse.Namespace` with "username", "password", "remote_repo" and \ "log_level" :return: None """ try: git_index = GitIndex(remote=args.index_repo, username=args.username, password=args.password, cache=args.cache, log_level=args.log_level) except ValueError: return 1 for model_type, models in git_index.models.items(): print(model_type) default = git_index.meta[model_type]["default"] for uuid, model in sorted(models.items(), key=lambda m: parse_datetime(m[1]["created_at"]), reverse=True): print(" %s %s" % ("*" if default == uuid else " ", uuid), model["created_at"])
python
def list_models(args: argparse.Namespace): """ Output the list of known models in the registry. :param args: :class:`argparse.Namespace` with "username", "password", "remote_repo" and \ "log_level" :return: None """ try: git_index = GitIndex(remote=args.index_repo, username=args.username, password=args.password, cache=args.cache, log_level=args.log_level) except ValueError: return 1 for model_type, models in git_index.models.items(): print(model_type) default = git_index.meta[model_type]["default"] for uuid, model in sorted(models.items(), key=lambda m: parse_datetime(m[1]["created_at"]), reverse=True): print(" %s %s" % ("*" if default == uuid else " ", uuid), model["created_at"])
[ "def", "list_models", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "try", ":", "git_index", "=", "GitIndex", "(", "remote", "=", "args", ".", "index_repo", ",", "username", "=", "args", ".", "username", ",", "password", "=", "args", ".", "...
Output the list of known models in the registry. :param args: :class:`argparse.Namespace` with "username", "password", "remote_repo" and \ "log_level" :return: None
[ "Output", "the", "list", "of", "known", "models", "in", "the", "registry", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/registry.py#L87-L107
train
26,397
src-d/modelforge
modelforge/tools.py
install_environment
def install_environment(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Install the packages mentioned in the model's metadata. :param args: :param args: :class:`argparse.Namespace` with "input", "reproduce", "backend", \ "args", "username", "password", "remote_repo" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None """ model = _load_generic_model(args.input, backend, log) if model is None: return 1 packages = ["%s==%s" % (pkg, ver) for pkg, ver in model.environment["packages"]] cmdline = [sys.executable, "-m", "pip", "install"] + args.pip + packages log.info(" ".join(cmdline)) subprocess.check_call(cmdline) if args.reproduce: for dataset in model.datasets: download_http(dataset[0], dataset[1], log)
python
def install_environment(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Install the packages mentioned in the model's metadata. :param args: :param args: :class:`argparse.Namespace` with "input", "reproduce", "backend", \ "args", "username", "password", "remote_repo" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None """ model = _load_generic_model(args.input, backend, log) if model is None: return 1 packages = ["%s==%s" % (pkg, ver) for pkg, ver in model.environment["packages"]] cmdline = [sys.executable, "-m", "pip", "install"] + args.pip + packages log.info(" ".join(cmdline)) subprocess.check_call(cmdline) if args.reproduce: for dataset in model.datasets: download_http(dataset[0], dataset[1], log)
[ "def", "install_environment", "(", "args", ":", "argparse", ".", "Namespace", ",", "backend", ":", "StorageBackend", ",", "log", ":", "logging", ".", "Logger", ")", ":", "model", "=", "_load_generic_model", "(", "args", ".", "input", ",", "backend", ",", "...
Install the packages mentioned in the model's metadata. :param args: :param args: :class:`argparse.Namespace` with "input", "reproduce", "backend", \ "args", "username", "password", "remote_repo" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None
[ "Install", "the", "packages", "mentioned", "in", "the", "model", "s", "metadata", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/tools.py#L13-L32
train
26,398
src-d/modelforge
modelforge/tools.py
dump_model
def dump_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Print the information about the model. :param args: :class:`argparse.Namespace` with "input", "backend", "args", "username", \ "password", "remote_repo" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None """ model = _load_generic_model(args.input, backend, log) if model is None: return 1 print(model)
python
def dump_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): """ Print the information about the model. :param args: :class:`argparse.Namespace` with "input", "backend", "args", "username", \ "password", "remote_repo" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None """ model = _load_generic_model(args.input, backend, log) if model is None: return 1 print(model)
[ "def", "dump_model", "(", "args", ":", "argparse", ".", "Namespace", ",", "backend", ":", "StorageBackend", ",", "log", ":", "logging", ".", "Logger", ")", ":", "model", "=", "_load_generic_model", "(", "args", ".", "input", ",", "backend", ",", "log", "...
Print the information about the model. :param args: :class:`argparse.Namespace` with "input", "backend", "args", "username", \ "password", "remote_repo" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None
[ "Print", "the", "information", "about", "the", "model", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/tools.py#L48-L61
train
26,399