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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.CreateItem | def CreateItem(self, database_or_Container_link, document, options=None):
"""Creates a document in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param dict document:
The Azure Cosmos document to create.
:param dict options:
The request options for the request.
:param bool options['disableAutomaticIdGeneration']:
Disables the automatic id generation. If id is missing in the body and this
option is true, an error will be returned.
:return:
The created Document.
:rtype:
dict
"""
# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby).
# This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
# So, using a non-mutable deafult in this case(None) and assigning an empty dict(mutable) inside the method
# For more details on this gotcha, please refer http://docs.python-guide.org/en/latest/writing/gotchas/
if options is None:
options = {}
# We check the link to be document collection link since it can be database link in case of client side partitioning
if(base.IsItemContainerLink(database_or_Container_link)):
options = self._AddPartitionKey(database_or_Container_link, document, options)
collection_id, document, path = self._GetContainerIdWithPathForItem(database_or_Container_link, document, options)
return self.Create(document,
path,
'docs',
collection_id,
None,
options) | python | def CreateItem(self, database_or_Container_link, document, options=None):
"""Creates a document in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param dict document:
The Azure Cosmos document to create.
:param dict options:
The request options for the request.
:param bool options['disableAutomaticIdGeneration']:
Disables the automatic id generation. If id is missing in the body and this
option is true, an error will be returned.
:return:
The created Document.
:rtype:
dict
"""
# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby).
# This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
# So, using a non-mutable deafult in this case(None) and assigning an empty dict(mutable) inside the method
# For more details on this gotcha, please refer http://docs.python-guide.org/en/latest/writing/gotchas/
if options is None:
options = {}
# We check the link to be document collection link since it can be database link in case of client side partitioning
if(base.IsItemContainerLink(database_or_Container_link)):
options = self._AddPartitionKey(database_or_Container_link, document, options)
collection_id, document, path = self._GetContainerIdWithPathForItem(database_or_Container_link, document, options)
return self.Create(document,
path,
'docs',
collection_id,
None,
options) | [
"def",
"CreateItem",
"(",
"self",
",",
"database_or_Container_link",
",",
"document",
",",
"options",
"=",
"None",
")",
":",
"# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). ",
"# This means t... | Creates a document in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param dict document:
The Azure Cosmos document to create.
:param dict options:
The request options for the request.
:param bool options['disableAutomaticIdGeneration']:
Disables the automatic id generation. If id is missing in the body and this
option is true, an error will be returned.
:return:
The created Document.
:rtype:
dict | [
"Creates",
"a",
"document",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L987-L1023 | train | 224,400 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.UpsertItem | def UpsertItem(self, database_or_Container_link, document, options=None):
"""Upserts a document in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param dict document:
The Azure Cosmos document to upsert.
:param dict options:
The request options for the request.
:param bool options['disableAutomaticIdGeneration']:
Disables the automatic id generation. If id is missing in the body and this
option is true, an error will be returned.
:return:
The upserted Document.
:rtype:
dict
"""
# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby).
# This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
# So, using a non-mutable deafult in this case(None) and assigning an empty dict(mutable) inside the method
# For more details on this gotcha, please refer http://docs.python-guide.org/en/latest/writing/gotchas/
if options is None:
options = {}
# We check the link to be document collection link since it can be database link in case of client side partitioning
if(base.IsItemContainerLink(database_or_Container_link)):
options = self._AddPartitionKey(database_or_Container_link, document, options)
collection_id, document, path = self._GetContainerIdWithPathForItem(database_or_Container_link, document, options)
return self.Upsert(document,
path,
'docs',
collection_id,
None,
options) | python | def UpsertItem(self, database_or_Container_link, document, options=None):
"""Upserts a document in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param dict document:
The Azure Cosmos document to upsert.
:param dict options:
The request options for the request.
:param bool options['disableAutomaticIdGeneration']:
Disables the automatic id generation. If id is missing in the body and this
option is true, an error will be returned.
:return:
The upserted Document.
:rtype:
dict
"""
# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby).
# This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
# So, using a non-mutable deafult in this case(None) and assigning an empty dict(mutable) inside the method
# For more details on this gotcha, please refer http://docs.python-guide.org/en/latest/writing/gotchas/
if options is None:
options = {}
# We check the link to be document collection link since it can be database link in case of client side partitioning
if(base.IsItemContainerLink(database_or_Container_link)):
options = self._AddPartitionKey(database_or_Container_link, document, options)
collection_id, document, path = self._GetContainerIdWithPathForItem(database_or_Container_link, document, options)
return self.Upsert(document,
path,
'docs',
collection_id,
None,
options) | [
"def",
"UpsertItem",
"(",
"self",
",",
"database_or_Container_link",
",",
"document",
",",
"options",
"=",
"None",
")",
":",
"# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). ",
"# This means t... | Upserts a document in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param dict document:
The Azure Cosmos document to upsert.
:param dict options:
The request options for the request.
:param bool options['disableAutomaticIdGeneration']:
Disables the automatic id generation. If id is missing in the body and this
option is true, an error will be returned.
:return:
The upserted Document.
:rtype:
dict | [
"Upserts",
"a",
"document",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1025-L1061 | train | 224,401 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadItem | def ReadItem(self, document_link, options=None):
"""Reads a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
The read Document.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(document_link)
document_id = base.GetResourceIdOrFullNameFromLink(document_link)
return self.Read(path,
'docs',
document_id,
None,
options) | python | def ReadItem(self, document_link, options=None):
"""Reads a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
The read Document.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(document_link)
document_id = base.GetResourceIdOrFullNameFromLink(document_link)
return self.Read(path,
'docs',
document_id,
None,
options) | [
"def",
"ReadItem",
"(",
"self",
",",
"document_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"document_link",
")",
"document_id",
"=",
"base",... | Reads a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
The read Document.
:rtype:
dict | [
"Reads",
"a",
"document",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1094-L1117 | train | 224,402 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadTriggers | def ReadTriggers(self, collection_link, options=None):
"""Reads all triggers in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of Triggers.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryTriggers(collection_link, None, options) | python | def ReadTriggers(self, collection_link, options=None):
"""Reads all triggers in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of Triggers.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryTriggers(collection_link, None, options) | [
"def",
"ReadTriggers",
"(",
"self",
",",
"collection_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"return",
"self",
".",
"QueryTriggers",
"(",
"collection_link",
",",
"None",
",",
"options",
... | Reads all triggers in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of Triggers.
:rtype:
query_iterable.QueryIterable | [
"Reads",
"all",
"triggers",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1119-L1136 | train | 224,403 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.CreateTrigger | def CreateTrigger(self, collection_link, trigger, options=None):
"""Creates a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The created Trigger.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, trigger = self._GetContainerIdWithPathForTrigger(collection_link, trigger)
return self.Create(trigger,
path,
'triggers',
collection_id,
None,
options) | python | def CreateTrigger(self, collection_link, trigger, options=None):
"""Creates a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The created Trigger.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, trigger = self._GetContainerIdWithPathForTrigger(collection_link, trigger)
return self.Create(trigger,
path,
'triggers',
collection_id,
None,
options) | [
"def",
"CreateTrigger",
"(",
"self",
",",
"collection_link",
",",
"trigger",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"trigger",
"=",
"self",
".",
"_GetContain... | Creates a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The created Trigger.
:rtype:
dict | [
"Creates",
"a",
"trigger",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1168-L1192 | train | 224,404 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.UpsertTrigger | def UpsertTrigger(self, collection_link, trigger, options=None):
"""Upserts a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The upserted Trigger.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, trigger = self._GetContainerIdWithPathForTrigger(collection_link, trigger)
return self.Upsert(trigger,
path,
'triggers',
collection_id,
None,
options) | python | def UpsertTrigger(self, collection_link, trigger, options=None):
"""Upserts a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The upserted Trigger.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, trigger = self._GetContainerIdWithPathForTrigger(collection_link, trigger)
return self.Upsert(trigger,
path,
'triggers',
collection_id,
None,
options) | [
"def",
"UpsertTrigger",
"(",
"self",
",",
"collection_link",
",",
"trigger",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"trigger",
"=",
"self",
".",
"_GetContain... | Upserts a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The upserted Trigger.
:rtype:
dict | [
"Upserts",
"a",
"trigger",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1194-L1218 | train | 224,405 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadTrigger | def ReadTrigger(self, trigger_link, options=None):
"""Reads a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The read Trigger.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(trigger_link)
trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)
return self.Read(path, 'triggers', trigger_id, None, options) | python | def ReadTrigger(self, trigger_link, options=None):
"""Reads a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The read Trigger.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(trigger_link)
trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)
return self.Read(path, 'triggers', trigger_id, None, options) | [
"def",
"ReadTrigger",
"(",
"self",
",",
"trigger_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"trigger_link",
")",
"trigger_id",
"=",
"base",... | Reads a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The read Trigger.
:rtype:
dict | [
"Reads",
"a",
"trigger",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1233-L1252 | train | 224,406 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadUserDefinedFunctions | def ReadUserDefinedFunctions(self, collection_link, options=None):
"""Reads all user defined functions in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of UDFs.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryUserDefinedFunctions(collection_link, None, options) | python | def ReadUserDefinedFunctions(self, collection_link, options=None):
"""Reads all user defined functions in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of UDFs.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryUserDefinedFunctions(collection_link, None, options) | [
"def",
"ReadUserDefinedFunctions",
"(",
"self",
",",
"collection_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"return",
"self",
".",
"QueryUserDefinedFunctions",
"(",
"collection_link",
",",
"None"... | Reads all user defined functions in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of UDFs.
:rtype:
query_iterable.QueryIterable | [
"Reads",
"all",
"user",
"defined",
"functions",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1254-L1271 | train | 224,407 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.QueryUserDefinedFunctions | def QueryUserDefinedFunctions(self, collection_link, query, options=None):
"""Queries user defined functions in a collection.
:param str collection_link:
The link to the collection.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of UDFs.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
path = base.GetPathFromLink(collection_link, 'udfs')
collection_id = base.GetResourceIdOrFullNameFromLink(collection_link)
def fetch_fn(options):
return self.__QueryFeed(path,
'udfs',
collection_id,
lambda r: r['UserDefinedFunctions'],
lambda _, b: b,
query,
options), self.last_response_headers
return query_iterable.QueryIterable(self, query, options, fetch_fn) | python | def QueryUserDefinedFunctions(self, collection_link, query, options=None):
"""Queries user defined functions in a collection.
:param str collection_link:
The link to the collection.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of UDFs.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
path = base.GetPathFromLink(collection_link, 'udfs')
collection_id = base.GetResourceIdOrFullNameFromLink(collection_link)
def fetch_fn(options):
return self.__QueryFeed(path,
'udfs',
collection_id,
lambda r: r['UserDefinedFunctions'],
lambda _, b: b,
query,
options), self.last_response_headers
return query_iterable.QueryIterable(self, query, options, fetch_fn) | [
"def",
"QueryUserDefinedFunctions",
"(",
"self",
",",
"collection_link",
",",
"query",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"collection_link",
... | Queries user defined functions in a collection.
:param str collection_link:
The link to the collection.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of UDFs.
:rtype:
query_iterable.QueryIterable | [
"Queries",
"user",
"defined",
"functions",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1273-L1301 | train | 224,408 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.CreateUserDefinedFunction | def CreateUserDefinedFunction(self, collection_link, udf, options=None):
"""Creates a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
The created UDF.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, udf = self._GetContainerIdWithPathForUDF(collection_link, udf)
return self.Create(udf,
path,
'udfs',
collection_id,
None,
options) | python | def CreateUserDefinedFunction(self, collection_link, udf, options=None):
"""Creates a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
The created UDF.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, udf = self._GetContainerIdWithPathForUDF(collection_link, udf)
return self.Create(udf,
path,
'udfs',
collection_id,
None,
options) | [
"def",
"CreateUserDefinedFunction",
"(",
"self",
",",
"collection_link",
",",
"udf",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"udf",
"=",
"self",
".",
"_GetCon... | Creates a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
The created UDF.
:rtype:
dict | [
"Creates",
"a",
"user",
"defined",
"function",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1303-L1327 | train | 224,409 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.UpsertUserDefinedFunction | def UpsertUserDefinedFunction(self, collection_link, udf, options=None):
"""Upserts a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
The upserted UDF.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, udf = self._GetContainerIdWithPathForUDF(collection_link, udf)
return self.Upsert(udf,
path,
'udfs',
collection_id,
None,
options) | python | def UpsertUserDefinedFunction(self, collection_link, udf, options=None):
"""Upserts a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
The upserted UDF.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, udf = self._GetContainerIdWithPathForUDF(collection_link, udf)
return self.Upsert(udf,
path,
'udfs',
collection_id,
None,
options) | [
"def",
"UpsertUserDefinedFunction",
"(",
"self",
",",
"collection_link",
",",
"udf",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"udf",
"=",
"self",
".",
"_GetCon... | Upserts a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
The upserted UDF.
:rtype:
dict | [
"Upserts",
"a",
"user",
"defined",
"function",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1329-L1353 | train | 224,410 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadUserDefinedFunction | def ReadUserDefinedFunction(self, udf_link, options=None):
"""Reads a user defined function.
:param str udf_link:
The link to the user defined function.
:param dict options:
The request options for the request.
:return:
The read UDF.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(udf_link)
udf_id = base.GetResourceIdOrFullNameFromLink(udf_link)
return self.Read(path, 'udfs', udf_id, None, options) | python | def ReadUserDefinedFunction(self, udf_link, options=None):
"""Reads a user defined function.
:param str udf_link:
The link to the user defined function.
:param dict options:
The request options for the request.
:return:
The read UDF.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(udf_link)
udf_id = base.GetResourceIdOrFullNameFromLink(udf_link)
return self.Read(path, 'udfs', udf_id, None, options) | [
"def",
"ReadUserDefinedFunction",
"(",
"self",
",",
"udf_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"udf_link",
")",
"udf_id",
"=",
"base",... | Reads a user defined function.
:param str udf_link:
The link to the user defined function.
:param dict options:
The request options for the request.
:return:
The read UDF.
:rtype:
dict | [
"Reads",
"a",
"user",
"defined",
"function",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1368-L1387 | train | 224,411 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadStoredProcedures | def ReadStoredProcedures(self, collection_link, options=None):
"""Reads all store procedures in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of Stored Procedures.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryStoredProcedures(collection_link, None, options) | python | def ReadStoredProcedures(self, collection_link, options=None):
"""Reads all store procedures in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of Stored Procedures.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryStoredProcedures(collection_link, None, options) | [
"def",
"ReadStoredProcedures",
"(",
"self",
",",
"collection_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"return",
"self",
".",
"QueryStoredProcedures",
"(",
"collection_link",
",",
"None",
",",... | Reads all store procedures in a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
Query Iterable of Stored Procedures.
:rtype:
query_iterable.QueryIterable | [
"Reads",
"all",
"store",
"procedures",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1389-L1406 | train | 224,412 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.CreateStoredProcedure | def CreateStoredProcedure(self, collection_link, sproc, options=None):
"""Creates a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The created Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, sproc = self._GetContainerIdWithPathForSproc(collection_link, sproc)
return self.Create(sproc,
path,
'sprocs',
collection_id,
None,
options) | python | def CreateStoredProcedure(self, collection_link, sproc, options=None):
"""Creates a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The created Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, sproc = self._GetContainerIdWithPathForSproc(collection_link, sproc)
return self.Create(sproc,
path,
'sprocs',
collection_id,
None,
options) | [
"def",
"CreateStoredProcedure",
"(",
"self",
",",
"collection_link",
",",
"sproc",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"sproc",
"=",
"self",
".",
"_GetCon... | Creates a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The created Stored Procedure.
:rtype:
dict | [
"Creates",
"a",
"stored",
"procedure",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1438-L1462 | train | 224,413 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.UpsertStoredProcedure | def UpsertStoredProcedure(self, collection_link, sproc, options=None):
"""Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The upserted Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, sproc = self._GetContainerIdWithPathForSproc(collection_link, sproc)
return self.Upsert(sproc,
path,
'sprocs',
collection_id,
None,
options) | python | def UpsertStoredProcedure(self, collection_link, sproc, options=None):
"""Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The upserted Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
collection_id, path, sproc = self._GetContainerIdWithPathForSproc(collection_link, sproc)
return self.Upsert(sproc,
path,
'sprocs',
collection_id,
None,
options) | [
"def",
"UpsertStoredProcedure",
"(",
"self",
",",
"collection_link",
",",
"sproc",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"sproc",
"=",
"self",
".",
"_GetCon... | Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The upserted Stored Procedure.
:rtype:
dict | [
"Upserts",
"a",
"stored",
"procedure",
"in",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1464-L1488 | train | 224,414 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadStoredProcedure | def ReadStoredProcedure(self, sproc_link, options=None):
"""Reads a stored procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict options:
The request options for the request.
:return:
The read Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
return self.Read(path, 'sprocs', sproc_id, None, options) | python | def ReadStoredProcedure(self, sproc_link, options=None):
"""Reads a stored procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict options:
The request options for the request.
:return:
The read Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
return self.Read(path, 'sprocs', sproc_id, None, options) | [
"def",
"ReadStoredProcedure",
"(",
"self",
",",
"sproc_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"sproc_link",
")",
"sproc_id",
"=",
"base... | Reads a stored procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict options:
The request options for the request.
:return:
The read Stored Procedure.
:rtype:
dict | [
"Reads",
"a",
"stored",
"procedure",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1502-L1521 | train | 224,415 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadConflicts | def ReadConflicts(self, collection_link, feed_options=None):
"""Reads conflicts.
:param str collection_link:
The link to the document collection.
:param dict feed_options:
:return:
Query Iterable of Conflicts.
:rtype:
query_iterable.QueryIterable
"""
if feed_options is None:
feed_options = {}
return self.QueryConflicts(collection_link, None, feed_options) | python | def ReadConflicts(self, collection_link, feed_options=None):
"""Reads conflicts.
:param str collection_link:
The link to the document collection.
:param dict feed_options:
:return:
Query Iterable of Conflicts.
:rtype:
query_iterable.QueryIterable
"""
if feed_options is None:
feed_options = {}
return self.QueryConflicts(collection_link, None, feed_options) | [
"def",
"ReadConflicts",
"(",
"self",
",",
"collection_link",
",",
"feed_options",
"=",
"None",
")",
":",
"if",
"feed_options",
"is",
"None",
":",
"feed_options",
"=",
"{",
"}",
"return",
"self",
".",
"QueryConflicts",
"(",
"collection_link",
",",
"None",
","... | Reads conflicts.
:param str collection_link:
The link to the document collection.
:param dict feed_options:
:return:
Query Iterable of Conflicts.
:rtype:
query_iterable.QueryIterable | [
"Reads",
"conflicts",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1523-L1539 | train | 224,416 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadConflict | def ReadConflict(self, conflict_link, options=None):
"""Reads a conflict.
:param str conflict_link:
The link to the conflict.
:param dict options:
:return:
The read Conflict.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(conflict_link)
conflict_id = base.GetResourceIdOrFullNameFromLink(conflict_link)
return self.Read(path,
'conflicts',
conflict_id,
None,
options) | python | def ReadConflict(self, conflict_link, options=None):
"""Reads a conflict.
:param str conflict_link:
The link to the conflict.
:param dict options:
:return:
The read Conflict.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(conflict_link)
conflict_id = base.GetResourceIdOrFullNameFromLink(conflict_link)
return self.Read(path,
'conflicts',
conflict_id,
None,
options) | [
"def",
"ReadConflict",
"(",
"self",
",",
"conflict_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"conflict_link",
")",
"conflict_id",
"=",
"ba... | Reads a conflict.
:param str conflict_link:
The link to the conflict.
:param dict options:
:return:
The read Conflict.
:rtype:
dict | [
"Reads",
"a",
"conflict",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1571-L1593 | train | 224,417 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.DeleteContainer | def DeleteContainer(self, collection_link, options=None):
"""Deletes a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
The deleted Collection.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(collection_link)
collection_id = base.GetResourceIdOrFullNameFromLink(collection_link)
return self.DeleteResource(path,
'colls',
collection_id,
None,
options) | python | def DeleteContainer(self, collection_link, options=None):
"""Deletes a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
The deleted Collection.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(collection_link)
collection_id = base.GetResourceIdOrFullNameFromLink(collection_link)
return self.DeleteResource(path,
'colls',
collection_id,
None,
options) | [
"def",
"DeleteContainer",
"(",
"self",
",",
"collection_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"collection_link",
")",
"collection_id",
"... | Deletes a collection.
:param str collection_link:
The link to the document collection.
:param dict options:
The request options for the request.
:return:
The deleted Collection.
:rtype:
dict | [
"Deletes",
"a",
"collection",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1595-L1618 | train | 224,418 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReplaceItem | def ReplaceItem(self, document_link, new_document, options=None):
"""Replaces a document and returns it.
:param str document_link:
The link to the document.
:param dict new_document:
:param dict options:
The request options for the request.
:return:
The new Document.
:rtype:
dict
"""
CosmosClient.__ValidateResource(new_document)
path = base.GetPathFromLink(document_link)
document_id = base.GetResourceIdOrFullNameFromLink(document_link)
# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby).
# This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
# So, using a non-mutable deafult in this case(None) and assigning an empty dict(mutable) inside the function so that it remains local
# For more details on this gotcha, please refer http://docs.python-guide.org/en/latest/writing/gotchas/
if options is None:
options = {}
# Extract the document collection link and add the partition key to options
collection_link = base.GetItemContainerLink(document_link)
options = self._AddPartitionKey(collection_link, new_document, options)
return self.Replace(new_document,
path,
'docs',
document_id,
None,
options) | python | def ReplaceItem(self, document_link, new_document, options=None):
"""Replaces a document and returns it.
:param str document_link:
The link to the document.
:param dict new_document:
:param dict options:
The request options for the request.
:return:
The new Document.
:rtype:
dict
"""
CosmosClient.__ValidateResource(new_document)
path = base.GetPathFromLink(document_link)
document_id = base.GetResourceIdOrFullNameFromLink(document_link)
# Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby).
# This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
# So, using a non-mutable deafult in this case(None) and assigning an empty dict(mutable) inside the function so that it remains local
# For more details on this gotcha, please refer http://docs.python-guide.org/en/latest/writing/gotchas/
if options is None:
options = {}
# Extract the document collection link and add the partition key to options
collection_link = base.GetItemContainerLink(document_link)
options = self._AddPartitionKey(collection_link, new_document, options)
return self.Replace(new_document,
path,
'docs',
document_id,
None,
options) | [
"def",
"ReplaceItem",
"(",
"self",
",",
"document_link",
",",
"new_document",
",",
"options",
"=",
"None",
")",
":",
"CosmosClient",
".",
"__ValidateResource",
"(",
"new_document",
")",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"document_link",
")",
"d... | Replaces a document and returns it.
:param str document_link:
The link to the document.
:param dict new_document:
:param dict options:
The request options for the request.
:return:
The new Document.
:rtype:
dict | [
"Replaces",
"a",
"document",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1620-L1655 | train | 224,419 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.CreateAttachment | def CreateAttachment(self, document_link, attachment, options=None):
"""Creates an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to create.
:param dict options:
The request options for the request.
:return:
The created Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, path = self._GetItemIdWithPathForAttachment(attachment, document_link)
return self.Create(attachment,
path,
'attachments',
document_id,
None,
options) | python | def CreateAttachment(self, document_link, attachment, options=None):
"""Creates an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to create.
:param dict options:
The request options for the request.
:return:
The created Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, path = self._GetItemIdWithPathForAttachment(attachment, document_link)
return self.Create(attachment,
path,
'attachments',
document_id,
None,
options) | [
"def",
"CreateAttachment",
"(",
"self",
",",
"document_link",
",",
"attachment",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"document_id",
",",
"path",
"=",
"self",
".",
"_GetItemIdWithPathForAttachme... | Creates an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to create.
:param dict options:
The request options for the request.
:return:
The created Attachment.
:rtype:
dict | [
"Creates",
"an",
"attachment",
"in",
"a",
"document",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1682-L1707 | train | 224,420 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.UpsertAttachment | def UpsertAttachment(self, document_link, attachment, options=None):
"""Upserts an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to upsert.
:param dict options:
The request options for the request.
:return:
The upserted Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, path = self._GetItemIdWithPathForAttachment(attachment, document_link)
return self.Upsert(attachment,
path,
'attachments',
document_id,
None,
options) | python | def UpsertAttachment(self, document_link, attachment, options=None):
"""Upserts an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to upsert.
:param dict options:
The request options for the request.
:return:
The upserted Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, path = self._GetItemIdWithPathForAttachment(attachment, document_link)
return self.Upsert(attachment,
path,
'attachments',
document_id,
None,
options) | [
"def",
"UpsertAttachment",
"(",
"self",
",",
"document_link",
",",
"attachment",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"document_id",
",",
"path",
"=",
"self",
".",
"_GetItemIdWithPathForAttachme... | Upserts an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to upsert.
:param dict options:
The request options for the request.
:return:
The upserted Attachment.
:rtype:
dict | [
"Upserts",
"an",
"attachment",
"in",
"a",
"document",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1709-L1734 | train | 224,421 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.CreateAttachmentAndUploadMedia | def CreateAttachmentAndUploadMedia(self,
document_link,
readable_stream,
options=None):
"""Creates an attachment and upload media.
:param str document_link:
The link to the document.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The created Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, initial_headers, path = self._GetItemIdWithPathForAttachmentMedia(document_link, options)
return self.Create(readable_stream,
path,
'attachments',
document_id,
initial_headers,
options) | python | def CreateAttachmentAndUploadMedia(self,
document_link,
readable_stream,
options=None):
"""Creates an attachment and upload media.
:param str document_link:
The link to the document.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The created Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, initial_headers, path = self._GetItemIdWithPathForAttachmentMedia(document_link, options)
return self.Create(readable_stream,
path,
'attachments',
document_id,
initial_headers,
options) | [
"def",
"CreateAttachmentAndUploadMedia",
"(",
"self",
",",
"document_link",
",",
"readable_stream",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"document_id",
",",
"initial_headers",
",",
"path",
"=",
... | Creates an attachment and upload media.
:param str document_link:
The link to the document.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The created Attachment.
:rtype:
dict | [
"Creates",
"an",
"attachment",
"and",
"upload",
"media",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1742-L1769 | train | 224,422 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.UpsertAttachmentAndUploadMedia | def UpsertAttachmentAndUploadMedia(self,
document_link,
readable_stream,
options=None):
"""Upserts an attachment and upload media.
:param str document_link:
The link to the document.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The upserted Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, initial_headers, path = self._GetItemIdWithPathForAttachmentMedia(document_link, options)
return self.Upsert(readable_stream,
path,
'attachments',
document_id,
initial_headers,
options) | python | def UpsertAttachmentAndUploadMedia(self,
document_link,
readable_stream,
options=None):
"""Upserts an attachment and upload media.
:param str document_link:
The link to the document.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The upserted Attachment.
:rtype:
dict
"""
if options is None:
options = {}
document_id, initial_headers, path = self._GetItemIdWithPathForAttachmentMedia(document_link, options)
return self.Upsert(readable_stream,
path,
'attachments',
document_id,
initial_headers,
options) | [
"def",
"UpsertAttachmentAndUploadMedia",
"(",
"self",
",",
"document_link",
",",
"readable_stream",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"document_id",
",",
"initial_headers",
",",
"path",
"=",
... | Upserts an attachment and upload media.
:param str document_link:
The link to the document.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The upserted Attachment.
:rtype:
dict | [
"Upserts",
"an",
"attachment",
"and",
"upload",
"media",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1771-L1798 | train | 224,423 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadAttachment | def ReadAttachment(self, attachment_link, options=None):
"""Reads an attachment.
:param str attachment_link:
The link to the attachment.
:param dict options:
The request options for the request.
:return:
The read Attachment.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
return self.Read(path,
'attachments',
attachment_id,
None,
options) | python | def ReadAttachment(self, attachment_link, options=None):
"""Reads an attachment.
:param str attachment_link:
The link to the attachment.
:param dict options:
The request options for the request.
:return:
The read Attachment.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
return self.Read(path,
'attachments',
attachment_id,
None,
options) | [
"def",
"ReadAttachment",
"(",
"self",
",",
"attachment_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"attachment_link",
")",
"attachment_id",
"=... | Reads an attachment.
:param str attachment_link:
The link to the attachment.
:param dict options:
The request options for the request.
:return:
The read Attachment.
:rtype:
dict | [
"Reads",
"an",
"attachment",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1819-L1842 | train | 224,424 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadAttachments | def ReadAttachments(self, document_link, options=None):
"""Reads all attachments in a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
Query Iterable of Attachments.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryAttachments(document_link, None, options) | python | def ReadAttachments(self, document_link, options=None):
"""Reads all attachments in a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
Query Iterable of Attachments.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
return self.QueryAttachments(document_link, None, options) | [
"def",
"ReadAttachments",
"(",
"self",
",",
"document_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"return",
"self",
".",
"QueryAttachments",
"(",
"document_link",
",",
"None",
",",
"options",
... | Reads all attachments in a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
Query Iterable of Attachments.
:rtype:
query_iterable.QueryIterable | [
"Reads",
"all",
"attachments",
"in",
"a",
"document",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1844-L1861 | train | 224,425 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.QueryAttachments | def QueryAttachments(self, document_link, query, options=None):
"""Queries attachments in a document.
:param str document_link:
The link to the document.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of Attachments.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
path = base.GetPathFromLink(document_link, 'attachments')
document_id = base.GetResourceIdOrFullNameFromLink(document_link)
def fetch_fn(options):
return self.__QueryFeed(path,
'attachments',
document_id,
lambda r: r['Attachments'],
lambda _, b: b,
query,
options), self.last_response_headers
return query_iterable.QueryIterable(self, query, options, fetch_fn) | python | def QueryAttachments(self, document_link, query, options=None):
"""Queries attachments in a document.
:param str document_link:
The link to the document.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of Attachments.
:rtype:
query_iterable.QueryIterable
"""
if options is None:
options = {}
path = base.GetPathFromLink(document_link, 'attachments')
document_id = base.GetResourceIdOrFullNameFromLink(document_link)
def fetch_fn(options):
return self.__QueryFeed(path,
'attachments',
document_id,
lambda r: r['Attachments'],
lambda _, b: b,
query,
options), self.last_response_headers
return query_iterable.QueryIterable(self, query, options, fetch_fn) | [
"def",
"QueryAttachments",
"(",
"self",
",",
"document_link",
",",
"query",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"document_link",
",",
"'att... | Queries attachments in a document.
:param str document_link:
The link to the document.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of Attachments.
:rtype:
query_iterable.QueryIterable | [
"Queries",
"attachments",
"in",
"a",
"document",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1863-L1892 | train | 224,426 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadMedia | def ReadMedia(self, media_link):
"""Reads a media.
When self.connection_policy.MediaReadMode ==
documents.MediaReadMode.Streamed, returns a file-like stream object;
otherwise, returns a str.
:param str media_link:
The link to the media.
:return:
The read Media.
:rtype:
str or file-like stream object
"""
default_headers = self.default_headers
path = base.GetPathFromLink(media_link)
media_id = base.GetResourceIdOrFullNameFromLink(media_link)
attachment_id = base.GetAttachmentIdFromMediaId(media_id)
headers = base.GetHeaders(self,
default_headers,
'get',
path,
attachment_id,
'media',
{})
# ReadMedia will always use WriteEndpoint since it's not replicated in readable Geo regions
request = request_object._RequestObject('media', documents._OperationType.Read)
result, self.last_response_headers = self.__Get(path,
request,
headers)
return result | python | def ReadMedia(self, media_link):
"""Reads a media.
When self.connection_policy.MediaReadMode ==
documents.MediaReadMode.Streamed, returns a file-like stream object;
otherwise, returns a str.
:param str media_link:
The link to the media.
:return:
The read Media.
:rtype:
str or file-like stream object
"""
default_headers = self.default_headers
path = base.GetPathFromLink(media_link)
media_id = base.GetResourceIdOrFullNameFromLink(media_link)
attachment_id = base.GetAttachmentIdFromMediaId(media_id)
headers = base.GetHeaders(self,
default_headers,
'get',
path,
attachment_id,
'media',
{})
# ReadMedia will always use WriteEndpoint since it's not replicated in readable Geo regions
request = request_object._RequestObject('media', documents._OperationType.Read)
result, self.last_response_headers = self.__Get(path,
request,
headers)
return result | [
"def",
"ReadMedia",
"(",
"self",
",",
"media_link",
")",
":",
"default_headers",
"=",
"self",
".",
"default_headers",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"media_link",
")",
"media_id",
"=",
"base",
".",
"GetResourceIdOrFullNameFromLink",
"(",
"medi... | Reads a media.
When self.connection_policy.MediaReadMode ==
documents.MediaReadMode.Streamed, returns a file-like stream object;
otherwise, returns a str.
:param str media_link:
The link to the media.
:return:
The read Media.
:rtype:
str or file-like stream object | [
"Reads",
"a",
"media",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1895-L1929 | train | 224,427 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.UpdateMedia | def UpdateMedia(self, media_link, readable_stream, options=None):
"""Updates a media and returns it.
:param str media_link:
The link to the media.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The updated Media.
:rtype:
str or file-like stream object
"""
if options is None:
options = {}
initial_headers = dict(self.default_headers)
# Add required headers slug and content-type in case the body is a stream
if options.get('slug'):
initial_headers[http_constants.HttpHeaders.Slug] = options['slug']
if options.get('contentType'):
initial_headers[http_constants.HttpHeaders.ContentType] = (
options['contentType'])
else:
initial_headers[http_constants.HttpHeaders.ContentType] = (
runtime_constants.MediaTypes.OctetStream)
path = base.GetPathFromLink(media_link)
media_id = base.GetResourceIdOrFullNameFromLink(media_link)
attachment_id = base.GetAttachmentIdFromMediaId(media_id)
headers = base.GetHeaders(self,
initial_headers,
'put',
path,
attachment_id,
'media',
options)
# UpdateMedia will use WriteEndpoint since it uses PUT operation
request = request_object._RequestObject('media', documents._OperationType.Update)
result, self.last_response_headers = self.__Put(path,
request,
readable_stream,
headers)
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | python | def UpdateMedia(self, media_link, readable_stream, options=None):
"""Updates a media and returns it.
:param str media_link:
The link to the media.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The updated Media.
:rtype:
str or file-like stream object
"""
if options is None:
options = {}
initial_headers = dict(self.default_headers)
# Add required headers slug and content-type in case the body is a stream
if options.get('slug'):
initial_headers[http_constants.HttpHeaders.Slug] = options['slug']
if options.get('contentType'):
initial_headers[http_constants.HttpHeaders.ContentType] = (
options['contentType'])
else:
initial_headers[http_constants.HttpHeaders.ContentType] = (
runtime_constants.MediaTypes.OctetStream)
path = base.GetPathFromLink(media_link)
media_id = base.GetResourceIdOrFullNameFromLink(media_link)
attachment_id = base.GetAttachmentIdFromMediaId(media_id)
headers = base.GetHeaders(self,
initial_headers,
'put',
path,
attachment_id,
'media',
options)
# UpdateMedia will use WriteEndpoint since it uses PUT operation
request = request_object._RequestObject('media', documents._OperationType.Update)
result, self.last_response_headers = self.__Put(path,
request,
readable_stream,
headers)
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | [
"def",
"UpdateMedia",
"(",
"self",
",",
"media_link",
",",
"readable_stream",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"initial_headers",
"=",
"dict",
"(",
"self",
".",
"default_headers",
")",
"... | Updates a media and returns it.
:param str media_link:
The link to the media.
:param (file-like stream object) readable_stream:
:param dict options:
The request options for the request.
:return:
The updated Media.
:rtype:
str or file-like stream object | [
"Updates",
"a",
"media",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1931-L1981 | train | 224,428 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReplaceAttachment | def ReplaceAttachment(self, attachment_link, attachment, options=None):
"""Replaces an attachment and returns it.
:param str attachment_link:
The link to the attachment.
:param dict attachment:
:param dict options:
The request options for the request.
:return:
The replaced Attachment
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(attachment)
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
return self.Replace(attachment,
path,
'attachments',
attachment_id,
None,
options) | python | def ReplaceAttachment(self, attachment_link, attachment, options=None):
"""Replaces an attachment and returns it.
:param str attachment_link:
The link to the attachment.
:param dict attachment:
:param dict options:
The request options for the request.
:return:
The replaced Attachment
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(attachment)
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
return self.Replace(attachment,
path,
'attachments',
attachment_id,
None,
options) | [
"def",
"ReplaceAttachment",
"(",
"self",
",",
"attachment_link",
",",
"attachment",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"CosmosClient",
".",
"__ValidateResource",
"(",
"attachment",
")",
"path"... | Replaces an attachment and returns it.
:param str attachment_link:
The link to the attachment.
:param dict attachment:
:param dict options:
The request options for the request.
:return:
The replaced Attachment
:rtype:
dict | [
"Replaces",
"an",
"attachment",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1983-L2009 | train | 224,429 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.DeleteAttachment | def DeleteAttachment(self, attachment_link, options=None):
"""Deletes an attachment.
:param str attachment_link:
The link to the attachment.
:param dict options:
The request options for the request.
:return:
The deleted Attachment.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
return self.DeleteResource(path,
'attachments',
attachment_id,
None,
options) | python | def DeleteAttachment(self, attachment_link, options=None):
"""Deletes an attachment.
:param str attachment_link:
The link to the attachment.
:param dict options:
The request options for the request.
:return:
The deleted Attachment.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
return self.DeleteResource(path,
'attachments',
attachment_id,
None,
options) | [
"def",
"DeleteAttachment",
"(",
"self",
",",
"attachment_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"attachment_link",
")",
"attachment_id",
... | Deletes an attachment.
:param str attachment_link:
The link to the attachment.
:param dict options:
The request options for the request.
:return:
The deleted Attachment.
:rtype:
dict | [
"Deletes",
"an",
"attachment",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2011-L2034 | train | 224,430 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReplaceTrigger | def ReplaceTrigger(self, trigger_link, trigger, options=None):
"""Replaces a trigger and returns it.
:param str trigger_link:
The link to the trigger.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The replaced Trigger.
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(trigger)
trigger = trigger.copy()
if trigger.get('serverScript'):
trigger['body'] = str(trigger['serverScript'])
elif trigger.get('body'):
trigger['body'] = str(trigger['body'])
path = base.GetPathFromLink(trigger_link)
trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)
return self.Replace(trigger,
path,
'triggers',
trigger_id,
None,
options) | python | def ReplaceTrigger(self, trigger_link, trigger, options=None):
"""Replaces a trigger and returns it.
:param str trigger_link:
The link to the trigger.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The replaced Trigger.
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(trigger)
trigger = trigger.copy()
if trigger.get('serverScript'):
trigger['body'] = str(trigger['serverScript'])
elif trigger.get('body'):
trigger['body'] = str(trigger['body'])
path = base.GetPathFromLink(trigger_link)
trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)
return self.Replace(trigger,
path,
'triggers',
trigger_id,
None,
options) | [
"def",
"ReplaceTrigger",
"(",
"self",
",",
"trigger_link",
",",
"trigger",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"CosmosClient",
".",
"__ValidateResource",
"(",
"trigger",
")",
"trigger",
"=",
... | Replaces a trigger and returns it.
:param str trigger_link:
The link to the trigger.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The replaced Trigger.
:rtype:
dict | [
"Replaces",
"a",
"trigger",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2036-L2068 | train | 224,431 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.DeleteTrigger | def DeleteTrigger(self, trigger_link, options=None):
"""Deletes a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The deleted Trigger.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(trigger_link)
trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)
return self.DeleteResource(path,
'triggers',
trigger_id,
None,
options) | python | def DeleteTrigger(self, trigger_link, options=None):
"""Deletes a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The deleted Trigger.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(trigger_link)
trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)
return self.DeleteResource(path,
'triggers',
trigger_id,
None,
options) | [
"def",
"DeleteTrigger",
"(",
"self",
",",
"trigger_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"trigger_link",
")",
"trigger_id",
"=",
"base... | Deletes a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The deleted Trigger.
:rtype:
dict | [
"Deletes",
"a",
"trigger",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2070-L2093 | train | 224,432 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReplaceUserDefinedFunction | def ReplaceUserDefinedFunction(self, udf_link, udf, options=None):
"""Replaces a user defined function and returns it.
:param str udf_link:
The link to the user defined function.
:param dict udf:
:param dict options:
The request options for the request.
:return:
The new UDF.
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(udf)
udf = udf.copy()
if udf.get('serverScript'):
udf['body'] = str(udf['serverScript'])
elif udf.get('body'):
udf['body'] = str(udf['body'])
path = base.GetPathFromLink(udf_link)
udf_id = base.GetResourceIdOrFullNameFromLink(udf_link)
return self.Replace(udf,
path,
'udfs',
udf_id,
None,
options) | python | def ReplaceUserDefinedFunction(self, udf_link, udf, options=None):
"""Replaces a user defined function and returns it.
:param str udf_link:
The link to the user defined function.
:param dict udf:
:param dict options:
The request options for the request.
:return:
The new UDF.
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(udf)
udf = udf.copy()
if udf.get('serverScript'):
udf['body'] = str(udf['serverScript'])
elif udf.get('body'):
udf['body'] = str(udf['body'])
path = base.GetPathFromLink(udf_link)
udf_id = base.GetResourceIdOrFullNameFromLink(udf_link)
return self.Replace(udf,
path,
'udfs',
udf_id,
None,
options) | [
"def",
"ReplaceUserDefinedFunction",
"(",
"self",
",",
"udf_link",
",",
"udf",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"CosmosClient",
".",
"__ValidateResource",
"(",
"udf",
")",
"udf",
"=",
"u... | Replaces a user defined function and returns it.
:param str udf_link:
The link to the user defined function.
:param dict udf:
:param dict options:
The request options for the request.
:return:
The new UDF.
:rtype:
dict | [
"Replaces",
"a",
"user",
"defined",
"function",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2095-L2127 | train | 224,433 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.DeleteUserDefinedFunction | def DeleteUserDefinedFunction(self, udf_link, options=None):
"""Deletes a user defined function.
:param str udf_link:
The link to the user defined function.
:param dict options:
The request options for the request.
:return:
The deleted UDF.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(udf_link)
udf_id = base.GetResourceIdOrFullNameFromLink(udf_link)
return self.DeleteResource(path,
'udfs',
udf_id,
None,
options) | python | def DeleteUserDefinedFunction(self, udf_link, options=None):
"""Deletes a user defined function.
:param str udf_link:
The link to the user defined function.
:param dict options:
The request options for the request.
:return:
The deleted UDF.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(udf_link)
udf_id = base.GetResourceIdOrFullNameFromLink(udf_link)
return self.DeleteResource(path,
'udfs',
udf_id,
None,
options) | [
"def",
"DeleteUserDefinedFunction",
"(",
"self",
",",
"udf_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"udf_link",
")",
"udf_id",
"=",
"base... | Deletes a user defined function.
:param str udf_link:
The link to the user defined function.
:param dict options:
The request options for the request.
:return:
The deleted UDF.
:rtype:
dict | [
"Deletes",
"a",
"user",
"defined",
"function",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2129-L2152 | train | 224,434 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ExecuteStoredProcedure | def ExecuteStoredProcedure(self, sproc_link, params, options=None):
"""Executes a store procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict params:
List or None
:param dict options:
The request options for the request.
:return:
The Stored Procedure response.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = dict(self.default_headers)
initial_headers.update({
http_constants.HttpHeaders.Accept: (
runtime_constants.MediaTypes.Json)
})
if params and not type(params) is list:
params = [params]
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
headers = base.GetHeaders(self,
initial_headers,
'post',
path,
sproc_id,
'sprocs',
options)
# ExecuteStoredProcedure will use WriteEndpoint since it uses POST operation
request = request_object._RequestObject('sprocs', documents._OperationType.ExecuteJavaScript)
result, self.last_response_headers = self.__Post(path,
request,
params,
headers)
return result | python | def ExecuteStoredProcedure(self, sproc_link, params, options=None):
"""Executes a store procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict params:
List or None
:param dict options:
The request options for the request.
:return:
The Stored Procedure response.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = dict(self.default_headers)
initial_headers.update({
http_constants.HttpHeaders.Accept: (
runtime_constants.MediaTypes.Json)
})
if params and not type(params) is list:
params = [params]
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
headers = base.GetHeaders(self,
initial_headers,
'post',
path,
sproc_id,
'sprocs',
options)
# ExecuteStoredProcedure will use WriteEndpoint since it uses POST operation
request = request_object._RequestObject('sprocs', documents._OperationType.ExecuteJavaScript)
result, self.last_response_headers = self.__Post(path,
request,
params,
headers)
return result | [
"def",
"ExecuteStoredProcedure",
"(",
"self",
",",
"sproc_link",
",",
"params",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"initial_headers",
"=",
"dict",
"(",
"self",
".",
"default_headers",
")",
... | Executes a store procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict params:
List or None
:param dict options:
The request options for the request.
:return:
The Stored Procedure response.
:rtype:
dict | [
"Executes",
"a",
"store",
"procedure",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2154-L2198 | train | 224,435 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReplaceStoredProcedure | def ReplaceStoredProcedure(self, sproc_link, sproc, options=None):
"""Replaces a stored procedure and returns it.
:param str sproc_link:
The link to the stored procedure.
:param dict sproc:
:param dict options:
The request options for the request.
:return:
The replaced Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(sproc)
sproc = sproc.copy()
if sproc.get('serverScript'):
sproc['body'] = str(sproc['serverScript'])
elif sproc.get('body'):
sproc['body'] = str(sproc['body'])
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
return self.Replace(sproc,
path,
'sprocs',
sproc_id,
None,
options) | python | def ReplaceStoredProcedure(self, sproc_link, sproc, options=None):
"""Replaces a stored procedure and returns it.
:param str sproc_link:
The link to the stored procedure.
:param dict sproc:
:param dict options:
The request options for the request.
:return:
The replaced Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
CosmosClient.__ValidateResource(sproc)
sproc = sproc.copy()
if sproc.get('serverScript'):
sproc['body'] = str(sproc['serverScript'])
elif sproc.get('body'):
sproc['body'] = str(sproc['body'])
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
return self.Replace(sproc,
path,
'sprocs',
sproc_id,
None,
options) | [
"def",
"ReplaceStoredProcedure",
"(",
"self",
",",
"sproc_link",
",",
"sproc",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"CosmosClient",
".",
"__ValidateResource",
"(",
"sproc",
")",
"sproc",
"=",
... | Replaces a stored procedure and returns it.
:param str sproc_link:
The link to the stored procedure.
:param dict sproc:
:param dict options:
The request options for the request.
:return:
The replaced Stored Procedure.
:rtype:
dict | [
"Replaces",
"a",
"stored",
"procedure",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2200-L2232 | train | 224,436 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.DeleteStoredProcedure | def DeleteStoredProcedure(self, sproc_link, options=None):
"""Deletes a stored procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict options:
The request options for the request.
:return:
The deleted Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
return self.DeleteResource(path,
'sprocs',
sproc_id,
None,
options) | python | def DeleteStoredProcedure(self, sproc_link, options=None):
"""Deletes a stored procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict options:
The request options for the request.
:return:
The deleted Stored Procedure.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(sproc_link)
sproc_id = base.GetResourceIdOrFullNameFromLink(sproc_link)
return self.DeleteResource(path,
'sprocs',
sproc_id,
None,
options) | [
"def",
"DeleteStoredProcedure",
"(",
"self",
",",
"sproc_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"sproc_link",
")",
"sproc_id",
"=",
"ba... | Deletes a stored procedure.
:param str sproc_link:
The link to the stored procedure.
:param dict options:
The request options for the request.
:return:
The deleted Stored Procedure.
:rtype:
dict | [
"Deletes",
"a",
"stored",
"procedure",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2234-L2257 | train | 224,437 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.DeleteConflict | def DeleteConflict(self, conflict_link, options=None):
"""Deletes a conflict.
:param str conflict_link:
The link to the conflict.
:param dict options:
The request options for the request.
:return:
The deleted Conflict.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(conflict_link)
conflict_id = base.GetResourceIdOrFullNameFromLink(conflict_link)
return self.DeleteResource(path,
'conflicts',
conflict_id,
None,
options) | python | def DeleteConflict(self, conflict_link, options=None):
"""Deletes a conflict.
:param str conflict_link:
The link to the conflict.
:param dict options:
The request options for the request.
:return:
The deleted Conflict.
:rtype:
dict
"""
if options is None:
options = {}
path = base.GetPathFromLink(conflict_link)
conflict_id = base.GetResourceIdOrFullNameFromLink(conflict_link)
return self.DeleteResource(path,
'conflicts',
conflict_id,
None,
options) | [
"def",
"DeleteConflict",
"(",
"self",
",",
"conflict_link",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"conflict_link",
")",
"conflict_id",
"=",
"... | Deletes a conflict.
:param str conflict_link:
The link to the conflict.
:param dict options:
The request options for the request.
:return:
The deleted Conflict.
:rtype:
dict | [
"Deletes",
"a",
"conflict",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2259-L2282 | train | 224,438 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReplaceOffer | def ReplaceOffer(self, offer_link, offer):
"""Replaces an offer and returns it.
:param str offer_link:
The link to the offer.
:param dict offer:
:return:
The replaced Offer.
:rtype:
dict
"""
CosmosClient.__ValidateResource(offer)
path = base.GetPathFromLink(offer_link)
offer_id = base.GetResourceIdOrFullNameFromLink(offer_link)
return self.Replace(offer, path, 'offers', offer_id, None, None) | python | def ReplaceOffer(self, offer_link, offer):
"""Replaces an offer and returns it.
:param str offer_link:
The link to the offer.
:param dict offer:
:return:
The replaced Offer.
:rtype:
dict
"""
CosmosClient.__ValidateResource(offer)
path = base.GetPathFromLink(offer_link)
offer_id = base.GetResourceIdOrFullNameFromLink(offer_link)
return self.Replace(offer, path, 'offers', offer_id, None, None) | [
"def",
"ReplaceOffer",
"(",
"self",
",",
"offer_link",
",",
"offer",
")",
":",
"CosmosClient",
".",
"__ValidateResource",
"(",
"offer",
")",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"offer_link",
")",
"offer_id",
"=",
"base",
".",
"GetResourceIdOrFull... | Replaces an offer and returns it.
:param str offer_link:
The link to the offer.
:param dict offer:
:return:
The replaced Offer.
:rtype:
dict | [
"Replaces",
"an",
"offer",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2284-L2300 | train | 224,439 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.ReadOffer | def ReadOffer(self, offer_link):
"""Reads an offer.
:param str offer_link:
The link to the offer.
:return:
The read Offer.
:rtype:
dict
"""
path = base.GetPathFromLink(offer_link)
offer_id = base.GetResourceIdOrFullNameFromLink(offer_link)
return self.Read(path, 'offers', offer_id, None, {}) | python | def ReadOffer(self, offer_link):
"""Reads an offer.
:param str offer_link:
The link to the offer.
:return:
The read Offer.
:rtype:
dict
"""
path = base.GetPathFromLink(offer_link)
offer_id = base.GetResourceIdOrFullNameFromLink(offer_link)
return self.Read(path, 'offers', offer_id, None, {}) | [
"def",
"ReadOffer",
"(",
"self",
",",
"offer_link",
")",
":",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"offer_link",
")",
"offer_id",
"=",
"base",
".",
"GetResourceIdOrFullNameFromLink",
"(",
"offer_link",
")",
"return",
"self",
".",
"Read",
"(",
"p... | Reads an offer.
:param str offer_link:
The link to the offer.
:return:
The read Offer.
:rtype:
dict | [
"Reads",
"an",
"offer",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2302-L2316 | train | 224,440 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.GetDatabaseAccount | def GetDatabaseAccount(self, url_connection=None):
"""Gets database account info.
:return:
The Database Account.
:rtype:
documents.DatabaseAccount
"""
if url_connection is None:
url_connection = self.url_connection
initial_headers = dict(self.default_headers)
headers = base.GetHeaders(self,
initial_headers,
'get',
'', # path
'', # id
'', # type
{})
request = request_object._RequestObject('databaseaccount', documents._OperationType.Read, url_connection)
result, self.last_response_headers = self.__Get('',
request,
headers)
database_account = documents.DatabaseAccount()
database_account.DatabasesLink = '/dbs/'
database_account.MediaLink = '/media/'
if (http_constants.HttpHeaders.MaxMediaStorageUsageInMB in
self.last_response_headers):
database_account.MaxMediaStorageUsageInMB = (
self.last_response_headers[
http_constants.HttpHeaders.MaxMediaStorageUsageInMB])
if (http_constants.HttpHeaders.CurrentMediaStorageUsageInMB in
self.last_response_headers):
database_account.CurrentMediaStorageUsageInMB = (
self.last_response_headers[
http_constants.HttpHeaders.CurrentMediaStorageUsageInMB])
database_account.ConsistencyPolicy = result.get(constants._Constants.UserConsistencyPolicy)
# WritableLocations and ReadableLocations fields will be available only for geo-replicated database accounts
if constants._Constants.WritableLocations in result:
database_account._WritableLocations = result[constants._Constants.WritableLocations]
if constants._Constants.ReadableLocations in result:
database_account._ReadableLocations = result[constants._Constants.ReadableLocations]
if constants._Constants.EnableMultipleWritableLocations in result:
database_account._EnableMultipleWritableLocations = result[constants._Constants.EnableMultipleWritableLocations]
self._useMultipleWriteLocations = self.connection_policy.UseMultipleWriteLocations and database_account._EnableMultipleWritableLocations
return database_account | python | def GetDatabaseAccount(self, url_connection=None):
"""Gets database account info.
:return:
The Database Account.
:rtype:
documents.DatabaseAccount
"""
if url_connection is None:
url_connection = self.url_connection
initial_headers = dict(self.default_headers)
headers = base.GetHeaders(self,
initial_headers,
'get',
'', # path
'', # id
'', # type
{})
request = request_object._RequestObject('databaseaccount', documents._OperationType.Read, url_connection)
result, self.last_response_headers = self.__Get('',
request,
headers)
database_account = documents.DatabaseAccount()
database_account.DatabasesLink = '/dbs/'
database_account.MediaLink = '/media/'
if (http_constants.HttpHeaders.MaxMediaStorageUsageInMB in
self.last_response_headers):
database_account.MaxMediaStorageUsageInMB = (
self.last_response_headers[
http_constants.HttpHeaders.MaxMediaStorageUsageInMB])
if (http_constants.HttpHeaders.CurrentMediaStorageUsageInMB in
self.last_response_headers):
database_account.CurrentMediaStorageUsageInMB = (
self.last_response_headers[
http_constants.HttpHeaders.CurrentMediaStorageUsageInMB])
database_account.ConsistencyPolicy = result.get(constants._Constants.UserConsistencyPolicy)
# WritableLocations and ReadableLocations fields will be available only for geo-replicated database accounts
if constants._Constants.WritableLocations in result:
database_account._WritableLocations = result[constants._Constants.WritableLocations]
if constants._Constants.ReadableLocations in result:
database_account._ReadableLocations = result[constants._Constants.ReadableLocations]
if constants._Constants.EnableMultipleWritableLocations in result:
database_account._EnableMultipleWritableLocations = result[constants._Constants.EnableMultipleWritableLocations]
self._useMultipleWriteLocations = self.connection_policy.UseMultipleWriteLocations and database_account._EnableMultipleWritableLocations
return database_account | [
"def",
"GetDatabaseAccount",
"(",
"self",
",",
"url_connection",
"=",
"None",
")",
":",
"if",
"url_connection",
"is",
"None",
":",
"url_connection",
"=",
"self",
".",
"url_connection",
"initial_headers",
"=",
"dict",
"(",
"self",
".",
"default_headers",
")",
"... | Gets database account info.
:return:
The Database Account.
:rtype:
documents.DatabaseAccount | [
"Gets",
"database",
"account",
"info",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2361-L2410 | train | 224,441 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.Create | def Create(self, body, path, type, id, initial_headers, options=None):
"""Creates a Azure Cosmos resource and returns it.
:param dict body:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The created Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'post',
path,
id,
type,
options)
# Create will use WriteEndpoint since it uses POST operation
request = request_object._RequestObject(type, documents._OperationType.Create)
result, self.last_response_headers = self.__Post(path,
request,
body,
headers)
# update session for write request
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | python | def Create(self, body, path, type, id, initial_headers, options=None):
"""Creates a Azure Cosmos resource and returns it.
:param dict body:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The created Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'post',
path,
id,
type,
options)
# Create will use WriteEndpoint since it uses POST operation
request = request_object._RequestObject(type, documents._OperationType.Create)
result, self.last_response_headers = self.__Post(path,
request,
body,
headers)
# update session for write request
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | [
"def",
"Create",
"(",
"self",
",",
"body",
",",
"path",
",",
"type",
",",
"id",
",",
"initial_headers",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"initial_headers",
"=",
"initial_headers",
"or"... | Creates a Azure Cosmos resource and returns it.
:param dict body:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The created Azure Cosmos resource.
:rtype:
dict | [
"Creates",
"a",
"Azure",
"Cosmos",
"resource",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2412-L2450 | train | 224,442 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.Replace | def Replace(self, resource, path, type, id, initial_headers, options=None):
"""Replaces a Azure Cosmos resource and returns it.
:param dict resource:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The new Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'put',
path,
id,
type,
options)
# Replace will use WriteEndpoint since it uses PUT operation
request = request_object._RequestObject(type, documents._OperationType.Replace)
result, self.last_response_headers = self.__Put(path,
request,
resource,
headers)
# update session for request mutates data on server side
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | python | def Replace(self, resource, path, type, id, initial_headers, options=None):
"""Replaces a Azure Cosmos resource and returns it.
:param dict resource:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The new Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'put',
path,
id,
type,
options)
# Replace will use WriteEndpoint since it uses PUT operation
request = request_object._RequestObject(type, documents._OperationType.Replace)
result, self.last_response_headers = self.__Put(path,
request,
resource,
headers)
# update session for request mutates data on server side
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | [
"def",
"Replace",
"(",
"self",
",",
"resource",
",",
"path",
",",
"type",
",",
"id",
",",
"initial_headers",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"initial_headers",
"=",
"initial_headers",
... | Replaces a Azure Cosmos resource and returns it.
:param dict resource:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The new Azure Cosmos resource.
:rtype:
dict | [
"Replaces",
"a",
"Azure",
"Cosmos",
"resource",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2493-L2530 | train | 224,443 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.Read | def Read(self, path, type, id, initial_headers, options=None):
"""Reads a Azure Cosmos resource and returns it.
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The upserted Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'get',
path,
id,
type,
options)
# Read will use ReadEndpoint since it uses GET operation
request = request_object._RequestObject(type, documents._OperationType.Read)
result, self.last_response_headers = self.__Get(path,
request,
headers)
return result | python | def Read(self, path, type, id, initial_headers, options=None):
"""Reads a Azure Cosmos resource and returns it.
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The upserted Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'get',
path,
id,
type,
options)
# Read will use ReadEndpoint since it uses GET operation
request = request_object._RequestObject(type, documents._OperationType.Read)
result, self.last_response_headers = self.__Get(path,
request,
headers)
return result | [
"def",
"Read",
"(",
"self",
",",
"path",
",",
"type",
",",
"id",
",",
"initial_headers",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"initial_headers",
"=",
"initial_headers",
"or",
"self",
".",
... | Reads a Azure Cosmos resource and returns it.
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The upserted Azure Cosmos resource.
:rtype:
dict | [
"Reads",
"a",
"Azure",
"Cosmos",
"resource",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2532-L2564 | train | 224,444 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.DeleteResource | def DeleteResource(self, path, type, id, initial_headers, options=None):
"""Deletes a Azure Cosmos resource and returns it.
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The deleted Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'delete',
path,
id,
type,
options)
# Delete will use WriteEndpoint since it uses DELETE operation
request = request_object._RequestObject(type, documents._OperationType.Delete)
result, self.last_response_headers = self.__Delete(path,
request,
headers)
# update session for request mutates data on server side
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | python | def DeleteResource(self, path, type, id, initial_headers, options=None):
"""Deletes a Azure Cosmos resource and returns it.
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The deleted Azure Cosmos resource.
:rtype:
dict
"""
if options is None:
options = {}
initial_headers = initial_headers or self.default_headers
headers = base.GetHeaders(self,
initial_headers,
'delete',
path,
id,
type,
options)
# Delete will use WriteEndpoint since it uses DELETE operation
request = request_object._RequestObject(type, documents._OperationType.Delete)
result, self.last_response_headers = self.__Delete(path,
request,
headers)
# update session for request mutates data on server side
self._UpdateSessionIfRequired(headers, result, self.last_response_headers)
return result | [
"def",
"DeleteResource",
"(",
"self",
",",
"path",
",",
"type",
",",
"id",
",",
"initial_headers",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"initial_headers",
"=",
"initial_headers",
"or",
"self... | Deletes a Azure Cosmos resource and returns it.
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The deleted Azure Cosmos resource.
:rtype:
dict | [
"Deletes",
"a",
"Azure",
"Cosmos",
"resource",
"and",
"returns",
"it",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2566-L2603 | train | 224,445 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.__Get | def __Get(self, path, request, headers):
"""Azure Cosmos 'GET' http request.
:params str url:
:params str path:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict)
"""
return synchronized_request.SynchronizedRequest(self,
request,
self._global_endpoint_manager,
self.connection_policy,
self._requests_session,
'GET',
path,
None,
None,
headers) | python | def __Get(self, path, request, headers):
"""Azure Cosmos 'GET' http request.
:params str url:
:params str path:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict)
"""
return synchronized_request.SynchronizedRequest(self,
request,
self._global_endpoint_manager,
self.connection_policy,
self._requests_session,
'GET',
path,
None,
None,
headers) | [
"def",
"__Get",
"(",
"self",
",",
"path",
",",
"request",
",",
"headers",
")",
":",
"return",
"synchronized_request",
".",
"SynchronizedRequest",
"(",
"self",
",",
"request",
",",
"self",
".",
"_global_endpoint_manager",
",",
"self",
".",
"connection_policy",
... | Azure Cosmos 'GET' http request.
:params str url:
:params str path:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict) | [
"Azure",
"Cosmos",
"GET",
"http",
"request",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2605-L2627 | train | 224,446 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.__Post | def __Post(self, path, request, body, headers):
"""Azure Cosmos 'POST' http request.
:params str url:
:params str path:
:params (str, unicode, dict) body:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict)
"""
return synchronized_request.SynchronizedRequest(self,
request,
self._global_endpoint_manager,
self.connection_policy,
self._requests_session,
'POST',
path,
body,
query_params=None,
headers=headers) | python | def __Post(self, path, request, body, headers):
"""Azure Cosmos 'POST' http request.
:params str url:
:params str path:
:params (str, unicode, dict) body:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict)
"""
return synchronized_request.SynchronizedRequest(self,
request,
self._global_endpoint_manager,
self.connection_policy,
self._requests_session,
'POST',
path,
body,
query_params=None,
headers=headers) | [
"def",
"__Post",
"(",
"self",
",",
"path",
",",
"request",
",",
"body",
",",
"headers",
")",
":",
"return",
"synchronized_request",
".",
"SynchronizedRequest",
"(",
"self",
",",
"request",
",",
"self",
".",
"_global_endpoint_manager",
",",
"self",
".",
"conn... | Azure Cosmos 'POST' http request.
:params str url:
:params str path:
:params (str, unicode, dict) body:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict) | [
"Azure",
"Cosmos",
"POST",
"http",
"request",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2629-L2652 | train | 224,447 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.__Delete | def __Delete(self, path, request, headers):
"""Azure Cosmos 'DELETE' http request.
:params str url:
:params str path:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict)
"""
return synchronized_request.SynchronizedRequest(self,
request,
self._global_endpoint_manager,
self.connection_policy,
self._requests_session,
'DELETE',
path,
request_data=None,
query_params=None,
headers=headers) | python | def __Delete(self, path, request, headers):
"""Azure Cosmos 'DELETE' http request.
:params str url:
:params str path:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict)
"""
return synchronized_request.SynchronizedRequest(self,
request,
self._global_endpoint_manager,
self.connection_policy,
self._requests_session,
'DELETE',
path,
request_data=None,
query_params=None,
headers=headers) | [
"def",
"__Delete",
"(",
"self",
",",
"path",
",",
"request",
",",
"headers",
")",
":",
"return",
"synchronized_request",
".",
"SynchronizedRequest",
"(",
"self",
",",
"request",
",",
"self",
".",
"_global_endpoint_manager",
",",
"self",
".",
"connection_policy",... | Azure Cosmos 'DELETE' http request.
:params str url:
:params str path:
:params dict headers:
:return:
Tuple of (result, headers).
:rtype:
tuple of (dict, dict) | [
"Azure",
"Cosmos",
"DELETE",
"http",
"request",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2679-L2701 | train | 224,448 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.QueryFeed | def QueryFeed(self, path, collection_id, query, options, partition_key_range_id = None):
"""Query Feed for Document Collection resource.
:param str path:
Path to the document collection.
:param str collection_id:
Id of the document collection.
:param (str or dict) query:
:param dict options:
The request options for the request.
:param str partition_key_range_id:
Partition key range id.
:rtype:
tuple
"""
return self.__QueryFeed(path,
'docs',
collection_id,
lambda r: r['Documents'],
lambda _, b: b,
query,
options,
partition_key_range_id), self.last_response_headers | python | def QueryFeed(self, path, collection_id, query, options, partition_key_range_id = None):
"""Query Feed for Document Collection resource.
:param str path:
Path to the document collection.
:param str collection_id:
Id of the document collection.
:param (str or dict) query:
:param dict options:
The request options for the request.
:param str partition_key_range_id:
Partition key range id.
:rtype:
tuple
"""
return self.__QueryFeed(path,
'docs',
collection_id,
lambda r: r['Documents'],
lambda _, b: b,
query,
options,
partition_key_range_id), self.last_response_headers | [
"def",
"QueryFeed",
"(",
"self",
",",
"path",
",",
"collection_id",
",",
"query",
",",
"options",
",",
"partition_key_range_id",
"=",
"None",
")",
":",
"return",
"self",
".",
"__QueryFeed",
"(",
"path",
",",
"'docs'",
",",
"collection_id",
",",
"lambda",
"... | Query Feed for Document Collection resource.
:param str path:
Path to the document collection.
:param str collection_id:
Id of the document collection.
:param (str or dict) query:
:param dict options:
The request options for the request.
:param str partition_key_range_id:
Partition key range id.
:rtype:
tuple | [
"Query",
"Feed",
"for",
"Document",
"Collection",
"resource",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2703-L2726 | train | 224,449 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.__QueryFeed | def __QueryFeed(self,
path,
type,
id,
result_fn,
create_fn,
query,
options=None,
partition_key_range_id=None):
"""Query for more than one Azure Cosmos resources.
:param str path:
:param str type:
:param str id:
:param function result_fn:
:param function create_fn:
:param (str or dict) query:
:param dict options:
The request options for the request.
:param str partition_key_range_id:
Specifies partition key range id.
:rtype:
list
:raises SystemError: If the query compatibility mode is undefined.
"""
if options is None:
options = {}
if query:
__GetBodiesFromQueryResult = result_fn
else:
def __GetBodiesFromQueryResult(result):
if result is not None:
return [create_fn(self, body) for body in result_fn(result)]
else:
# If there is no change feed, the result data is empty and result is None.
# This case should be interpreted as an empty array.
return []
initial_headers = self.default_headers.copy()
# Copy to make sure that default_headers won't be changed.
if query is None:
# Query operations will use ReadEndpoint even though it uses GET(for feed requests)
request = request_object._RequestObject(type, documents._OperationType.ReadFeed)
headers = base.GetHeaders(self,
initial_headers,
'get',
path,
id,
type,
options,
partition_key_range_id)
result, self.last_response_headers = self.__Get(path,
request,
headers)
return __GetBodiesFromQueryResult(result)
else:
query = self.__CheckAndUnifyQueryFormat(query)
initial_headers[http_constants.HttpHeaders.IsQuery] = 'true'
if (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Default or
self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Query):
initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.QueryJson
elif self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.SqlQuery:
initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.SQL
else:
raise SystemError('Unexpected query compatibility mode.')
# Query operations will use ReadEndpoint even though it uses POST(for regular query operations)
request = request_object._RequestObject(type, documents._OperationType.SqlQuery)
headers = base.GetHeaders(self,
initial_headers,
'post',
path,
id,
type,
options,
partition_key_range_id)
result, self.last_response_headers = self.__Post(path,
request,
query,
headers)
return __GetBodiesFromQueryResult(result) | python | def __QueryFeed(self,
path,
type,
id,
result_fn,
create_fn,
query,
options=None,
partition_key_range_id=None):
"""Query for more than one Azure Cosmos resources.
:param str path:
:param str type:
:param str id:
:param function result_fn:
:param function create_fn:
:param (str or dict) query:
:param dict options:
The request options for the request.
:param str partition_key_range_id:
Specifies partition key range id.
:rtype:
list
:raises SystemError: If the query compatibility mode is undefined.
"""
if options is None:
options = {}
if query:
__GetBodiesFromQueryResult = result_fn
else:
def __GetBodiesFromQueryResult(result):
if result is not None:
return [create_fn(self, body) for body in result_fn(result)]
else:
# If there is no change feed, the result data is empty and result is None.
# This case should be interpreted as an empty array.
return []
initial_headers = self.default_headers.copy()
# Copy to make sure that default_headers won't be changed.
if query is None:
# Query operations will use ReadEndpoint even though it uses GET(for feed requests)
request = request_object._RequestObject(type, documents._OperationType.ReadFeed)
headers = base.GetHeaders(self,
initial_headers,
'get',
path,
id,
type,
options,
partition_key_range_id)
result, self.last_response_headers = self.__Get(path,
request,
headers)
return __GetBodiesFromQueryResult(result)
else:
query = self.__CheckAndUnifyQueryFormat(query)
initial_headers[http_constants.HttpHeaders.IsQuery] = 'true'
if (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Default or
self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Query):
initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.QueryJson
elif self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.SqlQuery:
initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.SQL
else:
raise SystemError('Unexpected query compatibility mode.')
# Query operations will use ReadEndpoint even though it uses POST(for regular query operations)
request = request_object._RequestObject(type, documents._OperationType.SqlQuery)
headers = base.GetHeaders(self,
initial_headers,
'post',
path,
id,
type,
options,
partition_key_range_id)
result, self.last_response_headers = self.__Post(path,
request,
query,
headers)
return __GetBodiesFromQueryResult(result) | [
"def",
"__QueryFeed",
"(",
"self",
",",
"path",
",",
"type",
",",
"id",
",",
"result_fn",
",",
"create_fn",
",",
"query",
",",
"options",
"=",
"None",
",",
"partition_key_range_id",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
... | Query for more than one Azure Cosmos resources.
:param str path:
:param str type:
:param str id:
:param function result_fn:
:param function create_fn:
:param (str or dict) query:
:param dict options:
The request options for the request.
:param str partition_key_range_id:
Specifies partition key range id.
:rtype:
list
:raises SystemError: If the query compatibility mode is undefined. | [
"Query",
"for",
"more",
"than",
"one",
"Azure",
"Cosmos",
"resources",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2728-L2814 | train | 224,450 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient.__CheckAndUnifyQueryFormat | def __CheckAndUnifyQueryFormat(self, query_body):
"""Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
:raises SystemError: If the query compatibility mode is undefined.
:param (str or dict) query_body:
:return:
The formatted query body.
:rtype:
dict or string
"""
if (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Default or
self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Query):
if not isinstance(query_body, dict) and not isinstance(query_body, six.string_types):
raise TypeError('query body must be a dict or string.')
if isinstance(query_body, dict) and not query_body.get('query'):
raise ValueError('query body must have valid query text with key "query".')
if isinstance(query_body, six.string_types):
return {'query': query_body}
elif (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.SqlQuery and
not isinstance(query_body, six.string_types)):
raise TypeError('query body must be a string.')
else:
raise SystemError('Unexpected query compatibility mode.')
return query_body | python | def __CheckAndUnifyQueryFormat(self, query_body):
"""Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
:raises SystemError: If the query compatibility mode is undefined.
:param (str or dict) query_body:
:return:
The formatted query body.
:rtype:
dict or string
"""
if (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Default or
self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Query):
if not isinstance(query_body, dict) and not isinstance(query_body, six.string_types):
raise TypeError('query body must be a dict or string.')
if isinstance(query_body, dict) and not query_body.get('query'):
raise ValueError('query body must have valid query text with key "query".')
if isinstance(query_body, six.string_types):
return {'query': query_body}
elif (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.SqlQuery and
not isinstance(query_body, six.string_types)):
raise TypeError('query body must be a string.')
else:
raise SystemError('Unexpected query compatibility mode.')
return query_body | [
"def",
"__CheckAndUnifyQueryFormat",
"(",
"self",
",",
"query_body",
")",
":",
"if",
"(",
"self",
".",
"_query_compatibility_mode",
"==",
"CosmosClient",
".",
"_QueryCompatibilityMode",
".",
"Default",
"or",
"self",
".",
"_query_compatibility_mode",
"==",
"CosmosClien... | Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
:raises SystemError: If the query compatibility mode is undefined.
:param (str or dict) query_body:
:return:
The formatted query body.
:rtype:
dict or string | [
"Checks",
"and",
"unifies",
"the",
"format",
"of",
"the",
"query",
"body",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2816-L2844 | train | 224,451 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | CosmosClient._UpdateSessionIfRequired | def _UpdateSessionIfRequired(self, request_headers, response_result, response_headers):
"""
Updates session if necessary.
:param dict response_result:
:param dict response_headers:
:param dict response_headers
:return:
None, but updates the client session if necessary.
"""
'''if this request was made with consistency level as session, then update
the session'''
if response_result is None or response_headers is None:
return
is_session_consistency = False
if http_constants.HttpHeaders.ConsistencyLevel in request_headers:
if documents.ConsistencyLevel.Session == request_headers[http_constants.HttpHeaders.ConsistencyLevel]:
is_session_consistency = True
if is_session_consistency:
# update session
self.session.update_session(response_result, response_headers) | python | def _UpdateSessionIfRequired(self, request_headers, response_result, response_headers):
"""
Updates session if necessary.
:param dict response_result:
:param dict response_headers:
:param dict response_headers
:return:
None, but updates the client session if necessary.
"""
'''if this request was made with consistency level as session, then update
the session'''
if response_result is None or response_headers is None:
return
is_session_consistency = False
if http_constants.HttpHeaders.ConsistencyLevel in request_headers:
if documents.ConsistencyLevel.Session == request_headers[http_constants.HttpHeaders.ConsistencyLevel]:
is_session_consistency = True
if is_session_consistency:
# update session
self.session.update_session(response_result, response_headers) | [
"def",
"_UpdateSessionIfRequired",
"(",
"self",
",",
"request_headers",
",",
"response_result",
",",
"response_headers",
")",
":",
"'''if this request was made with consistency level as session, then update\n the session'''",
"if",
"response_result",
"is",
"None",
"or",
"r... | Updates session if necessary.
:param dict response_result:
:param dict response_headers:
:param dict response_headers
:return:
None, but updates the client session if necessary. | [
"Updates",
"session",
"if",
"necessary",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2912-L2938 | train | 224,452 |
Azure/azure-cosmos-python | azure/cosmos/base.py | GetResourceIdOrFullNameFromLink | def GetResourceIdOrFullNameFromLink(resource_link):
"""Gets resource id or full name from resource link.
:param str resource_link:
:return:
The resource id or full name from the resource link.
:rtype: str
"""
# For named based, the resource link is the full name
if IsNameBased(resource_link):
return TrimBeginningAndEndingSlashes(resource_link)
# Padding the resource link with leading and trailing slashes if not already
if resource_link[-1] != '/':
resource_link = resource_link + '/'
if resource_link[0] != '/':
resource_link = '/' + resource_link
# The path will be in the form of
# /[resourceType]/[resourceId]/ .... /[resourceType]/[resourceId]/ or
# /[resourceType]/[resourceId]/ .... /[resourceType]/
# The result of split will be in the form of
# ["", [resourceType], [resourceId] ... ,[resourceType], [resourceId], ""]
# In the first case, to extract the resourceId it will the element
# before last ( at length -2 ) and the the type will before it
# ( at length -3 )
# In the second case, to extract the resource type it will the element
# before last ( at length -2 )
path_parts = resource_link.split("/")
if len(path_parts) % 2 == 0:
# request in form
# /[resourceType]/[resourceId]/ .... /[resourceType]/[resourceId]/.
return str(path_parts[-2])
return None | python | def GetResourceIdOrFullNameFromLink(resource_link):
"""Gets resource id or full name from resource link.
:param str resource_link:
:return:
The resource id or full name from the resource link.
:rtype: str
"""
# For named based, the resource link is the full name
if IsNameBased(resource_link):
return TrimBeginningAndEndingSlashes(resource_link)
# Padding the resource link with leading and trailing slashes if not already
if resource_link[-1] != '/':
resource_link = resource_link + '/'
if resource_link[0] != '/':
resource_link = '/' + resource_link
# The path will be in the form of
# /[resourceType]/[resourceId]/ .... /[resourceType]/[resourceId]/ or
# /[resourceType]/[resourceId]/ .... /[resourceType]/
# The result of split will be in the form of
# ["", [resourceType], [resourceId] ... ,[resourceType], [resourceId], ""]
# In the first case, to extract the resourceId it will the element
# before last ( at length -2 ) and the the type will before it
# ( at length -3 )
# In the second case, to extract the resource type it will the element
# before last ( at length -2 )
path_parts = resource_link.split("/")
if len(path_parts) % 2 == 0:
# request in form
# /[resourceType]/[resourceId]/ .... /[resourceType]/[resourceId]/.
return str(path_parts[-2])
return None | [
"def",
"GetResourceIdOrFullNameFromLink",
"(",
"resource_link",
")",
":",
"# For named based, the resource link is the full name",
"if",
"IsNameBased",
"(",
"resource_link",
")",
":",
"return",
"TrimBeginningAndEndingSlashes",
"(",
"resource_link",
")",
"# Padding the resource li... | Gets resource id or full name from resource link.
:param str resource_link:
:return:
The resource id or full name from the resource link.
:rtype: str | [
"Gets",
"resource",
"id",
"or",
"full",
"name",
"from",
"resource",
"link",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L217-L252 | train | 224,453 |
Azure/azure-cosmos-python | azure/cosmos/base.py | GetAttachmentIdFromMediaId | def GetAttachmentIdFromMediaId(media_id):
"""Gets attachment id from media id.
:param str media_id:
:return:
The attachment id from the media id.
:rtype: str
"""
altchars = '+-'
if not six.PY2:
altchars = altchars.encode('utf-8')
# altchars for '+' and '/'. We keep '+' but replace '/' with '-'
buffer = base64.b64decode(str(media_id), altchars)
resoure_id_length = 20
attachment_id = ''
if len(buffer) > resoure_id_length:
# We are cutting off the storage index.
attachment_id = base64.b64encode(buffer[0:resoure_id_length], altchars)
if not six.PY2:
attachment_id = attachment_id.decode('utf-8')
else:
attachment_id = media_id
return attachment_id | python | def GetAttachmentIdFromMediaId(media_id):
"""Gets attachment id from media id.
:param str media_id:
:return:
The attachment id from the media id.
:rtype: str
"""
altchars = '+-'
if not six.PY2:
altchars = altchars.encode('utf-8')
# altchars for '+' and '/'. We keep '+' but replace '/' with '-'
buffer = base64.b64decode(str(media_id), altchars)
resoure_id_length = 20
attachment_id = ''
if len(buffer) > resoure_id_length:
# We are cutting off the storage index.
attachment_id = base64.b64encode(buffer[0:resoure_id_length], altchars)
if not six.PY2:
attachment_id = attachment_id.decode('utf-8')
else:
attachment_id = media_id
return attachment_id | [
"def",
"GetAttachmentIdFromMediaId",
"(",
"media_id",
")",
":",
"altchars",
"=",
"'+-'",
"if",
"not",
"six",
".",
"PY2",
":",
"altchars",
"=",
"altchars",
".",
"encode",
"(",
"'utf-8'",
")",
"# altchars for '+' and '/'. We keep '+' but replace '/' with '-'",
"buffer",... | Gets attachment id from media id.
:param str media_id:
:return:
The attachment id from the media id.
:rtype: str | [
"Gets",
"attachment",
"id",
"from",
"media",
"id",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L255-L279 | train | 224,454 |
Azure/azure-cosmos-python | azure/cosmos/base.py | GetPathFromLink | def GetPathFromLink(resource_link, resource_type=''):
"""Gets path from resource link with optional resource type
:param str resource_link:
:param str resource_type:
:return:
Path from resource link with resource type appended (if provided).
:rtype: str
"""
resource_link = TrimBeginningAndEndingSlashes(resource_link)
if IsNameBased(resource_link):
# Replace special characters in string using the %xx escape. For example, space(' ') would be replaced by %20
# This function is intended for quoting the path section of the URL and excludes '/' to be quoted as that's the default safe char
resource_link = urllib_quote(resource_link)
# Padding leading and trailing slashes to the path returned both for name based and resource id based links
if resource_type:
return '/' + resource_link + '/' + resource_type + '/'
else:
return '/' + resource_link + '/' | python | def GetPathFromLink(resource_link, resource_type=''):
"""Gets path from resource link with optional resource type
:param str resource_link:
:param str resource_type:
:return:
Path from resource link with resource type appended (if provided).
:rtype: str
"""
resource_link = TrimBeginningAndEndingSlashes(resource_link)
if IsNameBased(resource_link):
# Replace special characters in string using the %xx escape. For example, space(' ') would be replaced by %20
# This function is intended for quoting the path section of the URL and excludes '/' to be quoted as that's the default safe char
resource_link = urllib_quote(resource_link)
# Padding leading and trailing slashes to the path returned both for name based and resource id based links
if resource_type:
return '/' + resource_link + '/' + resource_type + '/'
else:
return '/' + resource_link + '/' | [
"def",
"GetPathFromLink",
"(",
"resource_link",
",",
"resource_type",
"=",
"''",
")",
":",
"resource_link",
"=",
"TrimBeginningAndEndingSlashes",
"(",
"resource_link",
")",
"if",
"IsNameBased",
"(",
"resource_link",
")",
":",
"# Replace special characters in string using ... | Gets path from resource link with optional resource type
:param str resource_link:
:param str resource_type:
:return:
Path from resource link with resource type appended (if provided).
:rtype: str | [
"Gets",
"path",
"from",
"resource",
"link",
"with",
"optional",
"resource",
"type"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L294-L315 | train | 224,455 |
Azure/azure-cosmos-python | azure/cosmos/base.py | IsNameBased | def IsNameBased(link):
"""Finds whether the link is name based or not
:param str link:
:return:
True if link is name-based; otherwise, False.
:rtype: boolean
"""
if not link:
return False
# trimming the leading "/"
if link.startswith('/') and len(link) > 1:
link = link[1:]
# Splitting the link(separated by "/") into parts
parts = link.split('/')
# First part should be "dbs"
if len(parts) == 0 or not parts[0] or not parts[0].lower() == 'dbs':
return False
# The second part is the database id(ResourceID or Name) and cannot be empty
if len(parts) < 2 or not parts[1]:
return False
# Either ResourceID or database name
databaseID = parts[1]
# Length of databaseID(in case of ResourceID) is always 8
if len(databaseID) != 8:
return True
return not IsValidBase64String(str(databaseID)) | python | def IsNameBased(link):
"""Finds whether the link is name based or not
:param str link:
:return:
True if link is name-based; otherwise, False.
:rtype: boolean
"""
if not link:
return False
# trimming the leading "/"
if link.startswith('/') and len(link) > 1:
link = link[1:]
# Splitting the link(separated by "/") into parts
parts = link.split('/')
# First part should be "dbs"
if len(parts) == 0 or not parts[0] or not parts[0].lower() == 'dbs':
return False
# The second part is the database id(ResourceID or Name) and cannot be empty
if len(parts) < 2 or not parts[1]:
return False
# Either ResourceID or database name
databaseID = parts[1]
# Length of databaseID(in case of ResourceID) is always 8
if len(databaseID) != 8:
return True
return not IsValidBase64String(str(databaseID)) | [
"def",
"IsNameBased",
"(",
"link",
")",
":",
"if",
"not",
"link",
":",
"return",
"False",
"# trimming the leading \"/\"",
"if",
"link",
".",
"startswith",
"(",
"'/'",
")",
"and",
"len",
"(",
"link",
")",
">",
"1",
":",
"link",
"=",
"link",
"[",
"1",
... | Finds whether the link is name based or not
:param str link:
:return:
True if link is name-based; otherwise, False.
:rtype: boolean | [
"Finds",
"whether",
"the",
"link",
"is",
"name",
"based",
"or",
"not"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L317-L351 | train | 224,456 |
Azure/azure-cosmos-python | azure/cosmos/base.py | IsDatabaseLink | def IsDatabaseLink(link):
"""Finds whether the link is a database Self Link or a database ID based link
:param str link:
Link to analyze
:return:
True or False.
:rtype: boolean
"""
if not link:
return False
# trimming the leading and trailing "/" from the input string
link = TrimBeginningAndEndingSlashes(link)
# Splitting the link(separated by "/") into parts
parts = link.split('/')
if len(parts) != 2:
return False
# First part should be "dbs"
if not parts[0] or not parts[0].lower() == 'dbs':
return False
# The second part is the database id(ResourceID or Name) and cannot be empty
if not parts[1]:
return False
return True | python | def IsDatabaseLink(link):
"""Finds whether the link is a database Self Link or a database ID based link
:param str link:
Link to analyze
:return:
True or False.
:rtype: boolean
"""
if not link:
return False
# trimming the leading and trailing "/" from the input string
link = TrimBeginningAndEndingSlashes(link)
# Splitting the link(separated by "/") into parts
parts = link.split('/')
if len(parts) != 2:
return False
# First part should be "dbs"
if not parts[0] or not parts[0].lower() == 'dbs':
return False
# The second part is the database id(ResourceID or Name) and cannot be empty
if not parts[1]:
return False
return True | [
"def",
"IsDatabaseLink",
"(",
"link",
")",
":",
"if",
"not",
"link",
":",
"return",
"False",
"# trimming the leading and trailing \"/\" from the input string",
"link",
"=",
"TrimBeginningAndEndingSlashes",
"(",
"link",
")",
"# Splitting the link(separated by \"/\") into parts "... | Finds whether the link is a database Self Link or a database ID based link
:param str link:
Link to analyze
:return:
True or False.
:rtype: boolean | [
"Finds",
"whether",
"the",
"link",
"is",
"a",
"database",
"Self",
"Link",
"or",
"a",
"database",
"ID",
"based",
"link"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L363-L393 | train | 224,457 |
Azure/azure-cosmos-python | azure/cosmos/base.py | GetItemContainerInfo | def GetItemContainerInfo(self_link, alt_content_path, id_from_response):
""" Given the self link and alt_content_path from the reponse header and result
extract the collection name and collection id
Ever response header has alt-content-path that is the
owner's path in ascii. For document create / update requests, this can be used
to get the collection name, but for collection create response, we can't use it.
So we also rely on
:param str self_link:
Self link of the resource, as obtained from response result.
:param str alt_content_path:
Owner path of the resource, as obtained from response header.
:param str resource_id:
'id' as returned from the response result. This is only used if it is deduced that the
request was to create a collection.
:return:
tuple of (collection rid, collection name)
:rtype: tuple
"""
self_link = TrimBeginningAndEndingSlashes(self_link) + '/'
index = IndexOfNth(self_link, '/', 4)
if index != -1:
collection_id = self_link[0:index]
if 'colls' in self_link:
# this is a collection request
index_second_slash = IndexOfNth(alt_content_path, '/', 2)
if index_second_slash == -1:
collection_name = alt_content_path + '/colls/' + urllib_quote(id_from_response)
return collection_id, collection_name
else:
collection_name = alt_content_path
return collection_id, collection_name
else:
raise ValueError('Response Not from Server Partition, self_link: {0}, alt_content_path: {1}, id: {2}'
.format(self_link, alt_content_path, id_from_response))
else:
raise ValueError('Unable to parse document collection link from ' + self_link) | python | def GetItemContainerInfo(self_link, alt_content_path, id_from_response):
""" Given the self link and alt_content_path from the reponse header and result
extract the collection name and collection id
Ever response header has alt-content-path that is the
owner's path in ascii. For document create / update requests, this can be used
to get the collection name, but for collection create response, we can't use it.
So we also rely on
:param str self_link:
Self link of the resource, as obtained from response result.
:param str alt_content_path:
Owner path of the resource, as obtained from response header.
:param str resource_id:
'id' as returned from the response result. This is only used if it is deduced that the
request was to create a collection.
:return:
tuple of (collection rid, collection name)
:rtype: tuple
"""
self_link = TrimBeginningAndEndingSlashes(self_link) + '/'
index = IndexOfNth(self_link, '/', 4)
if index != -1:
collection_id = self_link[0:index]
if 'colls' in self_link:
# this is a collection request
index_second_slash = IndexOfNth(alt_content_path, '/', 2)
if index_second_slash == -1:
collection_name = alt_content_path + '/colls/' + urllib_quote(id_from_response)
return collection_id, collection_name
else:
collection_name = alt_content_path
return collection_id, collection_name
else:
raise ValueError('Response Not from Server Partition, self_link: {0}, alt_content_path: {1}, id: {2}'
.format(self_link, alt_content_path, id_from_response))
else:
raise ValueError('Unable to parse document collection link from ' + self_link) | [
"def",
"GetItemContainerInfo",
"(",
"self_link",
",",
"alt_content_path",
",",
"id_from_response",
")",
":",
"self_link",
"=",
"TrimBeginningAndEndingSlashes",
"(",
"self_link",
")",
"+",
"'/'",
"index",
"=",
"IndexOfNth",
"(",
"self_link",
",",
"'/'",
",",
"4",
... | Given the self link and alt_content_path from the reponse header and result
extract the collection name and collection id
Ever response header has alt-content-path that is the
owner's path in ascii. For document create / update requests, this can be used
to get the collection name, but for collection create response, we can't use it.
So we also rely on
:param str self_link:
Self link of the resource, as obtained from response result.
:param str alt_content_path:
Owner path of the resource, as obtained from response header.
:param str resource_id:
'id' as returned from the response result. This is only used if it is deduced that the
request was to create a collection.
:return:
tuple of (collection rid, collection name)
:rtype: tuple | [
"Given",
"the",
"self",
"link",
"and",
"alt_content_path",
"from",
"the",
"reponse",
"header",
"and",
"result",
"extract",
"the",
"collection",
"name",
"and",
"collection",
"id"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L435-L477 | train | 224,458 |
Azure/azure-cosmos-python | azure/cosmos/base.py | GetItemContainerLink | def GetItemContainerLink(link):
"""Gets the document collection link
:param str link:
Resource link
:return:
Document collection link.
:rtype: str
"""
link = TrimBeginningAndEndingSlashes(link) + '/'
index = IndexOfNth(link, '/', 4)
if index != -1:
return link[0:index]
else:
raise ValueError('Unable to parse document collection link from ' + link) | python | def GetItemContainerLink(link):
"""Gets the document collection link
:param str link:
Resource link
:return:
Document collection link.
:rtype: str
"""
link = TrimBeginningAndEndingSlashes(link) + '/'
index = IndexOfNth(link, '/', 4)
if index != -1:
return link[0:index]
else:
raise ValueError('Unable to parse document collection link from ' + link) | [
"def",
"GetItemContainerLink",
"(",
"link",
")",
":",
"link",
"=",
"TrimBeginningAndEndingSlashes",
"(",
"link",
")",
"+",
"'/'",
"index",
"=",
"IndexOfNth",
"(",
"link",
",",
"'/'",
",",
"4",
")",
"if",
"index",
"!=",
"-",
"1",
":",
"return",
"link",
... | Gets the document collection link
:param str link:
Resource link
:return:
Document collection link.
:rtype: str | [
"Gets",
"the",
"document",
"collection",
"link"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L479-L497 | train | 224,459 |
Azure/azure-cosmos-python | azure/cosmos/base.py | IndexOfNth | def IndexOfNth(s, value, n):
"""Gets the index of Nth occurance of a given character in a string
:param str s:
Input string
:param char value:
Input char to be searched.
:param int n:
Nth occurrence of char to be searched.
:return:
Index of the Nth occurrence in the string.
:rtype: int
"""
remaining = n
for i in xrange(0, len(s)):
if s[i] == value:
remaining -= 1
if remaining == 0:
return i
return -1 | python | def IndexOfNth(s, value, n):
"""Gets the index of Nth occurance of a given character in a string
:param str s:
Input string
:param char value:
Input char to be searched.
:param int n:
Nth occurrence of char to be searched.
:return:
Index of the Nth occurrence in the string.
:rtype: int
"""
remaining = n
for i in xrange(0, len(s)):
if s[i] == value:
remaining -= 1
if remaining == 0:
return i
return -1 | [
"def",
"IndexOfNth",
"(",
"s",
",",
"value",
",",
"n",
")",
":",
"remaining",
"=",
"n",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"s",
")",
")",
":",
"if",
"s",
"[",
"i",
"]",
"==",
"value",
":",
"remaining",
"-=",
"1",
"if",
"... | Gets the index of Nth occurance of a given character in a string
:param str s:
Input string
:param char value:
Input char to be searched.
:param int n:
Nth occurrence of char to be searched.
:return:
Index of the Nth occurrence in the string.
:rtype: int | [
"Gets",
"the",
"index",
"of",
"Nth",
"occurance",
"of",
"a",
"given",
"character",
"in",
"a",
"string"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L499-L520 | train | 224,460 |
Azure/azure-cosmos-python | azure/cosmos/base.py | TrimBeginningAndEndingSlashes | def TrimBeginningAndEndingSlashes(path):
"""Trims beginning and ending slashes
:param str path:
:return:
Path with beginning and ending slashes trimmed.
:rtype: str
"""
if path.startswith('/'):
# Returns substring starting from index 1 to end of the string
path = path[1:]
if path.endswith('/'):
# Returns substring starting from beginning to last but one char in the string
path = path[:-1]
return path | python | def TrimBeginningAndEndingSlashes(path):
"""Trims beginning and ending slashes
:param str path:
:return:
Path with beginning and ending slashes trimmed.
:rtype: str
"""
if path.startswith('/'):
# Returns substring starting from index 1 to end of the string
path = path[1:]
if path.endswith('/'):
# Returns substring starting from beginning to last but one char in the string
path = path[:-1]
return path | [
"def",
"TrimBeginningAndEndingSlashes",
"(",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# Returns substring starting from index 1 to end of the string",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"if",
"path",
".",
"endswith",
"(",
"... | Trims beginning and ending slashes
:param str path:
:return:
Path with beginning and ending slashes trimmed.
:rtype: str | [
"Trims",
"beginning",
"and",
"ending",
"slashes"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/base.py#L546-L563 | train | 224,461 |
Azure/azure-cosmos-python | azure/cosmos/synchronized_request.py | _RequestBodyFromData | def _RequestBodyFromData(data):
"""Gets request body from data.
When `data` is dict and list into unicode string; otherwise return `data`
without making any change.
:param (str, unicode, file-like stream object, dict, list or None) data:
:rtype:
str, unicode, file-like stream object, or None
"""
if isinstance(data, six.string_types) or _IsReadableStream(data):
return data
elif isinstance(data, (dict, list, tuple)):
json_dumped = json.dumps(data, separators=(',',':'))
if six.PY2:
return json_dumped.decode('utf-8')
else:
return json_dumped
return None | python | def _RequestBodyFromData(data):
"""Gets request body from data.
When `data` is dict and list into unicode string; otherwise return `data`
without making any change.
:param (str, unicode, file-like stream object, dict, list or None) data:
:rtype:
str, unicode, file-like stream object, or None
"""
if isinstance(data, six.string_types) or _IsReadableStream(data):
return data
elif isinstance(data, (dict, list, tuple)):
json_dumped = json.dumps(data, separators=(',',':'))
if six.PY2:
return json_dumped.decode('utf-8')
else:
return json_dumped
return None | [
"def",
"_RequestBodyFromData",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
"or",
"_IsReadableStream",
"(",
"data",
")",
":",
"return",
"data",
"elif",
"isinstance",
"(",
"data",
",",
"(",
"dict",
",",
"li... | Gets request body from data.
When `data` is dict and list into unicode string; otherwise return `data`
without making any change.
:param (str, unicode, file-like stream object, dict, list or None) data:
:rtype:
str, unicode, file-like stream object, or None | [
"Gets",
"request",
"body",
"from",
"data",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/synchronized_request.py#L47-L69 | train | 224,462 |
Azure/azure-cosmos-python | azure/cosmos/synchronized_request.py | _Request | def _Request(global_endpoint_manager, request, connection_policy, requests_session, path, request_options, request_body):
"""Makes one http request using the requests module.
:param _GlobalEndpointManager global_endpoint_manager:
:param dict request:
contains the resourceType, operationType, endpointOverride,
useWriteEndpoint, useAlternateWriteEndpoint information
:param documents.ConnectionPolicy connection_policy:
:param requests.Session requests_session:
Session object in requests module
:param str resource_url:
The url for the resource
:param dict request_options:
:param str request_body:
Unicode or None
:return:
tuple of (result, headers)
:rtype:
tuple of (dict, dict)
"""
is_media = request_options['path'].find('media') > -1
is_media_stream = is_media and connection_policy.MediaReadMode == documents.MediaReadMode.Streamed
connection_timeout = (connection_policy.MediaRequestTimeout
if is_media
else connection_policy.RequestTimeout)
# Every request tries to perform a refresh
global_endpoint_manager.refresh_endpoint_list(None)
if (request.endpoint_override):
base_url = request.endpoint_override
else:
base_url = global_endpoint_manager.resolve_service_endpoint(request)
if path:
resource_url = base_url + path
else:
resource_url = base_url
parse_result = urlparse(resource_url)
# The requests library now expects header values to be strings only starting 2.11,
# and will raise an error on validation if they are not, so casting all header values to strings.
request_options['headers'] = { header: str(value) for header, value in request_options['headers'].items() }
# We are disabling the SSL verification for local emulator(localhost/127.0.0.1) or if the user
# has explicitly specified to disable SSL verification.
is_ssl_enabled = (parse_result.hostname != 'localhost' and parse_result.hostname != '127.0.0.1' and not connection_policy.DisableSSLVerification)
if connection_policy.SSLConfiguration:
ca_certs = connection_policy.SSLConfiguration.SSLCaCerts
cert_files = (connection_policy.SSLConfiguration.SSLCertFile, connection_policy.SSLConfiguration.SSLKeyFile)
response = requests_session.request(request_options['method'],
resource_url,
data = request_body,
headers = request_options['headers'],
timeout = connection_timeout / 1000.0,
stream = is_media_stream,
verify = ca_certs,
cert = cert_files)
else:
response = requests_session.request(request_options['method'],
resource_url,
data = request_body,
headers = request_options['headers'],
timeout = connection_timeout / 1000.0,
stream = is_media_stream,
# If SSL is disabled, verify = false
verify = is_ssl_enabled)
headers = dict(response.headers)
# In case of media stream response, return the response to the user and the user
# will need to handle reading the response.
if is_media_stream:
return (response.raw, headers)
data = response.content
if not six.PY2:
# python 3 compatible: convert data from byte to unicode string
data = data.decode('utf-8')
if response.status_code >= 400:
raise errors.HTTPFailure(response.status_code, data, headers)
result = None
if is_media:
result = data
else:
if len(data) > 0:
try:
result = json.loads(data)
except:
raise errors.JSONParseFailure(data)
return (result, headers) | python | def _Request(global_endpoint_manager, request, connection_policy, requests_session, path, request_options, request_body):
"""Makes one http request using the requests module.
:param _GlobalEndpointManager global_endpoint_manager:
:param dict request:
contains the resourceType, operationType, endpointOverride,
useWriteEndpoint, useAlternateWriteEndpoint information
:param documents.ConnectionPolicy connection_policy:
:param requests.Session requests_session:
Session object in requests module
:param str resource_url:
The url for the resource
:param dict request_options:
:param str request_body:
Unicode or None
:return:
tuple of (result, headers)
:rtype:
tuple of (dict, dict)
"""
is_media = request_options['path'].find('media') > -1
is_media_stream = is_media and connection_policy.MediaReadMode == documents.MediaReadMode.Streamed
connection_timeout = (connection_policy.MediaRequestTimeout
if is_media
else connection_policy.RequestTimeout)
# Every request tries to perform a refresh
global_endpoint_manager.refresh_endpoint_list(None)
if (request.endpoint_override):
base_url = request.endpoint_override
else:
base_url = global_endpoint_manager.resolve_service_endpoint(request)
if path:
resource_url = base_url + path
else:
resource_url = base_url
parse_result = urlparse(resource_url)
# The requests library now expects header values to be strings only starting 2.11,
# and will raise an error on validation if they are not, so casting all header values to strings.
request_options['headers'] = { header: str(value) for header, value in request_options['headers'].items() }
# We are disabling the SSL verification for local emulator(localhost/127.0.0.1) or if the user
# has explicitly specified to disable SSL verification.
is_ssl_enabled = (parse_result.hostname != 'localhost' and parse_result.hostname != '127.0.0.1' and not connection_policy.DisableSSLVerification)
if connection_policy.SSLConfiguration:
ca_certs = connection_policy.SSLConfiguration.SSLCaCerts
cert_files = (connection_policy.SSLConfiguration.SSLCertFile, connection_policy.SSLConfiguration.SSLKeyFile)
response = requests_session.request(request_options['method'],
resource_url,
data = request_body,
headers = request_options['headers'],
timeout = connection_timeout / 1000.0,
stream = is_media_stream,
verify = ca_certs,
cert = cert_files)
else:
response = requests_session.request(request_options['method'],
resource_url,
data = request_body,
headers = request_options['headers'],
timeout = connection_timeout / 1000.0,
stream = is_media_stream,
# If SSL is disabled, verify = false
verify = is_ssl_enabled)
headers = dict(response.headers)
# In case of media stream response, return the response to the user and the user
# will need to handle reading the response.
if is_media_stream:
return (response.raw, headers)
data = response.content
if not six.PY2:
# python 3 compatible: convert data from byte to unicode string
data = data.decode('utf-8')
if response.status_code >= 400:
raise errors.HTTPFailure(response.status_code, data, headers)
result = None
if is_media:
result = data
else:
if len(data) > 0:
try:
result = json.loads(data)
except:
raise errors.JSONParseFailure(data)
return (result, headers) | [
"def",
"_Request",
"(",
"global_endpoint_manager",
",",
"request",
",",
"connection_policy",
",",
"requests_session",
",",
"path",
",",
"request_options",
",",
"request_body",
")",
":",
"is_media",
"=",
"request_options",
"[",
"'path'",
"]",
".",
"find",
"(",
"'... | Makes one http request using the requests module.
:param _GlobalEndpointManager global_endpoint_manager:
:param dict request:
contains the resourceType, operationType, endpointOverride,
useWriteEndpoint, useAlternateWriteEndpoint information
:param documents.ConnectionPolicy connection_policy:
:param requests.Session requests_session:
Session object in requests module
:param str resource_url:
The url for the resource
:param dict request_options:
:param str request_body:
Unicode or None
:return:
tuple of (result, headers)
:rtype:
tuple of (dict, dict) | [
"Makes",
"one",
"http",
"request",
"using",
"the",
"requests",
"module",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/synchronized_request.py#L72-L171 | train | 224,463 |
Azure/azure-cosmos-python | azure/cosmos/synchronized_request.py | SynchronizedRequest | def SynchronizedRequest(client,
request,
global_endpoint_manager,
connection_policy,
requests_session,
method,
path,
request_data,
query_params,
headers):
"""Performs one synchronized http request according to the parameters.
:param object client:
Document client instance
:param dict request:
:param _GlobalEndpointManager global_endpoint_manager:
:param documents.ConnectionPolicy connection_policy:
:param requests.Session requests_session:
Session object in requests module
:param str method:
:param str path:
:param (str, unicode, file-like stream object, dict, list or None) request_data:
:param dict query_params:
:param dict headers:
:return:
tuple of (result, headers)
:rtype:
tuple of (dict dict)
"""
request_body = None
if request_data:
request_body = _RequestBodyFromData(request_data)
if not request_body:
raise errors.UnexpectedDataType(
'parameter data must be a JSON object, string or' +
' readable stream.')
request_options = {}
request_options['path'] = path
request_options['method'] = method
if query_params:
request_options['path'] += '?' + urlencode(query_params)
request_options['headers'] = headers
if request_body and (type(request_body) is str or
type(request_body) is six.text_type):
request_options['headers'][http_constants.HttpHeaders.ContentLength] = (
len(request_body))
elif request_body is None:
request_options['headers'][http_constants.HttpHeaders.ContentLength] = 0
# Pass _Request function with it's parameters to retry_utility's Execute method that wraps the call with retries
return retry_utility._Execute(client, global_endpoint_manager, _Request, request, connection_policy, requests_session, path, request_options, request_body) | python | def SynchronizedRequest(client,
request,
global_endpoint_manager,
connection_policy,
requests_session,
method,
path,
request_data,
query_params,
headers):
"""Performs one synchronized http request according to the parameters.
:param object client:
Document client instance
:param dict request:
:param _GlobalEndpointManager global_endpoint_manager:
:param documents.ConnectionPolicy connection_policy:
:param requests.Session requests_session:
Session object in requests module
:param str method:
:param str path:
:param (str, unicode, file-like stream object, dict, list or None) request_data:
:param dict query_params:
:param dict headers:
:return:
tuple of (result, headers)
:rtype:
tuple of (dict dict)
"""
request_body = None
if request_data:
request_body = _RequestBodyFromData(request_data)
if not request_body:
raise errors.UnexpectedDataType(
'parameter data must be a JSON object, string or' +
' readable stream.')
request_options = {}
request_options['path'] = path
request_options['method'] = method
if query_params:
request_options['path'] += '?' + urlencode(query_params)
request_options['headers'] = headers
if request_body and (type(request_body) is str or
type(request_body) is six.text_type):
request_options['headers'][http_constants.HttpHeaders.ContentLength] = (
len(request_body))
elif request_body is None:
request_options['headers'][http_constants.HttpHeaders.ContentLength] = 0
# Pass _Request function with it's parameters to retry_utility's Execute method that wraps the call with retries
return retry_utility._Execute(client, global_endpoint_manager, _Request, request, connection_policy, requests_session, path, request_options, request_body) | [
"def",
"SynchronizedRequest",
"(",
"client",
",",
"request",
",",
"global_endpoint_manager",
",",
"connection_policy",
",",
"requests_session",
",",
"method",
",",
"path",
",",
"request_data",
",",
"query_params",
",",
"headers",
")",
":",
"request_body",
"=",
"No... | Performs one synchronized http request according to the parameters.
:param object client:
Document client instance
:param dict request:
:param _GlobalEndpointManager global_endpoint_manager:
:param documents.ConnectionPolicy connection_policy:
:param requests.Session requests_session:
Session object in requests module
:param str method:
:param str path:
:param (str, unicode, file-like stream object, dict, list or None) request_data:
:param dict query_params:
:param dict headers:
:return:
tuple of (result, headers)
:rtype:
tuple of (dict dict) | [
"Performs",
"one",
"synchronized",
"http",
"request",
"according",
"to",
"the",
"parameters",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/synchronized_request.py#L173-L227 | train | 224,464 |
Azure/azure-cosmos-python | azure/cosmos/routing/collection_routing_map.py | _CollectionRoutingMap.get_range_by_effective_partition_key | def get_range_by_effective_partition_key(self, effective_partition_key_value):
"""Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict
"""
if _CollectionRoutingMap.MinimumInclusiveEffectivePartitionKey == effective_partition_key_value:
return self._orderedPartitionKeyRanges[0]
if _CollectionRoutingMap.MaximumExclusiveEffectivePartitionKey == effective_partition_key_value:
return None
sortedLow = [(r.min, not r.isMinInclusive) for r in self._orderedRanges]
index = bisect.bisect_right(sortedLow, (effective_partition_key_value, True))
if (index > 0):
index = index -1
return self._orderedPartitionKeyRanges[index] | python | def get_range_by_effective_partition_key(self, effective_partition_key_value):
"""Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict
"""
if _CollectionRoutingMap.MinimumInclusiveEffectivePartitionKey == effective_partition_key_value:
return self._orderedPartitionKeyRanges[0]
if _CollectionRoutingMap.MaximumExclusiveEffectivePartitionKey == effective_partition_key_value:
return None
sortedLow = [(r.min, not r.isMinInclusive) for r in self._orderedRanges]
index = bisect.bisect_right(sortedLow, (effective_partition_key_value, True))
if (index > 0):
index = index -1
return self._orderedPartitionKeyRanges[index] | [
"def",
"get_range_by_effective_partition_key",
"(",
"self",
",",
"effective_partition_key_value",
")",
":",
"if",
"_CollectionRoutingMap",
".",
"MinimumInclusiveEffectivePartitionKey",
"==",
"effective_partition_key_value",
":",
"return",
"self",
".",
"_orderedPartitionKeyRanges"... | Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict | [
"Gets",
"the",
"range",
"containing",
"the",
"given",
"partition",
"key"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/routing/collection_routing_map.py#L74-L94 | train | 224,465 |
Azure/azure-cosmos-python | azure/cosmos/routing/collection_routing_map.py | _CollectionRoutingMap.get_range_by_partition_key_range_id | def get_range_by_partition_key_range_id(self, partition_key_range_id):
"""Gets the partition key range given the partition key range id
:param str partition_key_range_id:
The partition key range id.
:return:
The partition key range.
:rtype: dict
"""
t = self._rangeById.get(partition_key_range_id)
if t is None:
return None
return t[0] | python | def get_range_by_partition_key_range_id(self, partition_key_range_id):
"""Gets the partition key range given the partition key range id
:param str partition_key_range_id:
The partition key range id.
:return:
The partition key range.
:rtype: dict
"""
t = self._rangeById.get(partition_key_range_id)
if t is None:
return None
return t[0] | [
"def",
"get_range_by_partition_key_range_id",
"(",
"self",
",",
"partition_key_range_id",
")",
":",
"t",
"=",
"self",
".",
"_rangeById",
".",
"get",
"(",
"partition_key_range_id",
")",
"if",
"t",
"is",
"None",
":",
"return",
"None",
"return",
"t",
"[",
"0",
... | Gets the partition key range given the partition key range id
:param str partition_key_range_id:
The partition key range id.
:return:
The partition key range.
:rtype: dict | [
"Gets",
"the",
"partition",
"key",
"range",
"given",
"the",
"partition",
"key",
"range",
"id"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/routing/collection_routing_map.py#L96-L109 | train | 224,466 |
Azure/azure-cosmos-python | azure/cosmos/routing/collection_routing_map.py | _CollectionRoutingMap.get_overlapping_ranges | def get_overlapping_ranges(self, provided_partition_key_ranges):
"""Gets the partition key ranges overlapping the provided ranges
:param list provided_partition_key_ranges:
List of partition key ranges.
:return:
List of partition key ranges, where each is a dict.
:rtype: list
"""
if isinstance(provided_partition_key_ranges, routing_range._Range):
return self.get_overlapping_ranges([provided_partition_key_ranges])
minToPartitionRange = {}
sortedLow = [(r.min, not r.isMinInclusive) for r in self._orderedRanges]
sortedHigh = [(r.max, r.isMaxInclusive) for r in self._orderedRanges]
for providedRange in provided_partition_key_ranges:
minIndex = bisect.bisect_right(sortedLow, (providedRange.min, not providedRange.isMinInclusive))
if minIndex > 0: minIndex = minIndex - 1
maxIndex = bisect.bisect_left(sortedHigh, (providedRange.max, providedRange.isMaxInclusive))
if maxIndex >= len(sortedHigh):
maxIndex = maxIndex - 1
for i in xrange(minIndex, maxIndex + 1):
if routing_range._Range.overlaps(self._orderedRanges[i], providedRange):
minToPartitionRange[self._orderedPartitionKeyRanges[i][_PartitionKeyRange.MinInclusive]] = self._orderedPartitionKeyRanges[i]
overlapping_partition_key_ranges = list(minToPartitionRange.values())
def getKey(r):
return r[_PartitionKeyRange.MinInclusive]
overlapping_partition_key_ranges.sort(key = getKey)
return overlapping_partition_key_ranges | python | def get_overlapping_ranges(self, provided_partition_key_ranges):
"""Gets the partition key ranges overlapping the provided ranges
:param list provided_partition_key_ranges:
List of partition key ranges.
:return:
List of partition key ranges, where each is a dict.
:rtype: list
"""
if isinstance(provided_partition_key_ranges, routing_range._Range):
return self.get_overlapping_ranges([provided_partition_key_ranges])
minToPartitionRange = {}
sortedLow = [(r.min, not r.isMinInclusive) for r in self._orderedRanges]
sortedHigh = [(r.max, r.isMaxInclusive) for r in self._orderedRanges]
for providedRange in provided_partition_key_ranges:
minIndex = bisect.bisect_right(sortedLow, (providedRange.min, not providedRange.isMinInclusive))
if minIndex > 0: minIndex = minIndex - 1
maxIndex = bisect.bisect_left(sortedHigh, (providedRange.max, providedRange.isMaxInclusive))
if maxIndex >= len(sortedHigh):
maxIndex = maxIndex - 1
for i in xrange(minIndex, maxIndex + 1):
if routing_range._Range.overlaps(self._orderedRanges[i], providedRange):
minToPartitionRange[self._orderedPartitionKeyRanges[i][_PartitionKeyRange.MinInclusive]] = self._orderedPartitionKeyRanges[i]
overlapping_partition_key_ranges = list(minToPartitionRange.values())
def getKey(r):
return r[_PartitionKeyRange.MinInclusive]
overlapping_partition_key_ranges.sort(key = getKey)
return overlapping_partition_key_ranges | [
"def",
"get_overlapping_ranges",
"(",
"self",
",",
"provided_partition_key_ranges",
")",
":",
"if",
"isinstance",
"(",
"provided_partition_key_ranges",
",",
"routing_range",
".",
"_Range",
")",
":",
"return",
"self",
".",
"get_overlapping_ranges",
"(",
"[",
"provided_... | Gets the partition key ranges overlapping the provided ranges
:param list provided_partition_key_ranges:
List of partition key ranges.
:return:
List of partition key ranges, where each is a dict.
:rtype: list | [
"Gets",
"the",
"partition",
"key",
"ranges",
"overlapping",
"the",
"provided",
"ranges"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/routing/collection_routing_map.py#L111-L147 | train | 224,467 |
Azure/azure-cosmos-python | azure/cosmos/auth.py | GetAuthorizationHeader | def GetAuthorizationHeader(cosmos_client,
verb,
path,
resource_id_or_fullname,
is_name_based,
resource_type,
headers):
"""Gets the authorization header.
:param cosmos_client.CosmosClient cosmos_client:
:param str verb:
:param str path:
:param str resource_id_or_fullname:
:param str resource_type:
:param dict headers:
:return:
The authorization headers.
:rtype: dict
"""
# In the AuthorizationToken generation logic, lower casing of ResourceID is required as rest of the fields are lower cased
# Lower casing should not be done for named based "ID", which should be used as is
if resource_id_or_fullname is not None and not is_name_based:
resource_id_or_fullname = resource_id_or_fullname.lower()
if cosmos_client.master_key:
return __GetAuthorizationTokenUsingMasterKey(verb,
resource_id_or_fullname,
resource_type,
headers,
cosmos_client.master_key)
elif cosmos_client.resource_tokens:
return __GetAuthorizationTokenUsingResourceTokens(
cosmos_client.resource_tokens, path, resource_id_or_fullname) | python | def GetAuthorizationHeader(cosmos_client,
verb,
path,
resource_id_or_fullname,
is_name_based,
resource_type,
headers):
"""Gets the authorization header.
:param cosmos_client.CosmosClient cosmos_client:
:param str verb:
:param str path:
:param str resource_id_or_fullname:
:param str resource_type:
:param dict headers:
:return:
The authorization headers.
:rtype: dict
"""
# In the AuthorizationToken generation logic, lower casing of ResourceID is required as rest of the fields are lower cased
# Lower casing should not be done for named based "ID", which should be used as is
if resource_id_or_fullname is not None and not is_name_based:
resource_id_or_fullname = resource_id_or_fullname.lower()
if cosmos_client.master_key:
return __GetAuthorizationTokenUsingMasterKey(verb,
resource_id_or_fullname,
resource_type,
headers,
cosmos_client.master_key)
elif cosmos_client.resource_tokens:
return __GetAuthorizationTokenUsingResourceTokens(
cosmos_client.resource_tokens, path, resource_id_or_fullname) | [
"def",
"GetAuthorizationHeader",
"(",
"cosmos_client",
",",
"verb",
",",
"path",
",",
"resource_id_or_fullname",
",",
"is_name_based",
",",
"resource_type",
",",
"headers",
")",
":",
"# In the AuthorizationToken generation logic, lower casing of ResourceID is required as rest of ... | Gets the authorization header.
:param cosmos_client.CosmosClient cosmos_client:
:param str verb:
:param str path:
:param str resource_id_or_fullname:
:param str resource_type:
:param dict headers:
:return:
The authorization headers.
:rtype: dict | [
"Gets",
"the",
"authorization",
"header",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/auth.py#L31-L64 | train | 224,468 |
Azure/azure-cosmos-python | azure/cosmos/auth.py | __GetAuthorizationTokenUsingMasterKey | def __GetAuthorizationTokenUsingMasterKey(verb,
resource_id_or_fullname,
resource_type,
headers,
master_key):
"""Gets the authorization token using `master_key.
:param str verb:
:param str resource_id_or_fullname:
:param str resource_type:
:param dict headers:
:param str master_key:
:return:
The authorization token.
:rtype: dict
"""
# decodes the master key which is encoded in base64
key = base64.b64decode(master_key)
# Skipping lower casing of resource_id_or_fullname since it may now contain "ID" of the resource as part of the fullname
text = '{verb}\n{resource_type}\n{resource_id_or_fullname}\n{x_date}\n{http_date}\n'.format(
verb=(verb.lower() or ''),
resource_type=(resource_type.lower() or ''),
resource_id_or_fullname=(resource_id_or_fullname or ''),
x_date=headers.get(http_constants.HttpHeaders.XDate, '').lower(),
http_date=headers.get(http_constants.HttpHeaders.HttpDate, '').lower())
if six.PY2:
body = text.decode('utf-8')
digest = hmac.new(key, body, sha256).digest()
signature = digest.encode('base64')
else:
# python 3 support
body = text.encode('utf-8')
digest = hmac.new(key, body, sha256).digest()
signature = base64.encodebytes(digest).decode('utf-8')
master_token = 'master'
token_version = '1.0'
return 'type={type}&ver={ver}&sig={sig}'.format(type=master_token,
ver=token_version,
sig=signature[:-1]) | python | def __GetAuthorizationTokenUsingMasterKey(verb,
resource_id_or_fullname,
resource_type,
headers,
master_key):
"""Gets the authorization token using `master_key.
:param str verb:
:param str resource_id_or_fullname:
:param str resource_type:
:param dict headers:
:param str master_key:
:return:
The authorization token.
:rtype: dict
"""
# decodes the master key which is encoded in base64
key = base64.b64decode(master_key)
# Skipping lower casing of resource_id_or_fullname since it may now contain "ID" of the resource as part of the fullname
text = '{verb}\n{resource_type}\n{resource_id_or_fullname}\n{x_date}\n{http_date}\n'.format(
verb=(verb.lower() or ''),
resource_type=(resource_type.lower() or ''),
resource_id_or_fullname=(resource_id_or_fullname or ''),
x_date=headers.get(http_constants.HttpHeaders.XDate, '').lower(),
http_date=headers.get(http_constants.HttpHeaders.HttpDate, '').lower())
if six.PY2:
body = text.decode('utf-8')
digest = hmac.new(key, body, sha256).digest()
signature = digest.encode('base64')
else:
# python 3 support
body = text.encode('utf-8')
digest = hmac.new(key, body, sha256).digest()
signature = base64.encodebytes(digest).decode('utf-8')
master_token = 'master'
token_version = '1.0'
return 'type={type}&ver={ver}&sig={sig}'.format(type=master_token,
ver=token_version,
sig=signature[:-1]) | [
"def",
"__GetAuthorizationTokenUsingMasterKey",
"(",
"verb",
",",
"resource_id_or_fullname",
",",
"resource_type",
",",
"headers",
",",
"master_key",
")",
":",
"# decodes the master key which is encoded in base64 ",
"key",
"=",
"base64",
".",
"b64decode",
"(",
"master_ke... | Gets the authorization token using `master_key.
:param str verb:
:param str resource_id_or_fullname:
:param str resource_type:
:param dict headers:
:param str master_key:
:return:
The authorization token.
:rtype: dict | [
"Gets",
"the",
"authorization",
"token",
"using",
"master_key",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/auth.py#L69-L114 | train | 224,469 |
Azure/azure-cosmos-python | azure/cosmos/auth.py | __GetAuthorizationTokenUsingResourceTokens | def __GetAuthorizationTokenUsingResourceTokens(resource_tokens,
path,
resource_id_or_fullname):
"""Get the authorization token using `resource_tokens`.
:param dict resource_tokens:
:param str path:
:param str resource_id_or_fullname:
:return:
The authorization token.
:rtype: dict
"""
if resource_tokens and len(resource_tokens) > 0:
# For database account access(through GetDatabaseAccount API), path and resource_id_or_fullname are '',
# so in this case we return the first token to be used for creating the auth header as the service will accept any token in this case
if not path and not resource_id_or_fullname:
return next(six.itervalues(resource_tokens))
if resource_tokens.get(resource_id_or_fullname):
return resource_tokens[resource_id_or_fullname]
else:
path_parts = []
if path:
path_parts = path.split('/')
resource_types = ['dbs', 'colls', 'docs', 'sprocs', 'udfs', 'triggers',
'users', 'permissions', 'attachments', 'media',
'conflicts', 'offers']
# Get the last resource id or resource name from the path and get it's token from resource_tokens
for one_part in reversed(path_parts):
if not one_part in resource_types and one_part in resource_tokens:
return resource_tokens[one_part]
return None | python | def __GetAuthorizationTokenUsingResourceTokens(resource_tokens,
path,
resource_id_or_fullname):
"""Get the authorization token using `resource_tokens`.
:param dict resource_tokens:
:param str path:
:param str resource_id_or_fullname:
:return:
The authorization token.
:rtype: dict
"""
if resource_tokens and len(resource_tokens) > 0:
# For database account access(through GetDatabaseAccount API), path and resource_id_or_fullname are '',
# so in this case we return the first token to be used for creating the auth header as the service will accept any token in this case
if not path and not resource_id_or_fullname:
return next(six.itervalues(resource_tokens))
if resource_tokens.get(resource_id_or_fullname):
return resource_tokens[resource_id_or_fullname]
else:
path_parts = []
if path:
path_parts = path.split('/')
resource_types = ['dbs', 'colls', 'docs', 'sprocs', 'udfs', 'triggers',
'users', 'permissions', 'attachments', 'media',
'conflicts', 'offers']
# Get the last resource id or resource name from the path and get it's token from resource_tokens
for one_part in reversed(path_parts):
if not one_part in resource_types and one_part in resource_tokens:
return resource_tokens[one_part]
return None | [
"def",
"__GetAuthorizationTokenUsingResourceTokens",
"(",
"resource_tokens",
",",
"path",
",",
"resource_id_or_fullname",
")",
":",
"if",
"resource_tokens",
"and",
"len",
"(",
"resource_tokens",
")",
">",
"0",
":",
"# For database account access(through GetDatabaseAccount API... | Get the authorization token using `resource_tokens`.
:param dict resource_tokens:
:param str path:
:param str resource_id_or_fullname:
:return:
The authorization token.
:rtype: dict | [
"Get",
"the",
"authorization",
"token",
"using",
"resource_tokens",
"."
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/auth.py#L116-L149 | train | 224,470 |
Azure/azure-cosmos-python | azure/cosmos/session.py | SessionContainer.parse_session_token | def parse_session_token(response_headers):
""" Extracts session token from response headers and parses
:param dict response_headers:
:return:
A dictionary of partition id to session lsn
for given collection
:rtype: dict
"""
# extract session token from response header
session_token = ''
if http_constants.HttpHeaders.SessionToken in response_headers:
session_token = response_headers[http_constants.HttpHeaders.SessionToken]
id_to_sessionlsn = {}
if session_token is not '':
''' extract id, lsn from the token. For p-collection,
the token will be a concatenation of pairs for each collection'''
token_pairs = session_token.split(',')
for token_pair in token_pairs:
tokens = token_pair.split(':')
if (len(tokens) == 2):
id = tokens[0]
sessionToken = VectorSessionToken.create(tokens[1])
if sessionToken is None:
raise HTTPFailure(http_constants.StatusCodes.INTERNAL_SERVER_ERROR, "Could not parse the received session token: %s" % tokens[1])
id_to_sessionlsn[id] = sessionToken
return id_to_sessionlsn | python | def parse_session_token(response_headers):
""" Extracts session token from response headers and parses
:param dict response_headers:
:return:
A dictionary of partition id to session lsn
for given collection
:rtype: dict
"""
# extract session token from response header
session_token = ''
if http_constants.HttpHeaders.SessionToken in response_headers:
session_token = response_headers[http_constants.HttpHeaders.SessionToken]
id_to_sessionlsn = {}
if session_token is not '':
''' extract id, lsn from the token. For p-collection,
the token will be a concatenation of pairs for each collection'''
token_pairs = session_token.split(',')
for token_pair in token_pairs:
tokens = token_pair.split(':')
if (len(tokens) == 2):
id = tokens[0]
sessionToken = VectorSessionToken.create(tokens[1])
if sessionToken is None:
raise HTTPFailure(http_constants.StatusCodes.INTERNAL_SERVER_ERROR, "Could not parse the received session token: %s" % tokens[1])
id_to_sessionlsn[id] = sessionToken
return id_to_sessionlsn | [
"def",
"parse_session_token",
"(",
"response_headers",
")",
":",
"# extract session token from response header",
"session_token",
"=",
"''",
"if",
"http_constants",
".",
"HttpHeaders",
".",
"SessionToken",
"in",
"response_headers",
":",
"session_token",
"=",
"response_heade... | Extracts session token from response headers and parses
:param dict response_headers:
:return:
A dictionary of partition id to session lsn
for given collection
:rtype: dict | [
"Extracts",
"session",
"token",
"from",
"response",
"headers",
"and",
"parses"
] | dd01b3c5d308c6da83cfcaa0ab7083351a476353 | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/session.py#L169-L198 | train | 224,471 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | VectorMixin.generate_vector_color_map | def generate_vector_color_map(self):
"""Generate color stops array for use with match expression in mapbox template"""
vector_stops = []
# if join data specified as filename or URL, parse JSON to list of Python dicts
if type(self.data) == str:
self.data = geojson_to_dict_list(self.data)
# loop through features in self.data to create join-data map
for row in self.data:
# map color to JSON feature using color_property
color = color_map(row[self.color_property], self.color_stops, self.color_default)
# link to vector feature using data_join_property (from JSON object)
vector_stops.append([row[self.data_join_property], color])
return vector_stops | python | def generate_vector_color_map(self):
"""Generate color stops array for use with match expression in mapbox template"""
vector_stops = []
# if join data specified as filename or URL, parse JSON to list of Python dicts
if type(self.data) == str:
self.data = geojson_to_dict_list(self.data)
# loop through features in self.data to create join-data map
for row in self.data:
# map color to JSON feature using color_property
color = color_map(row[self.color_property], self.color_stops, self.color_default)
# link to vector feature using data_join_property (from JSON object)
vector_stops.append([row[self.data_join_property], color])
return vector_stops | [
"def",
"generate_vector_color_map",
"(",
"self",
")",
":",
"vector_stops",
"=",
"[",
"]",
"# if join data specified as filename or URL, parse JSON to list of Python dicts",
"if",
"type",
"(",
"self",
".",
"data",
")",
"==",
"str",
":",
"self",
".",
"data",
"=",
"geo... | Generate color stops array for use with match expression in mapbox template | [
"Generate",
"color",
"stops",
"array",
"for",
"use",
"with",
"match",
"expression",
"in",
"mapbox",
"template"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L20-L37 | train | 224,472 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | VectorMixin.generate_vector_numeric_map | def generate_vector_numeric_map(self, numeric_property):
"""Generate stops array for use with match expression in mapbox template"""
vector_stops = []
function_type = getattr(self, '{}_function_type'.format(numeric_property))
lookup_property = getattr(self, '{}_property'.format(numeric_property))
numeric_stops = getattr(self, '{}_stops'.format(numeric_property))
default = getattr(self, '{}_default'.format(numeric_property))
if function_type == 'match':
match_width = numeric_stops
# if join data specified as filename or URL, parse JSON to list of Python dicts
if type(self.data) == str:
self.data = geojson_to_dict_list(self.data)
for row in self.data:
# map value to JSON feature using the numeric property
value = numeric_map(row[lookup_property], numeric_stops, default)
# link to vector feature using data_join_property (from JSON object)
vector_stops.append([row[self.data_join_property], value])
return vector_stops | python | def generate_vector_numeric_map(self, numeric_property):
"""Generate stops array for use with match expression in mapbox template"""
vector_stops = []
function_type = getattr(self, '{}_function_type'.format(numeric_property))
lookup_property = getattr(self, '{}_property'.format(numeric_property))
numeric_stops = getattr(self, '{}_stops'.format(numeric_property))
default = getattr(self, '{}_default'.format(numeric_property))
if function_type == 'match':
match_width = numeric_stops
# if join data specified as filename or URL, parse JSON to list of Python dicts
if type(self.data) == str:
self.data = geojson_to_dict_list(self.data)
for row in self.data:
# map value to JSON feature using the numeric property
value = numeric_map(row[lookup_property], numeric_stops, default)
# link to vector feature using data_join_property (from JSON object)
vector_stops.append([row[self.data_join_property], value])
return vector_stops | [
"def",
"generate_vector_numeric_map",
"(",
"self",
",",
"numeric_property",
")",
":",
"vector_stops",
"=",
"[",
"]",
"function_type",
"=",
"getattr",
"(",
"self",
",",
"'{}_function_type'",
".",
"format",
"(",
"numeric_property",
")",
")",
"lookup_property",
"=",
... | Generate stops array for use with match expression in mapbox template | [
"Generate",
"stops",
"array",
"for",
"use",
"with",
"match",
"expression",
"in",
"mapbox",
"template"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L39-L63 | train | 224,473 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | VectorMixin.check_vector_template | def check_vector_template(self):
"""Determines if features are defined as vector source based on MapViz arguments."""
if self.vector_url is not None and self.vector_layer_name is not None:
self.template = 'vector_' + self.template
self.vector_source = True
else:
self.vector_source = False | python | def check_vector_template(self):
"""Determines if features are defined as vector source based on MapViz arguments."""
if self.vector_url is not None and self.vector_layer_name is not None:
self.template = 'vector_' + self.template
self.vector_source = True
else:
self.vector_source = False | [
"def",
"check_vector_template",
"(",
"self",
")",
":",
"if",
"self",
".",
"vector_url",
"is",
"not",
"None",
"and",
"self",
".",
"vector_layer_name",
"is",
"not",
"None",
":",
"self",
".",
"template",
"=",
"'vector_'",
"+",
"self",
".",
"template",
"self",... | Determines if features are defined as vector source based on MapViz arguments. | [
"Determines",
"if",
"features",
"are",
"defined",
"as",
"vector",
"source",
"based",
"on",
"MapViz",
"arguments",
"."
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L65-L72 | train | 224,474 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | MapViz.as_iframe | def as_iframe(self, html_data):
"""Build the HTML representation for the mapviz."""
srcdoc = html_data.replace('"', "'")
return ('<iframe id="{div_id}", srcdoc="{srcdoc}" style="width: {width}; '
'height: {height};"></iframe>'.format(
div_id=self.div_id,
srcdoc=srcdoc,
width=self.width,
height=self.height)) | python | def as_iframe(self, html_data):
"""Build the HTML representation for the mapviz."""
srcdoc = html_data.replace('"', "'")
return ('<iframe id="{div_id}", srcdoc="{srcdoc}" style="width: {width}; '
'height: {height};"></iframe>'.format(
div_id=self.div_id,
srcdoc=srcdoc,
width=self.width,
height=self.height)) | [
"def",
"as_iframe",
"(",
"self",
",",
"html_data",
")",
":",
"srcdoc",
"=",
"html_data",
".",
"replace",
"(",
"'\"'",
",",
"\"'\"",
")",
"return",
"(",
"'<iframe id=\"{div_id}\", srcdoc=\"{srcdoc}\" style=\"width: {width}; '",
"'height: {height};\"></iframe>'",
".",
"fo... | Build the HTML representation for the mapviz. | [
"Build",
"the",
"HTML",
"representation",
"for",
"the",
"mapviz",
"."
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L244-L253 | train | 224,475 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | CircleViz.add_unique_template_variables | def add_unique_template_variables(self, options):
"""Update map template variables specific to circle visual"""
options.update(dict(
geojson_data=json.dumps(self.data, ensure_ascii=False),
colorProperty=self.color_property,
colorType=self.color_function_type,
colorStops=self.color_stops,
strokeWidth=self.stroke_width,
strokeColor=self.stroke_color,
radius=self.radius,
defaultColor=self.color_default,
highlightColor=self.highlight_color
))
if self.vector_source:
options.update(vectorColorStops=self.generate_vector_color_map()) | python | def add_unique_template_variables(self, options):
"""Update map template variables specific to circle visual"""
options.update(dict(
geojson_data=json.dumps(self.data, ensure_ascii=False),
colorProperty=self.color_property,
colorType=self.color_function_type,
colorStops=self.color_stops,
strokeWidth=self.stroke_width,
strokeColor=self.stroke_color,
radius=self.radius,
defaultColor=self.color_default,
highlightColor=self.highlight_color
))
if self.vector_source:
options.update(vectorColorStops=self.generate_vector_color_map()) | [
"def",
"add_unique_template_variables",
"(",
"self",
",",
"options",
")",
":",
"options",
".",
"update",
"(",
"dict",
"(",
"geojson_data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"data",
",",
"ensure_ascii",
"=",
"False",
")",
",",
"colorProperty",
"=... | Update map template variables specific to circle visual | [
"Update",
"map",
"template",
"variables",
"specific",
"to",
"circle",
"visual"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L403-L418 | train | 224,476 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | GraduatedCircleViz.add_unique_template_variables | def add_unique_template_variables(self, options):
"""Update map template variables specific to graduated circle visual"""
options.update(dict(
colorProperty=self.color_property,
colorStops=self.color_stops,
colorType=self.color_function_type,
radiusType=self.radius_function_type,
defaultColor=self.color_default,
defaultRadius=self.radius_default,
radiusProperty=self.radius_property,
radiusStops=self.radius_stops,
strokeWidth=self.stroke_width,
strokeColor=self.stroke_color,
highlightColor=self.highlight_color
))
if self.vector_source:
options.update(dict(
vectorColorStops=self.generate_vector_color_map(),
vectorRadiusStops=self.generate_vector_numeric_map('radius'))) | python | def add_unique_template_variables(self, options):
"""Update map template variables specific to graduated circle visual"""
options.update(dict(
colorProperty=self.color_property,
colorStops=self.color_stops,
colorType=self.color_function_type,
radiusType=self.radius_function_type,
defaultColor=self.color_default,
defaultRadius=self.radius_default,
radiusProperty=self.radius_property,
radiusStops=self.radius_stops,
strokeWidth=self.stroke_width,
strokeColor=self.stroke_color,
highlightColor=self.highlight_color
))
if self.vector_source:
options.update(dict(
vectorColorStops=self.generate_vector_color_map(),
vectorRadiusStops=self.generate_vector_numeric_map('radius'))) | [
"def",
"add_unique_template_variables",
"(",
"self",
",",
"options",
")",
":",
"options",
".",
"update",
"(",
"dict",
"(",
"colorProperty",
"=",
"self",
".",
"color_property",
",",
"colorStops",
"=",
"self",
".",
"color_stops",
",",
"colorType",
"=",
"self",
... | Update map template variables specific to graduated circle visual | [
"Update",
"map",
"template",
"variables",
"specific",
"to",
"graduated",
"circle",
"visual"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L473-L491 | train | 224,477 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | ClusteredCircleViz.add_unique_template_variables | def add_unique_template_variables(self, options):
"""Update map template variables specific to a clustered circle visual"""
options.update(dict(
colorStops=self.color_stops,
colorDefault=self.color_default,
radiusStops=self.radius_stops,
clusterRadius=self.clusterRadius,
clusterMaxZoom=self.clusterMaxZoom,
strokeWidth=self.stroke_width,
strokeColor=self.stroke_color,
radiusDefault=self.radius_default,
highlightColor=self.highlight_color
)) | python | def add_unique_template_variables(self, options):
"""Update map template variables specific to a clustered circle visual"""
options.update(dict(
colorStops=self.color_stops,
colorDefault=self.color_default,
radiusStops=self.radius_stops,
clusterRadius=self.clusterRadius,
clusterMaxZoom=self.clusterMaxZoom,
strokeWidth=self.stroke_width,
strokeColor=self.stroke_color,
radiusDefault=self.radius_default,
highlightColor=self.highlight_color
)) | [
"def",
"add_unique_template_variables",
"(",
"self",
",",
"options",
")",
":",
"options",
".",
"update",
"(",
"dict",
"(",
"colorStops",
"=",
"self",
".",
"color_stops",
",",
"colorDefault",
"=",
"self",
".",
"color_default",
",",
"radiusStops",
"=",
"self",
... | Update map template variables specific to a clustered circle visual | [
"Update",
"map",
"template",
"variables",
"specific",
"to",
"a",
"clustered",
"circle",
"visual"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L608-L620 | train | 224,478 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | ImageViz.add_unique_template_variables | def add_unique_template_variables(self, options):
"""Update map template variables specific to image visual"""
options.update(dict(
image=self.image,
coordinates=self.coordinates)) | python | def add_unique_template_variables(self, options):
"""Update map template variables specific to image visual"""
options.update(dict(
image=self.image,
coordinates=self.coordinates)) | [
"def",
"add_unique_template_variables",
"(",
"self",
",",
"options",
")",
":",
"options",
".",
"update",
"(",
"dict",
"(",
"image",
"=",
"self",
".",
"image",
",",
"coordinates",
"=",
"self",
".",
"coordinates",
")",
")"
] | Update map template variables specific to image visual | [
"Update",
"map",
"template",
"variables",
"specific",
"to",
"image",
"visual"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L760-L764 | train | 224,479 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | RasterTilesViz.add_unique_template_variables | def add_unique_template_variables(self, options):
"""Update map template variables specific to a raster visual"""
options.update(dict(
tiles_url=self.tiles_url,
tiles_size=self.tiles_size,
tiles_minzoom=self.tiles_minzoom,
tiles_maxzoom=self.tiles_maxzoom,
tiles_bounds=self.tiles_bounds if self.tiles_bounds else 'undefined')) | python | def add_unique_template_variables(self, options):
"""Update map template variables specific to a raster visual"""
options.update(dict(
tiles_url=self.tiles_url,
tiles_size=self.tiles_size,
tiles_minzoom=self.tiles_minzoom,
tiles_maxzoom=self.tiles_maxzoom,
tiles_bounds=self.tiles_bounds if self.tiles_bounds else 'undefined')) | [
"def",
"add_unique_template_variables",
"(",
"self",
",",
"options",
")",
":",
"options",
".",
"update",
"(",
"dict",
"(",
"tiles_url",
"=",
"self",
".",
"tiles_url",
",",
"tiles_size",
"=",
"self",
".",
"tiles_size",
",",
"tiles_minzoom",
"=",
"self",
".",
... | Update map template variables specific to a raster visual | [
"Update",
"map",
"template",
"variables",
"specific",
"to",
"a",
"raster",
"visual"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L798-L805 | train | 224,480 |
mapbox/mapboxgl-jupyter | mapboxgl/viz.py | LinestringViz.add_unique_template_variables | def add_unique_template_variables(self, options):
"""Update map template variables specific to linestring visual"""
# set line stroke dash interval based on line_stroke property
if self.line_stroke in ["dashed", "--"]:
self.line_dash_array = [6, 4]
elif self.line_stroke in ["dotted", ":"]:
self.line_dash_array = [0.5, 4]
elif self.line_stroke in ["dash dot", "-."]:
self.line_dash_array = [6, 4, 0.5, 4]
elif self.line_stroke in ["solid", "-"]:
self.line_dash_array = [1, 0]
else:
# default to solid line
self.line_dash_array = [1, 0]
# common variables for vector and geojson-based linestring maps
options.update(dict(
colorStops=self.color_stops,
colorProperty=self.color_property,
colorType=self.color_function_type,
defaultColor=self.color_default,
lineColor=self.color_default,
lineDashArray=self.line_dash_array,
lineStroke=self.line_stroke,
widthStops=self.line_width_stops,
widthProperty=self.line_width_property,
widthType=self.line_width_function_type,
defaultWidth=self.line_width_default,
highlightColor=self.highlight_color
))
# vector-based linestring map variables
if self.vector_source:
options.update(dict(
vectorColorStops=[[0, self.color_default]],
vectorWidthStops=[[0, self.line_width_default]],
))
if self.color_property:
options.update(vectorColorStops=self.generate_vector_color_map())
if self.line_width_property:
options.update(vectorWidthStops=self.generate_vector_numeric_map('line_width'))
# geojson-based linestring map variables
else:
options.update(geojson_data=json.dumps(self.data, ensure_ascii=False)) | python | def add_unique_template_variables(self, options):
"""Update map template variables specific to linestring visual"""
# set line stroke dash interval based on line_stroke property
if self.line_stroke in ["dashed", "--"]:
self.line_dash_array = [6, 4]
elif self.line_stroke in ["dotted", ":"]:
self.line_dash_array = [0.5, 4]
elif self.line_stroke in ["dash dot", "-."]:
self.line_dash_array = [6, 4, 0.5, 4]
elif self.line_stroke in ["solid", "-"]:
self.line_dash_array = [1, 0]
else:
# default to solid line
self.line_dash_array = [1, 0]
# common variables for vector and geojson-based linestring maps
options.update(dict(
colorStops=self.color_stops,
colorProperty=self.color_property,
colorType=self.color_function_type,
defaultColor=self.color_default,
lineColor=self.color_default,
lineDashArray=self.line_dash_array,
lineStroke=self.line_stroke,
widthStops=self.line_width_stops,
widthProperty=self.line_width_property,
widthType=self.line_width_function_type,
defaultWidth=self.line_width_default,
highlightColor=self.highlight_color
))
# vector-based linestring map variables
if self.vector_source:
options.update(dict(
vectorColorStops=[[0, self.color_default]],
vectorWidthStops=[[0, self.line_width_default]],
))
if self.color_property:
options.update(vectorColorStops=self.generate_vector_color_map())
if self.line_width_property:
options.update(vectorWidthStops=self.generate_vector_numeric_map('line_width'))
# geojson-based linestring map variables
else:
options.update(geojson_data=json.dumps(self.data, ensure_ascii=False)) | [
"def",
"add_unique_template_variables",
"(",
"self",
",",
"options",
")",
":",
"# set line stroke dash interval based on line_stroke property",
"if",
"self",
".",
"line_stroke",
"in",
"[",
"\"dashed\"",
",",
"\"--\"",
"]",
":",
"self",
".",
"line_dash_array",
"=",
"["... | Update map template variables specific to linestring visual | [
"Update",
"map",
"template",
"variables",
"specific",
"to",
"linestring",
"visual"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/viz.py#L861-L908 | train | 224,481 |
mapbox/mapboxgl-jupyter | mapboxgl/utils.py | row_to_geojson | def row_to_geojson(row, lon, lat, precision, date_format='epoch'):
"""Convert a pandas dataframe row to a geojson format object. Converts all datetimes to epoch seconds.
"""
# Let pandas handle json serialization
row_json = json.loads(row.to_json(date_format=date_format, date_unit='s'))
return geojson.Feature(geometry=geojson.Point((round(row_json[lon], precision), round(row_json[lat], precision))),
properties={key: row_json[key] for key in row_json.keys() if key not in [lon, lat]}) | python | def row_to_geojson(row, lon, lat, precision, date_format='epoch'):
"""Convert a pandas dataframe row to a geojson format object. Converts all datetimes to epoch seconds.
"""
# Let pandas handle json serialization
row_json = json.loads(row.to_json(date_format=date_format, date_unit='s'))
return geojson.Feature(geometry=geojson.Point((round(row_json[lon], precision), round(row_json[lat], precision))),
properties={key: row_json[key] for key in row_json.keys() if key not in [lon, lat]}) | [
"def",
"row_to_geojson",
"(",
"row",
",",
"lon",
",",
"lat",
",",
"precision",
",",
"date_format",
"=",
"'epoch'",
")",
":",
"# Let pandas handle json serialization",
"row_json",
"=",
"json",
".",
"loads",
"(",
"row",
".",
"to_json",
"(",
"date_format",
"=",
... | Convert a pandas dataframe row to a geojson format object. Converts all datetimes to epoch seconds. | [
"Convert",
"a",
"pandas",
"dataframe",
"row",
"to",
"a",
"geojson",
"format",
"object",
".",
"Converts",
"all",
"datetimes",
"to",
"epoch",
"seconds",
"."
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/utils.py#L17-L24 | train | 224,482 |
mapbox/mapboxgl-jupyter | mapboxgl/utils.py | scale_between | def scale_between(minval, maxval, numStops):
""" Scale a min and max value to equal interval domain with
numStops discrete values
"""
scale = []
if numStops < 2:
return [minval, maxval]
elif maxval < minval:
raise ValueError()
else:
domain = maxval - minval
interval = float(domain) / float(numStops)
for i in range(numStops):
scale.append(round(minval + interval * i, 2))
return scale | python | def scale_between(minval, maxval, numStops):
""" Scale a min and max value to equal interval domain with
numStops discrete values
"""
scale = []
if numStops < 2:
return [minval, maxval]
elif maxval < minval:
raise ValueError()
else:
domain = maxval - minval
interval = float(domain) / float(numStops)
for i in range(numStops):
scale.append(round(minval + interval * i, 2))
return scale | [
"def",
"scale_between",
"(",
"minval",
",",
"maxval",
",",
"numStops",
")",
":",
"scale",
"=",
"[",
"]",
"if",
"numStops",
"<",
"2",
":",
"return",
"[",
"minval",
",",
"maxval",
"]",
"elif",
"maxval",
"<",
"minval",
":",
"raise",
"ValueError",
"(",
"... | Scale a min and max value to equal interval domain with
numStops discrete values | [
"Scale",
"a",
"min",
"and",
"max",
"value",
"to",
"equal",
"interval",
"domain",
"with",
"numStops",
"discrete",
"values"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/utils.py#L138-L154 | train | 224,483 |
mapbox/mapboxgl-jupyter | mapboxgl/utils.py | create_radius_stops | def create_radius_stops(breaks, min_radius, max_radius):
"""Convert a data breaks into a radius ramp
"""
num_breaks = len(breaks)
radius_breaks = scale_between(min_radius, max_radius, num_breaks)
stops = []
for i, b in enumerate(breaks):
stops.append([b, radius_breaks[i]])
return stops | python | def create_radius_stops(breaks, min_radius, max_radius):
"""Convert a data breaks into a radius ramp
"""
num_breaks = len(breaks)
radius_breaks = scale_between(min_radius, max_radius, num_breaks)
stops = []
for i, b in enumerate(breaks):
stops.append([b, radius_breaks[i]])
return stops | [
"def",
"create_radius_stops",
"(",
"breaks",
",",
"min_radius",
",",
"max_radius",
")",
":",
"num_breaks",
"=",
"len",
"(",
"breaks",
")",
"radius_breaks",
"=",
"scale_between",
"(",
"min_radius",
",",
"max_radius",
",",
"num_breaks",
")",
"stops",
"=",
"[",
... | Convert a data breaks into a radius ramp | [
"Convert",
"a",
"data",
"breaks",
"into",
"a",
"radius",
"ramp"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/utils.py#L157-L166 | train | 224,484 |
mapbox/mapboxgl-jupyter | mapboxgl/utils.py | create_weight_stops | def create_weight_stops(breaks):
"""Convert data breaks into a heatmap-weight ramp
"""
num_breaks = len(breaks)
weight_breaks = scale_between(0, 1, num_breaks)
stops = []
for i, b in enumerate(breaks):
stops.append([b, weight_breaks[i]])
return stops | python | def create_weight_stops(breaks):
"""Convert data breaks into a heatmap-weight ramp
"""
num_breaks = len(breaks)
weight_breaks = scale_between(0, 1, num_breaks)
stops = []
for i, b in enumerate(breaks):
stops.append([b, weight_breaks[i]])
return stops | [
"def",
"create_weight_stops",
"(",
"breaks",
")",
":",
"num_breaks",
"=",
"len",
"(",
"breaks",
")",
"weight_breaks",
"=",
"scale_between",
"(",
"0",
",",
"1",
",",
"num_breaks",
")",
"stops",
"=",
"[",
"]",
"for",
"i",
",",
"b",
"in",
"enumerate",
"("... | Convert data breaks into a heatmap-weight ramp | [
"Convert",
"data",
"breaks",
"into",
"a",
"heatmap",
"-",
"weight",
"ramp"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/utils.py#L169-L178 | train | 224,485 |
mapbox/mapboxgl-jupyter | mapboxgl/utils.py | create_color_stops | def create_color_stops(breaks, colors='RdYlGn', color_ramps=color_ramps):
"""Convert a list of breaks into color stops using colors from colorBrewer
or a custom list of color values in RGB, RGBA, HSL, CSS text, or HEX format.
See www.colorbrewer2.org for a list of color options to pass
"""
num_breaks = len(breaks)
stops = []
if isinstance(colors, list):
# Check if colors contain a list of color values
if len(colors) == 0 or len(colors) != num_breaks:
raise ValueError(
'custom color list must be of same length as breaks list')
for color in colors:
# Check if color is valid string
try:
Colour(color)
except:
raise ValueError(
'The color code {color} is in the wrong format'.format(color=color))
for i, b in enumerate(breaks):
stops.append([b, colors[i]])
else:
if colors not in color_ramps.keys():
raise ValueError('color does not exist in colorBrewer!')
else:
try:
ramp = color_ramps[colors][num_breaks]
except KeyError:
raise ValueError("Color ramp {} does not have a {} breaks".format(
colors, num_breaks))
for i, b in enumerate(breaks):
stops.append([b, ramp[i]])
return stops | python | def create_color_stops(breaks, colors='RdYlGn', color_ramps=color_ramps):
"""Convert a list of breaks into color stops using colors from colorBrewer
or a custom list of color values in RGB, RGBA, HSL, CSS text, or HEX format.
See www.colorbrewer2.org for a list of color options to pass
"""
num_breaks = len(breaks)
stops = []
if isinstance(colors, list):
# Check if colors contain a list of color values
if len(colors) == 0 or len(colors) != num_breaks:
raise ValueError(
'custom color list must be of same length as breaks list')
for color in colors:
# Check if color is valid string
try:
Colour(color)
except:
raise ValueError(
'The color code {color} is in the wrong format'.format(color=color))
for i, b in enumerate(breaks):
stops.append([b, colors[i]])
else:
if colors not in color_ramps.keys():
raise ValueError('color does not exist in colorBrewer!')
else:
try:
ramp = color_ramps[colors][num_breaks]
except KeyError:
raise ValueError("Color ramp {} does not have a {} breaks".format(
colors, num_breaks))
for i, b in enumerate(breaks):
stops.append([b, ramp[i]])
return stops | [
"def",
"create_color_stops",
"(",
"breaks",
",",
"colors",
"=",
"'RdYlGn'",
",",
"color_ramps",
"=",
"color_ramps",
")",
":",
"num_breaks",
"=",
"len",
"(",
"breaks",
")",
"stops",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"colors",
",",
"list",
")",
":",
... | Convert a list of breaks into color stops using colors from colorBrewer
or a custom list of color values in RGB, RGBA, HSL, CSS text, or HEX format.
See www.colorbrewer2.org for a list of color options to pass | [
"Convert",
"a",
"list",
"of",
"breaks",
"into",
"color",
"stops",
"using",
"colors",
"from",
"colorBrewer",
"or",
"a",
"custom",
"list",
"of",
"color",
"values",
"in",
"RGB",
"RGBA",
"HSL",
"CSS",
"text",
"or",
"HEX",
"format",
".",
"See",
"www",
".",
... | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/utils.py#L188-L228 | train | 224,486 |
mapbox/mapboxgl-jupyter | mapboxgl/utils.py | numeric_map | def numeric_map(lookup, numeric_stops, default=0.0):
"""Return a number value interpolated from given numeric_stops
"""
# if no numeric_stops, use default
if len(numeric_stops) == 0:
return default
# dictionary to lookup value from match-type numeric_stops
match_map = dict((x, y) for (x, y) in numeric_stops)
# if lookup matches stop exactly, return corresponding stop (first priority)
# (includes non-numeric numeric_stop "keys" for finding value by match)
if lookup in match_map.keys():
return match_map.get(lookup)
# if lookup value numeric, map value by interpolating from scale
if isinstance(lookup, (int, float, complex)):
# try ordering stops
try:
stops, values = zip(*sorted(numeric_stops))
# if not all stops are numeric, attempt looking up as if categorical stops
except TypeError:
return match_map.get(lookup, default)
# for interpolation, all stops must be numeric
if not all(isinstance(x, (int, float, complex)) for x in stops):
return default
# check if lookup value in stops bounds
if float(lookup) <= stops[0]:
return values[0]
elif float(lookup) >= stops[-1]:
return values[-1]
# check if lookup value matches any stop value
elif float(lookup) in stops:
return values[stops.index(lookup)]
# interpolation required
else:
# identify bounding stop values
lower = max([stops[0]] + [x for x in stops if x < lookup])
upper = min([stops[-1]] + [x for x in stops if x > lookup])
# values from bounding stops
lower_value = values[stops.index(lower)]
upper_value = values[stops.index(upper)]
# compute linear "relative distance" from lower bound to upper bound
distance = (lookup - lower) / (upper - lower)
# return interpolated value
return lower_value + distance * (upper_value - lower_value)
# default value catch-all
return default | python | def numeric_map(lookup, numeric_stops, default=0.0):
"""Return a number value interpolated from given numeric_stops
"""
# if no numeric_stops, use default
if len(numeric_stops) == 0:
return default
# dictionary to lookup value from match-type numeric_stops
match_map = dict((x, y) for (x, y) in numeric_stops)
# if lookup matches stop exactly, return corresponding stop (first priority)
# (includes non-numeric numeric_stop "keys" for finding value by match)
if lookup in match_map.keys():
return match_map.get(lookup)
# if lookup value numeric, map value by interpolating from scale
if isinstance(lookup, (int, float, complex)):
# try ordering stops
try:
stops, values = zip(*sorted(numeric_stops))
# if not all stops are numeric, attempt looking up as if categorical stops
except TypeError:
return match_map.get(lookup, default)
# for interpolation, all stops must be numeric
if not all(isinstance(x, (int, float, complex)) for x in stops):
return default
# check if lookup value in stops bounds
if float(lookup) <= stops[0]:
return values[0]
elif float(lookup) >= stops[-1]:
return values[-1]
# check if lookup value matches any stop value
elif float(lookup) in stops:
return values[stops.index(lookup)]
# interpolation required
else:
# identify bounding stop values
lower = max([stops[0]] + [x for x in stops if x < lookup])
upper = min([stops[-1]] + [x for x in stops if x > lookup])
# values from bounding stops
lower_value = values[stops.index(lower)]
upper_value = values[stops.index(upper)]
# compute linear "relative distance" from lower bound to upper bound
distance = (lookup - lower) / (upper - lower)
# return interpolated value
return lower_value + distance * (upper_value - lower_value)
# default value catch-all
return default | [
"def",
"numeric_map",
"(",
"lookup",
",",
"numeric_stops",
",",
"default",
"=",
"0.0",
")",
":",
"# if no numeric_stops, use default",
"if",
"len",
"(",
"numeric_stops",
")",
"==",
"0",
":",
"return",
"default",
"# dictionary to lookup value from match-type numeric_stop... | Return a number value interpolated from given numeric_stops | [
"Return",
"a",
"number",
"value",
"interpolated",
"from",
"given",
"numeric_stops"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/utils.py#L321-L380 | train | 224,487 |
marshmallow-code/apispec | src/apispec/yaml_utils.py | load_yaml_from_docstring | def load_yaml_from_docstring(docstring):
"""Loads YAML from docstring."""
split_lines = trim_docstring(docstring).split("\n")
# Cut YAML from rest of docstring
for index, line in enumerate(split_lines):
line = line.strip()
if line.startswith("---"):
cut_from = index
break
else:
return {}
yaml_string = "\n".join(split_lines[cut_from:])
yaml_string = dedent(yaml_string)
return yaml.safe_load(yaml_string) or {} | python | def load_yaml_from_docstring(docstring):
"""Loads YAML from docstring."""
split_lines = trim_docstring(docstring).split("\n")
# Cut YAML from rest of docstring
for index, line in enumerate(split_lines):
line = line.strip()
if line.startswith("---"):
cut_from = index
break
else:
return {}
yaml_string = "\n".join(split_lines[cut_from:])
yaml_string = dedent(yaml_string)
return yaml.safe_load(yaml_string) or {} | [
"def",
"load_yaml_from_docstring",
"(",
"docstring",
")",
":",
"split_lines",
"=",
"trim_docstring",
"(",
"docstring",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"# Cut YAML from rest of docstring",
"for",
"index",
",",
"line",
"in",
"enumerate",
"(",
"split_lines",
... | Loads YAML from docstring. | [
"Loads",
"YAML",
"from",
"docstring",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/yaml_utils.py#L32-L47 | train | 224,488 |
marshmallow-code/apispec | src/apispec/yaml_utils.py | load_operations_from_docstring | def load_operations_from_docstring(docstring):
"""Return a dictionary of OpenAPI operations parsed from a
a docstring.
"""
doc_data = load_yaml_from_docstring(docstring)
return {
key: val
for key, val in iteritems(doc_data)
if key in PATH_KEYS or key.startswith("x-")
} | python | def load_operations_from_docstring(docstring):
"""Return a dictionary of OpenAPI operations parsed from a
a docstring.
"""
doc_data = load_yaml_from_docstring(docstring)
return {
key: val
for key, val in iteritems(doc_data)
if key in PATH_KEYS or key.startswith("x-")
} | [
"def",
"load_operations_from_docstring",
"(",
"docstring",
")",
":",
"doc_data",
"=",
"load_yaml_from_docstring",
"(",
"docstring",
")",
"return",
"{",
"key",
":",
"val",
"for",
"key",
",",
"val",
"in",
"iteritems",
"(",
"doc_data",
")",
"if",
"key",
"in",
"... | Return a dictionary of OpenAPI operations parsed from a
a docstring. | [
"Return",
"a",
"dictionary",
"of",
"OpenAPI",
"operations",
"parsed",
"from",
"a",
"a",
"docstring",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/yaml_utils.py#L53-L62 | train | 224,489 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/common.py | get_fields | def get_fields(schema, exclude_dump_only=False):
"""Return fields from schema
:param Schema schema: A marshmallow Schema instance or a class object
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only
:rtype: dict, of field name field object pairs
"""
if hasattr(schema, "fields"):
fields = schema.fields
elif hasattr(schema, "_declared_fields"):
fields = copy.deepcopy(schema._declared_fields)
else:
raise ValueError(
"{!r} doesn't have either `fields` or `_declared_fields`.".format(schema)
)
Meta = getattr(schema, "Meta", None)
warn_if_fields_defined_in_meta(fields, Meta)
return filter_excluded_fields(fields, Meta, exclude_dump_only) | python | def get_fields(schema, exclude_dump_only=False):
"""Return fields from schema
:param Schema schema: A marshmallow Schema instance or a class object
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only
:rtype: dict, of field name field object pairs
"""
if hasattr(schema, "fields"):
fields = schema.fields
elif hasattr(schema, "_declared_fields"):
fields = copy.deepcopy(schema._declared_fields)
else:
raise ValueError(
"{!r} doesn't have either `fields` or `_declared_fields`.".format(schema)
)
Meta = getattr(schema, "Meta", None)
warn_if_fields_defined_in_meta(fields, Meta)
return filter_excluded_fields(fields, Meta, exclude_dump_only) | [
"def",
"get_fields",
"(",
"schema",
",",
"exclude_dump_only",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"schema",
",",
"\"fields\"",
")",
":",
"fields",
"=",
"schema",
".",
"fields",
"elif",
"hasattr",
"(",
"schema",
",",
"\"_declared_fields\"",
")",
"... | Return fields from schema
:param Schema schema: A marshmallow Schema instance or a class object
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only
:rtype: dict, of field name field object pairs | [
"Return",
"fields",
"from",
"schema"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/common.py#L52-L69 | train | 224,490 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/common.py | warn_if_fields_defined_in_meta | def warn_if_fields_defined_in_meta(fields, Meta):
"""Warns user that fields defined in Meta.fields or Meta.additional will
be ignored
:param dict fields: A dictionary of fields name field object pairs
:param Meta: the schema's Meta class
"""
if getattr(Meta, "fields", None) or getattr(Meta, "additional", None):
declared_fields = set(fields.keys())
if (
set(getattr(Meta, "fields", set())) > declared_fields
or set(getattr(Meta, "additional", set())) > declared_fields
):
warnings.warn(
"Only explicitly-declared fields will be included in the Schema Object. "
"Fields defined in Meta.fields or Meta.additional are ignored."
) | python | def warn_if_fields_defined_in_meta(fields, Meta):
"""Warns user that fields defined in Meta.fields or Meta.additional will
be ignored
:param dict fields: A dictionary of fields name field object pairs
:param Meta: the schema's Meta class
"""
if getattr(Meta, "fields", None) or getattr(Meta, "additional", None):
declared_fields = set(fields.keys())
if (
set(getattr(Meta, "fields", set())) > declared_fields
or set(getattr(Meta, "additional", set())) > declared_fields
):
warnings.warn(
"Only explicitly-declared fields will be included in the Schema Object. "
"Fields defined in Meta.fields or Meta.additional are ignored."
) | [
"def",
"warn_if_fields_defined_in_meta",
"(",
"fields",
",",
"Meta",
")",
":",
"if",
"getattr",
"(",
"Meta",
",",
"\"fields\"",
",",
"None",
")",
"or",
"getattr",
"(",
"Meta",
",",
"\"additional\"",
",",
"None",
")",
":",
"declared_fields",
"=",
"set",
"("... | Warns user that fields defined in Meta.fields or Meta.additional will
be ignored
:param dict fields: A dictionary of fields name field object pairs
:param Meta: the schema's Meta class | [
"Warns",
"user",
"that",
"fields",
"defined",
"in",
"Meta",
".",
"fields",
"or",
"Meta",
".",
"additional",
"will",
"be",
"ignored"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/common.py#L72-L88 | train | 224,491 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/common.py | filter_excluded_fields | def filter_excluded_fields(fields, Meta, exclude_dump_only):
"""Filter fields that should be ignored in the OpenAPI spec
:param dict fields: A dictionary of fields name field object pairs
:param Meta: the schema's Meta class
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only
"""
exclude = list(getattr(Meta, "exclude", []))
if exclude_dump_only:
exclude.extend(getattr(Meta, "dump_only", []))
filtered_fields = OrderedDict(
(key, value) for key, value in fields.items() if key not in exclude
)
return filtered_fields | python | def filter_excluded_fields(fields, Meta, exclude_dump_only):
"""Filter fields that should be ignored in the OpenAPI spec
:param dict fields: A dictionary of fields name field object pairs
:param Meta: the schema's Meta class
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only
"""
exclude = list(getattr(Meta, "exclude", []))
if exclude_dump_only:
exclude.extend(getattr(Meta, "dump_only", []))
filtered_fields = OrderedDict(
(key, value) for key, value in fields.items() if key not in exclude
)
return filtered_fields | [
"def",
"filter_excluded_fields",
"(",
"fields",
",",
"Meta",
",",
"exclude_dump_only",
")",
":",
"exclude",
"=",
"list",
"(",
"getattr",
"(",
"Meta",
",",
"\"exclude\"",
",",
"[",
"]",
")",
")",
"if",
"exclude_dump_only",
":",
"exclude",
".",
"extend",
"("... | Filter fields that should be ignored in the OpenAPI spec
:param dict fields: A dictionary of fields name field object pairs
:param Meta: the schema's Meta class
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only | [
"Filter",
"fields",
"that",
"should",
"be",
"ignored",
"in",
"the",
"OpenAPI",
"spec"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/common.py#L91-L106 | train | 224,492 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/common.py | get_unique_schema_name | def get_unique_schema_name(components, name, counter=0):
"""Function to generate a unique name based on the provided name and names
already in the spec. Will append a number to the name to make it unique if
the name is already in the spec.
:param Components components: instance of the components of the spec
:param string name: the name to use as a basis for the unique name
:param int counter: the counter of the number of recursions
:return: the unique name
"""
if name not in components._schemas:
return name
if not counter: # first time through recursion
warnings.warn(
"Multiple schemas resolved to the name {}. The name has been modified. "
"Either manually add each of the schemas with a different name or "
"provide a custom schema_name_resolver.".format(name),
UserWarning,
)
else: # subsequent recursions
name = name[: -len(str(counter))]
counter += 1
return get_unique_schema_name(components, name + str(counter), counter) | python | def get_unique_schema_name(components, name, counter=0):
"""Function to generate a unique name based on the provided name and names
already in the spec. Will append a number to the name to make it unique if
the name is already in the spec.
:param Components components: instance of the components of the spec
:param string name: the name to use as a basis for the unique name
:param int counter: the counter of the number of recursions
:return: the unique name
"""
if name not in components._schemas:
return name
if not counter: # first time through recursion
warnings.warn(
"Multiple schemas resolved to the name {}. The name has been modified. "
"Either manually add each of the schemas with a different name or "
"provide a custom schema_name_resolver.".format(name),
UserWarning,
)
else: # subsequent recursions
name = name[: -len(str(counter))]
counter += 1
return get_unique_schema_name(components, name + str(counter), counter) | [
"def",
"get_unique_schema_name",
"(",
"components",
",",
"name",
",",
"counter",
"=",
"0",
")",
":",
"if",
"name",
"not",
"in",
"components",
".",
"_schemas",
":",
"return",
"name",
"if",
"not",
"counter",
":",
"# first time through recursion",
"warnings",
"."... | Function to generate a unique name based on the provided name and names
already in the spec. Will append a number to the name to make it unique if
the name is already in the spec.
:param Components components: instance of the components of the spec
:param string name: the name to use as a basis for the unique name
:param int counter: the counter of the number of recursions
:return: the unique name | [
"Function",
"to",
"generate",
"a",
"unique",
"name",
"based",
"on",
"the",
"provided",
"name",
"and",
"names",
"already",
"in",
"the",
"spec",
".",
"Will",
"append",
"a",
"number",
"to",
"the",
"name",
"to",
"make",
"it",
"unique",
"if",
"the",
"name",
... | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/common.py#L128-L150 | train | 224,493 |
marshmallow-code/apispec | src/apispec/utils.py | build_reference | def build_reference(component_type, openapi_major_version, component_name):
"""Return path to reference
:param str component_type: Component type (schema, parameter, response, security_scheme)
:param int openapi_major_version: OpenAPI major version (2 or 3)
:param str component_name: Name of component to reference
"""
return {
"$ref": "#/{}{}/{}".format(
"components/" if openapi_major_version >= 3 else "",
COMPONENT_SUBSECTIONS[openapi_major_version][component_type],
component_name,
)
} | python | def build_reference(component_type, openapi_major_version, component_name):
"""Return path to reference
:param str component_type: Component type (schema, parameter, response, security_scheme)
:param int openapi_major_version: OpenAPI major version (2 or 3)
:param str component_name: Name of component to reference
"""
return {
"$ref": "#/{}{}/{}".format(
"components/" if openapi_major_version >= 3 else "",
COMPONENT_SUBSECTIONS[openapi_major_version][component_type],
component_name,
)
} | [
"def",
"build_reference",
"(",
"component_type",
",",
"openapi_major_version",
",",
"component_name",
")",
":",
"return",
"{",
"\"$ref\"",
":",
"\"#/{}{}/{}\"",
".",
"format",
"(",
"\"components/\"",
"if",
"openapi_major_version",
">=",
"3",
"else",
"\"\"",
",",
"... | Return path to reference
:param str component_type: Component type (schema, parameter, response, security_scheme)
:param int openapi_major_version: OpenAPI major version (2 or 3)
:param str component_name: Name of component to reference | [
"Return",
"path",
"to",
"reference"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/utils.py#L29-L42 | train | 224,494 |
marshmallow-code/apispec | src/apispec/utils.py | deepupdate | def deepupdate(original, update):
"""Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update | python | def deepupdate(original, update):
"""Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update | [
"def",
"deepupdate",
"(",
"original",
",",
"update",
")",
":",
"for",
"key",
",",
"value",
"in",
"original",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"update",
":",
"update",
"[",
"key",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"... | Recursively update a dict.
Subdict's won't be overwritten but also updated. | [
"Recursively",
"update",
"a",
"dict",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/utils.py#L162-L172 | train | 224,495 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter._observed_name | def _observed_name(field, name):
"""Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str
"""
if MARSHMALLOW_VERSION_INFO[0] < 3:
# use getattr in case we're running against older versions of marshmallow.
dump_to = getattr(field, "dump_to", None)
load_from = getattr(field, "load_from", None)
return dump_to or load_from or name
return field.data_key or name | python | def _observed_name(field, name):
"""Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str
"""
if MARSHMALLOW_VERSION_INFO[0] < 3:
# use getattr in case we're running against older versions of marshmallow.
dump_to = getattr(field, "dump_to", None)
load_from = getattr(field, "load_from", None)
return dump_to or load_from or name
return field.data_key or name | [
"def",
"_observed_name",
"(",
"field",
",",
"name",
")",
":",
"if",
"MARSHMALLOW_VERSION_INFO",
"[",
"0",
"]",
"<",
"3",
":",
"# use getattr in case we're running against older versions of marshmallow.",
"dump_to",
"=",
"getattr",
"(",
"field",
",",
"\"dump_to\"",
","... | Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str | [
"Adjust",
"field",
"name",
"to",
"reflect",
"dump_to",
"and",
"load_from",
"attributes",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L124-L136 | train | 224,496 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.map_to_openapi_type | def map_to_openapi_type(self, *args):
"""Decorator to set mapping for custom fields.
``*args`` can be:
- a pair of the form ``(type, format)``
- a core marshmallow field type (in which case we reuse that type's mapping)
"""
if len(args) == 1 and args[0] in self.field_mapping:
openapi_type_field = self.field_mapping[args[0]]
elif len(args) == 2:
openapi_type_field = args
else:
raise TypeError("Pass core marshmallow field type or (type, fmt) pair.")
def inner(field_type):
self.field_mapping[field_type] = openapi_type_field
return field_type
return inner | python | def map_to_openapi_type(self, *args):
"""Decorator to set mapping for custom fields.
``*args`` can be:
- a pair of the form ``(type, format)``
- a core marshmallow field type (in which case we reuse that type's mapping)
"""
if len(args) == 1 and args[0] in self.field_mapping:
openapi_type_field = self.field_mapping[args[0]]
elif len(args) == 2:
openapi_type_field = args
else:
raise TypeError("Pass core marshmallow field type or (type, fmt) pair.")
def inner(field_type):
self.field_mapping[field_type] = openapi_type_field
return field_type
return inner | [
"def",
"map_to_openapi_type",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"args",
"[",
"0",
"]",
"in",
"self",
".",
"field_mapping",
":",
"openapi_type_field",
"=",
"self",
".",
"field_mapping",
"[",
"args"... | Decorator to set mapping for custom fields.
``*args`` can be:
- a pair of the form ``(type, format)``
- a core marshmallow field type (in which case we reuse that type's mapping) | [
"Decorator",
"to",
"set",
"mapping",
"for",
"custom",
"fields",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L138-L157 | train | 224,497 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2type_and_format | def field2type_and_format(self, field):
"""Return the dictionary of OpenAPI type and format based on the field
type
:param Field field: A marshmallow field.
:rtype: dict
"""
# If this type isn't directly in the field mapping then check the
# hierarchy until we find something that does.
for field_class in type(field).__mro__:
if field_class in self.field_mapping:
type_, fmt = self.field_mapping[field_class]
break
else:
warnings.warn(
"Field of type {} does not inherit from marshmallow.Field.".format(
type(field)
),
UserWarning,
)
type_, fmt = "string", None
ret = {"type": type_}
if fmt:
ret["format"] = fmt
return ret | python | def field2type_and_format(self, field):
"""Return the dictionary of OpenAPI type and format based on the field
type
:param Field field: A marshmallow field.
:rtype: dict
"""
# If this type isn't directly in the field mapping then check the
# hierarchy until we find something that does.
for field_class in type(field).__mro__:
if field_class in self.field_mapping:
type_, fmt = self.field_mapping[field_class]
break
else:
warnings.warn(
"Field of type {} does not inherit from marshmallow.Field.".format(
type(field)
),
UserWarning,
)
type_, fmt = "string", None
ret = {"type": type_}
if fmt:
ret["format"] = fmt
return ret | [
"def",
"field2type_and_format",
"(",
"self",
",",
"field",
")",
":",
"# If this type isn't directly in the field mapping then check the",
"# hierarchy until we find something that does.",
"for",
"field_class",
"in",
"type",
"(",
"field",
")",
".",
"__mro__",
":",
"if",
"fie... | Return the dictionary of OpenAPI type and format based on the field
type
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"type",
"and",
"format",
"based",
"on",
"the",
"field",
"type"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L159-L186 | train | 224,498 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2default | def field2default(self, field):
"""Return the dictionary containing the field's default value
Will first look for a `doc_default` key in the field's metadata and then
fall back on the field's `missing` parameter. A callable passed to the
field's missing parameter will be ignored.
:param Field field: A marshmallow field.
:rtype: dict
"""
ret = {}
if "doc_default" in field.metadata:
ret["default"] = field.metadata["doc_default"]
else:
default = field.missing
if default is not marshmallow.missing and not callable(default):
ret["default"] = default
return ret | python | def field2default(self, field):
"""Return the dictionary containing the field's default value
Will first look for a `doc_default` key in the field's metadata and then
fall back on the field's `missing` parameter. A callable passed to the
field's missing parameter will be ignored.
:param Field field: A marshmallow field.
:rtype: dict
"""
ret = {}
if "doc_default" in field.metadata:
ret["default"] = field.metadata["doc_default"]
else:
default = field.missing
if default is not marshmallow.missing and not callable(default):
ret["default"] = default
return ret | [
"def",
"field2default",
"(",
"self",
",",
"field",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"\"doc_default\"",
"in",
"field",
".",
"metadata",
":",
"ret",
"[",
"\"default\"",
"]",
"=",
"field",
".",
"metadata",
"[",
"\"doc_default\"",
"]",
"else",
":",
"d... | Return the dictionary containing the field's default value
Will first look for a `doc_default` key in the field's metadata and then
fall back on the field's `missing` parameter. A callable passed to the
field's missing parameter will be ignored.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"containing",
"the",
"field",
"s",
"default",
"value"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L188-L206 | train | 224,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.