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: - ac...
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: - ac...
[ "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 ...
[ "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 41...
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 41...
[ "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(quer...
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(quer...
[ "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 sp...
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 sp...
[ "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 = [Resp...
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 = [Resp...
[ "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, ...
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, ...
[ "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 versi...
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 versi...
[ "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 ...
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 ...
[ "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 sch...
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 sch...
[ "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) fo...
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) fo...
[ "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", "requ...
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", "requ...
[ "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],...
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],...
[ "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...
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...
[ "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(resour...
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(resour...
[ "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 grap...
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 grap...
[ "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 dynami...
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 dynami...
[ "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 = g...
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 = g...
[ "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_res...
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_res...
[ "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 t...
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 t...
[ "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): ...
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): ...
[ "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_res...
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_res...
[ "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....
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....
[ "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...
[ "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: ...
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: ...
[ "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....
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....
[ "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...
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...
[ "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_h...
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_h...
[ "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): ...
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): ...
[ "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_...
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_...
[ "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_t...
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_t...
[ "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 upd...
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 upd...
[ "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 ...
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 ...
[ "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...
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...
[ "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 `_...
[ "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}) ...
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}) ...
[ "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) ...
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) ...
[ "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(...
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(...
[ "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...
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...
[ "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: ...
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: ...
[ "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), **k...
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), **k...
[ "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_...
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_...
[ "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(...
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(...
[ "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.ge...
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.ge...
[ "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 ...
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 ...
[ "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 ...
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 ...
[ "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}/' i...
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}/' i...
[ "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 # Ge...
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 # Ge...
[ "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, \ 'Databa...
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, \ 'Databa...
[ "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 :) """ ...
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 :) """ ...
[ "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: bre...
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: bre...
[ "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] targe...
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] targe...
[ "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] ...
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] ...
[ "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...
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...
[ "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, ...
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, ...
[ "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() r...
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() r...
[ "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 ...
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 ...
[ "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 ...
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 ...
[ "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 eli...
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 eli...
[ "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 ...
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 ...
[ "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) ...
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) ...
[ "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 ...
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 ...
[ "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 finishe...
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 finishe...
[ "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 met...
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 met...
[ "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 reco...
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 reco...
[ "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} ...
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} ...
[ "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 ...
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 ...
[ "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(): ...
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(): ...
[ "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(): ...
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(): ...
[ "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._...
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._...
[ "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(): ...
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(): ...
[ "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 d...
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 d...
[ "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...
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...
[ "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", "passw...
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", "passw...
[ "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...
[ "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_rep...
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_rep...
[ "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...
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...
[ "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. :p...
[ "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 ...
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 ...
[ "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...
[ "Print", "the", "information", "about", "the", "model", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/tools.py#L48-L61
train
26,399