id int32 0 252k | 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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,600 | 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",
"=",
"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"
] | 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 |
229,601 | 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 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",
"+",
"'/'"
] | 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 |
229,602 | 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",
":",
"]",
"# 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",
")",
")"
] | 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 |
229,603 | 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 ",
"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"
] | 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 |
229,604 | 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",
")",
"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",
")"
] | 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 |
229,605 | 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",
"[",
"0",
":",
"index",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Unable to parse document collection link from '",
"+",
"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 |
229,606 | 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",
"remaining",
"==",
"0",
":",
"return",
"i",
"return",
"-",
"1"
] | 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 |
229,607 | 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",
"(",
"'/'",
")",
":",
"# Returns substring starting from beginning to last but one char in the string",
"path",
"=",
"path",
"[",
":",
"-",
"1",
"]",
"return",
"path"
] | 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 |
229,608 | 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",
",",
"list",
",",
"tuple",
")",
")",
":",
"json_dumped",
"=",
"json",
".",
"dumps",
"(",
"data",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
"if",
"six",
".",
"PY2",
":",
"return",
"json_dumped",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"json_dumped",
"return",
"None"
] | 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 |
229,609 | 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",
"(",
"'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",
")"
] | 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 |
229,610 | 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",
"=",
"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",
")"
] | 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 |
229,611 | 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",
"[",
"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",
"]"
] | 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 |
229,612 | 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 |
229,613 | 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_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"
] | 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 |
229,614 | 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 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",
")"
] | 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 |
229,615 | 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_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",
"]",
")"
] | 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 |
229,616 | 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), 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"
] | 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 |
229,617 | 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_headers",
"[",
"http_constants",
".",
"HttpHeaders",
".",
"SessionToken",
"]",
"id_to_sessionlsn",
"=",
"{",
"}",
"if",
"session_token",
"is",
"not",
"''",
":",
"''' extract id, lsn from the token. For p-collection,\n 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"
] | 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 |
229,618 | 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",
"=",
"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"
] | 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 |
229,619 | 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",
"=",
"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"
] | 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 |
229,620 | 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",
".",
"vector_source",
"=",
"True",
"else",
":",
"self",
".",
"vector_source",
"=",
"False"
] | 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 |
229,621 | 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>'",
".",
"format",
"(",
"div_id",
"=",
"self",
".",
"div_id",
",",
"srcdoc",
"=",
"srcdoc",
",",
"width",
"=",
"self",
".",
"width",
",",
"height",
"=",
"self",
".",
"height",
")",
")"
] | 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 |
229,622 | 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",
"=",
"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",
"(",
")",
")"
] | 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 |
229,623 | 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",
".",
"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'",
")",
")",
")"
] | 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 |
229,624 | 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",
".",
"radius_stops",
",",
"clusterRadius",
"=",
"self",
".",
"clusterRadius",
",",
"clusterMaxZoom",
"=",
"self",
".",
"clusterMaxZoom",
",",
"strokeWidth",
"=",
"self",
".",
"stroke_width",
",",
"strokeColor",
"=",
"self",
".",
"stroke_color",
",",
"radiusDefault",
"=",
"self",
".",
"radius_default",
",",
"highlightColor",
"=",
"self",
".",
"highlight_color",
")",
")"
] | 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 |
229,625 | 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 |
229,626 | 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",
".",
"tiles_minzoom",
",",
"tiles_maxzoom",
"=",
"self",
".",
"tiles_maxzoom",
",",
"tiles_bounds",
"=",
"self",
".",
"tiles_bounds",
"if",
"self",
".",
"tiles_bounds",
"else",
"'undefined'",
")",
")"
] | 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 |
229,627 | 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",
"=",
"[",
"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",
")",
")"
] | 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 |
229,628 | 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",
"=",
"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",
"]",
"}",
")"
] | 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 |
229,629 | 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",
"(",
")",
"else",
":",
"domain",
"=",
"maxval",
"-",
"minval",
"interval",
"=",
"float",
"(",
"domain",
")",
"/",
"float",
"(",
"numStops",
")",
"for",
"i",
"in",
"range",
"(",
"numStops",
")",
":",
"scale",
".",
"append",
"(",
"round",
"(",
"minval",
"+",
"interval",
"*",
"i",
",",
"2",
")",
")",
"return",
"scale"
] | 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 |
229,630 | 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",
"=",
"[",
"]",
"for",
"i",
",",
"b",
"in",
"enumerate",
"(",
"breaks",
")",
":",
"stops",
".",
"append",
"(",
"[",
"b",
",",
"radius_breaks",
"[",
"i",
"]",
"]",
")",
"return",
"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 |
229,631 | 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",
"(",
"breaks",
")",
":",
"stops",
".",
"append",
"(",
"[",
"b",
",",
"weight_breaks",
"[",
"i",
"]",
"]",
")",
"return",
"stops"
] | 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 |
229,632 | 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",
")",
":",
"# 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"
] | 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",
".",
"colorbrewer2",
".",
"org",
"for",
"a",
"list",
"of",
"color",
"options",
"to",
"pass"
] | f6e403c13eaa910e70659c7d179e8e32ce95ae34 | https://github.com/mapbox/mapboxgl-jupyter/blob/f6e403c13eaa910e70659c7d179e8e32ce95ae34/mapboxgl/utils.py#L188-L228 |
229,633 | 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_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"
] | 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 |
229,634 | 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",
")",
":",
"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",
"{",
"}"
] | Loads YAML from docstring. | [
"Loads",
"YAML",
"from",
"docstring",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/yaml_utils.py#L32-L47 |
229,635 | 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",
"PATH_KEYS",
"or",
"key",
".",
"startswith",
"(",
"\"x-\"",
")",
"}"
] | 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 |
229,636 | 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\"",
")",
":",
"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",
")"
] | 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 |
229,637 | 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",
"(",
"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.\"",
")"
] | 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 |
229,638 | 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",
"(",
"getattr",
"(",
"Meta",
",",
"\"dump_only\"",
",",
"[",
"]",
")",
")",
"filtered_fields",
"=",
"OrderedDict",
"(",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"fields",
".",
"items",
"(",
")",
"if",
"key",
"not",
"in",
"exclude",
")",
"return",
"filtered_fields"
] | 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 |
229,639 | 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",
".",
"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",
")"
] | 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",
"is",
"already",
"in",
"the",
"spec",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/common.py#L128-L150 |
229,640 | 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",
"\"\"",
",",
"COMPONENT_SUBSECTIONS",
"[",
"openapi_major_version",
"]",
"[",
"component_type",
"]",
",",
"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",
"path",
"to",
"reference"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/utils.py#L29-L42 |
229,641 | 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",
"(",
"value",
",",
"dict",
")",
":",
"deepupdate",
"(",
"value",
",",
"update",
"[",
"key",
"]",
")",
"return",
"update"
] | 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 |
229,642 | 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\"",
",",
"None",
")",
"load_from",
"=",
"getattr",
"(",
"field",
",",
"\"load_from\"",
",",
"None",
")",
"return",
"dump_to",
"or",
"load_from",
"or",
"name",
"return",
"field",
".",
"data_key",
"or",
"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 | [
"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 |
229,643 | 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",
"[",
"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"
] | 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 |
229,644 | 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",
"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"
] | 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 |
229,645 | 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",
":",
"default",
"=",
"field",
".",
"missing",
"if",
"default",
"is",
"not",
"marshmallow",
".",
"missing",
"and",
"not",
"callable",
"(",
"default",
")",
":",
"ret",
"[",
"\"default\"",
"]",
"=",
"default",
"return",
"ret"
] | 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 |
229,646 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2choices | def field2choices(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
comparable = [
validator.comparable
for validator in field.validators
if hasattr(validator, "comparable")
]
if comparable:
attributes["enum"] = comparable
else:
choices = [
OrderedSet(validator.choices)
for validator in field.validators
if hasattr(validator, "choices")
]
if choices:
attributes["enum"] = list(functools.reduce(operator.and_, choices))
return attributes | python | def field2choices(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
comparable = [
validator.comparable
for validator in field.validators
if hasattr(validator, "comparable")
]
if comparable:
attributes["enum"] = comparable
else:
choices = [
OrderedSet(validator.choices)
for validator in field.validators
if hasattr(validator, "choices")
]
if choices:
attributes["enum"] = list(functools.reduce(operator.and_, choices))
return attributes | [
"def",
"field2choices",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"comparable",
"=",
"[",
"validator",
".",
"comparable",
"for",
"validator",
"in",
"field",
".",
"validators",
"if",
"hasattr",
"(",
"validator",
",",
"\"comparable\"",
")",
"]",
"if",
"comparable",
":",
"attributes",
"[",
"\"enum\"",
"]",
"=",
"comparable",
"else",
":",
"choices",
"=",
"[",
"OrderedSet",
"(",
"validator",
".",
"choices",
")",
"for",
"validator",
"in",
"field",
".",
"validators",
"if",
"hasattr",
"(",
"validator",
",",
"\"choices\"",
")",
"]",
"if",
"choices",
":",
"attributes",
"[",
"\"enum\"",
"]",
"=",
"list",
"(",
"functools",
".",
"reduce",
"(",
"operator",
".",
"and_",
",",
"choices",
")",
")",
"return",
"attributes"
] | Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"valid",
"choices",
"definition"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L208-L232 |
229,647 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2read_only | def field2read_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.dump_only:
attributes["readOnly"] = True
return attributes | python | def field2read_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.dump_only:
attributes["readOnly"] = True
return attributes | [
"def",
"field2read_only",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"if",
"field",
".",
"dump_only",
":",
"attributes",
"[",
"\"readOnly\"",
"]",
"=",
"True",
"return",
"attributes"
] | Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"a",
"dump_only",
"field",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L234-L243 |
229,648 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2write_only | def field2write_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a load_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.load_only and self.openapi_version.major >= 3:
attributes["writeOnly"] = True
return attributes | python | def field2write_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a load_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.load_only and self.openapi_version.major >= 3:
attributes["writeOnly"] = True
return attributes | [
"def",
"field2write_only",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"if",
"field",
".",
"load_only",
"and",
"self",
".",
"openapi_version",
".",
"major",
">=",
"3",
":",
"attributes",
"[",
"\"writeOnly\"",
"]",
"=",
"True",
"return",
"attributes"
] | Return the dictionary of OpenAPI field attributes for a load_only field.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"a",
"load_only",
"field",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L245-L254 |
229,649 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2nullable | def field2nullable(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a nullable field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.allow_none:
attributes[
"x-nullable" if self.openapi_version.major < 3 else "nullable"
] = True
return attributes | python | def field2nullable(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a nullable field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.allow_none:
attributes[
"x-nullable" if self.openapi_version.major < 3 else "nullable"
] = True
return attributes | [
"def",
"field2nullable",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"if",
"field",
".",
"allow_none",
":",
"attributes",
"[",
"\"x-nullable\"",
"if",
"self",
".",
"openapi_version",
".",
"major",
"<",
"3",
"else",
"\"nullable\"",
"]",
"=",
"True",
"return",
"attributes"
] | Return the dictionary of OpenAPI field attributes for a nullable field.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"a",
"nullable",
"field",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L256-L267 |
229,650 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.metadata2properties | def metadata2properties(self, field):
"""Return a dictionary of properties extracted from field Metadata
Will include field metadata that are valid properties of `OpenAPI schema
objects
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_
(e.g. “description”, “enum”, “example”).
In addition, `specification extensions
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions>`_
are supported. Prefix `x_` to the desired extension when passing the
keyword argument to the field constructor. apispec will convert `x_` to
`x-` to comply with OpenAPI.
:param Field field: A marshmallow field.
:rtype: dict
"""
# Dasherize metadata that starts with x_
metadata = {
key.replace("_", "-") if key.startswith("x_") else key: value
for key, value in iteritems(field.metadata)
}
# Avoid validation error with "Additional properties not allowed"
ret = {
key: value
for key, value in metadata.items()
if key in _VALID_PROPERTIES or key.startswith(_VALID_PREFIX)
}
return ret | python | def metadata2properties(self, field):
"""Return a dictionary of properties extracted from field Metadata
Will include field metadata that are valid properties of `OpenAPI schema
objects
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_
(e.g. “description”, “enum”, “example”).
In addition, `specification extensions
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions>`_
are supported. Prefix `x_` to the desired extension when passing the
keyword argument to the field constructor. apispec will convert `x_` to
`x-` to comply with OpenAPI.
:param Field field: A marshmallow field.
:rtype: dict
"""
# Dasherize metadata that starts with x_
metadata = {
key.replace("_", "-") if key.startswith("x_") else key: value
for key, value in iteritems(field.metadata)
}
# Avoid validation error with "Additional properties not allowed"
ret = {
key: value
for key, value in metadata.items()
if key in _VALID_PROPERTIES or key.startswith(_VALID_PREFIX)
}
return ret | [
"def",
"metadata2properties",
"(",
"self",
",",
"field",
")",
":",
"# Dasherize metadata that starts with x_",
"metadata",
"=",
"{",
"key",
".",
"replace",
"(",
"\"_\"",
",",
"\"-\"",
")",
"if",
"key",
".",
"startswith",
"(",
"\"x_\"",
")",
"else",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"field",
".",
"metadata",
")",
"}",
"# Avoid validation error with \"Additional properties not allowed\"",
"ret",
"=",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"metadata",
".",
"items",
"(",
")",
"if",
"key",
"in",
"_VALID_PROPERTIES",
"or",
"key",
".",
"startswith",
"(",
"_VALID_PREFIX",
")",
"}",
"return",
"ret"
] | Return a dictionary of properties extracted from field Metadata
Will include field metadata that are valid properties of `OpenAPI schema
objects
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_
(e.g. “description”, “enum”, “example”).
In addition, `specification extensions
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions>`_
are supported. Prefix `x_` to the desired extension when passing the
keyword argument to the field constructor. apispec will convert `x_` to
`x-` to comply with OpenAPI.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"a",
"dictionary",
"of",
"properties",
"extracted",
"from",
"field",
"Metadata"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L367-L396 |
229,651 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.resolve_nested_schema | def resolve_nested_schema(self, schema):
"""Return the Open API representation of a marshmallow Schema.
Adds the schema to the spec if it isn't already present.
Typically will return a dictionary with the reference to the schema's
path in the spec unless the `schema_name_resolver` returns `None`, in
which case the returned dictoinary will contain a JSON Schema Object
representation of the schema.
:param schema: schema to add to the spec
"""
schema_instance = resolve_schema_instance(schema)
schema_key = make_schema_key(schema_instance)
if schema_key not in self.refs:
schema_cls = self.resolve_schema_class(schema)
name = self.schema_name_resolver(schema_cls)
if not name:
try:
json_schema = self.schema2jsonschema(schema)
except RuntimeError:
raise APISpecError(
"Name resolver returned None for schema {schema} which is "
"part of a chain of circular referencing schemas. Please"
" ensure that the schema_name_resolver passed to"
" MarshmallowPlugin returns a string for all circular"
" referencing schemas.".format(schema=schema)
)
if getattr(schema, "many", False):
return {"type": "array", "items": json_schema}
return json_schema
name = get_unique_schema_name(self.spec.components, name)
self.spec.components.schema(name, schema=schema)
return self.get_ref_dict(schema_instance) | python | def resolve_nested_schema(self, schema):
"""Return the Open API representation of a marshmallow Schema.
Adds the schema to the spec if it isn't already present.
Typically will return a dictionary with the reference to the schema's
path in the spec unless the `schema_name_resolver` returns `None`, in
which case the returned dictoinary will contain a JSON Schema Object
representation of the schema.
:param schema: schema to add to the spec
"""
schema_instance = resolve_schema_instance(schema)
schema_key = make_schema_key(schema_instance)
if schema_key not in self.refs:
schema_cls = self.resolve_schema_class(schema)
name = self.schema_name_resolver(schema_cls)
if not name:
try:
json_schema = self.schema2jsonschema(schema)
except RuntimeError:
raise APISpecError(
"Name resolver returned None for schema {schema} which is "
"part of a chain of circular referencing schemas. Please"
" ensure that the schema_name_resolver passed to"
" MarshmallowPlugin returns a string for all circular"
" referencing schemas.".format(schema=schema)
)
if getattr(schema, "many", False):
return {"type": "array", "items": json_schema}
return json_schema
name = get_unique_schema_name(self.spec.components, name)
self.spec.components.schema(name, schema=schema)
return self.get_ref_dict(schema_instance) | [
"def",
"resolve_nested_schema",
"(",
"self",
",",
"schema",
")",
":",
"schema_instance",
"=",
"resolve_schema_instance",
"(",
"schema",
")",
"schema_key",
"=",
"make_schema_key",
"(",
"schema_instance",
")",
"if",
"schema_key",
"not",
"in",
"self",
".",
"refs",
":",
"schema_cls",
"=",
"self",
".",
"resolve_schema_class",
"(",
"schema",
")",
"name",
"=",
"self",
".",
"schema_name_resolver",
"(",
"schema_cls",
")",
"if",
"not",
"name",
":",
"try",
":",
"json_schema",
"=",
"self",
".",
"schema2jsonschema",
"(",
"schema",
")",
"except",
"RuntimeError",
":",
"raise",
"APISpecError",
"(",
"\"Name resolver returned None for schema {schema} which is \"",
"\"part of a chain of circular referencing schemas. Please\"",
"\" ensure that the schema_name_resolver passed to\"",
"\" MarshmallowPlugin returns a string for all circular\"",
"\" referencing schemas.\"",
".",
"format",
"(",
"schema",
"=",
"schema",
")",
")",
"if",
"getattr",
"(",
"schema",
",",
"\"many\"",
",",
"False",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"array\"",
",",
"\"items\"",
":",
"json_schema",
"}",
"return",
"json_schema",
"name",
"=",
"get_unique_schema_name",
"(",
"self",
".",
"spec",
".",
"components",
",",
"name",
")",
"self",
".",
"spec",
".",
"components",
".",
"schema",
"(",
"name",
",",
"schema",
"=",
"schema",
")",
"return",
"self",
".",
"get_ref_dict",
"(",
"schema_instance",
")"
] | Return the Open API representation of a marshmallow Schema.
Adds the schema to the spec if it isn't already present.
Typically will return a dictionary with the reference to the schema's
path in the spec unless the `schema_name_resolver` returns `None`, in
which case the returned dictoinary will contain a JSON Schema Object
representation of the schema.
:param schema: schema to add to the spec | [
"Return",
"the",
"Open",
"API",
"representation",
"of",
"a",
"marshmallow",
"Schema",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L444-L477 |
229,652 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.property2parameter | def property2parameter(
self,
prop,
name="body",
required=False,
multiple=False,
location=None,
default_in="body",
):
"""Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object
"""
openapi_default_in = __location_map__.get(default_in, default_in)
openapi_location = __location_map__.get(location, openapi_default_in)
ret = {"in": openapi_location, "name": name}
if openapi_location == "body":
ret["required"] = False
ret["name"] = "body"
ret["schema"] = {
"type": "object",
"properties": {name: prop} if name else {},
}
if name and required:
ret["schema"]["required"] = [name]
else:
ret["required"] = required
if self.openapi_version.major < 3:
if multiple:
ret["collectionFormat"] = "multi"
ret.update(prop)
else:
if multiple:
ret["explode"] = True
ret["style"] = "form"
if prop.get("description", None):
ret["description"] = prop.pop("description")
ret["schema"] = prop
return ret | python | def property2parameter(
self,
prop,
name="body",
required=False,
multiple=False,
location=None,
default_in="body",
):
"""Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object
"""
openapi_default_in = __location_map__.get(default_in, default_in)
openapi_location = __location_map__.get(location, openapi_default_in)
ret = {"in": openapi_location, "name": name}
if openapi_location == "body":
ret["required"] = False
ret["name"] = "body"
ret["schema"] = {
"type": "object",
"properties": {name: prop} if name else {},
}
if name and required:
ret["schema"]["required"] = [name]
else:
ret["required"] = required
if self.openapi_version.major < 3:
if multiple:
ret["collectionFormat"] = "multi"
ret.update(prop)
else:
if multiple:
ret["explode"] = True
ret["style"] = "form"
if prop.get("description", None):
ret["description"] = prop.pop("description")
ret["schema"] = prop
return ret | [
"def",
"property2parameter",
"(",
"self",
",",
"prop",
",",
"name",
"=",
"\"body\"",
",",
"required",
"=",
"False",
",",
"multiple",
"=",
"False",
",",
"location",
"=",
"None",
",",
"default_in",
"=",
"\"body\"",
",",
")",
":",
"openapi_default_in",
"=",
"__location_map__",
".",
"get",
"(",
"default_in",
",",
"default_in",
")",
"openapi_location",
"=",
"__location_map__",
".",
"get",
"(",
"location",
",",
"openapi_default_in",
")",
"ret",
"=",
"{",
"\"in\"",
":",
"openapi_location",
",",
"\"name\"",
":",
"name",
"}",
"if",
"openapi_location",
"==",
"\"body\"",
":",
"ret",
"[",
"\"required\"",
"]",
"=",
"False",
"ret",
"[",
"\"name\"",
"]",
"=",
"\"body\"",
"ret",
"[",
"\"schema\"",
"]",
"=",
"{",
"\"type\"",
":",
"\"object\"",
",",
"\"properties\"",
":",
"{",
"name",
":",
"prop",
"}",
"if",
"name",
"else",
"{",
"}",
",",
"}",
"if",
"name",
"and",
"required",
":",
"ret",
"[",
"\"schema\"",
"]",
"[",
"\"required\"",
"]",
"=",
"[",
"name",
"]",
"else",
":",
"ret",
"[",
"\"required\"",
"]",
"=",
"required",
"if",
"self",
".",
"openapi_version",
".",
"major",
"<",
"3",
":",
"if",
"multiple",
":",
"ret",
"[",
"\"collectionFormat\"",
"]",
"=",
"\"multi\"",
"ret",
".",
"update",
"(",
"prop",
")",
"else",
":",
"if",
"multiple",
":",
"ret",
"[",
"\"explode\"",
"]",
"=",
"True",
"ret",
"[",
"\"style\"",
"]",
"=",
"\"form\"",
"if",
"prop",
".",
"get",
"(",
"\"description\"",
",",
"None",
")",
":",
"ret",
"[",
"\"description\"",
"]",
"=",
"prop",
".",
"pop",
"(",
"\"description\"",
")",
"ret",
"[",
"\"schema\"",
"]",
"=",
"prop",
"return",
"ret"
] | Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object | [
"Return",
"the",
"Parameter",
"Object",
"definition",
"for",
"a",
"JSON",
"Schema",
"property",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L571-L619 |
229,653 | marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.get_ref_dict | def get_ref_dict(self, schema):
"""Method to create a dictionary containing a JSON reference to the
schema in the spec
"""
schema_key = make_schema_key(schema)
ref_schema = build_reference(
"schema", self.openapi_version.major, self.refs[schema_key]
)
if getattr(schema, "many", False):
return {"type": "array", "items": ref_schema}
return ref_schema | python | def get_ref_dict(self, schema):
"""Method to create a dictionary containing a JSON reference to the
schema in the spec
"""
schema_key = make_schema_key(schema)
ref_schema = build_reference(
"schema", self.openapi_version.major, self.refs[schema_key]
)
if getattr(schema, "many", False):
return {"type": "array", "items": ref_schema}
return ref_schema | [
"def",
"get_ref_dict",
"(",
"self",
",",
"schema",
")",
":",
"schema_key",
"=",
"make_schema_key",
"(",
"schema",
")",
"ref_schema",
"=",
"build_reference",
"(",
"\"schema\"",
",",
"self",
".",
"openapi_version",
".",
"major",
",",
"self",
".",
"refs",
"[",
"schema_key",
"]",
")",
"if",
"getattr",
"(",
"schema",
",",
"\"many\"",
",",
"False",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"array\"",
",",
"\"items\"",
":",
"ref_schema",
"}",
"return",
"ref_schema"
] | Method to create a dictionary containing a JSON reference to the
schema in the spec | [
"Method",
"to",
"create",
"a",
"dictionary",
"containing",
"a",
"JSON",
"reference",
"to",
"the",
"schema",
"in",
"the",
"spec"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L696-L706 |
229,654 | marshmallow-code/apispec | src/apispec/core.py | clean_operations | def clean_operations(operations, openapi_major_version):
"""Ensure that all parameters with "in" equal to "path" are also required
as required by the OpenAPI specification, as well as normalizing any
references to global parameters. Also checks for invalid HTTP methods.
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject.
:param dict operations: Dict mapping status codes to operations
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3.
"""
invalid = {
key
for key in set(iterkeys(operations)) - set(VALID_METHODS[openapi_major_version])
if not key.startswith("x-")
}
if invalid:
raise APISpecError(
"One or more HTTP methods are invalid: {}".format(", ".join(invalid))
)
def get_ref(obj_type, obj, openapi_major_version):
"""Return object or rererence
If obj is a dict, it is assumed to be a complete description and it is returned as is.
Otherwise, it is assumed to be a reference name as string and the corresponding $ref
string is returned.
:param str obj_type: "parameter" or "response"
:param dict|str obj: parameter or response in dict form or as ref_id string
:param int openapi_major_version: The major version of the OpenAPI standard
"""
if isinstance(obj, dict):
return obj
return build_reference(obj_type, openapi_major_version, obj)
for operation in (operations or {}).values():
if "parameters" in operation:
parameters = operation["parameters"]
for parameter in parameters:
if (
isinstance(parameter, dict)
and "in" in parameter
and parameter["in"] == "path"
):
parameter["required"] = True
operation["parameters"] = [
get_ref("parameter", p, openapi_major_version) for p in parameters
]
if "responses" in operation:
responses = OrderedDict()
for code, response in iteritems(operation["responses"]):
try:
code = int(code) # handles IntEnums like http.HTTPStatus
except (TypeError, ValueError):
if openapi_major_version < 3:
warnings.warn("Non-integer code not allowed in OpenAPI < 3")
responses[str(code)] = get_ref(
"response", response, openapi_major_version
)
operation["responses"] = responses | python | def clean_operations(operations, openapi_major_version):
"""Ensure that all parameters with "in" equal to "path" are also required
as required by the OpenAPI specification, as well as normalizing any
references to global parameters. Also checks for invalid HTTP methods.
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject.
:param dict operations: Dict mapping status codes to operations
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3.
"""
invalid = {
key
for key in set(iterkeys(operations)) - set(VALID_METHODS[openapi_major_version])
if not key.startswith("x-")
}
if invalid:
raise APISpecError(
"One or more HTTP methods are invalid: {}".format(", ".join(invalid))
)
def get_ref(obj_type, obj, openapi_major_version):
"""Return object or rererence
If obj is a dict, it is assumed to be a complete description and it is returned as is.
Otherwise, it is assumed to be a reference name as string and the corresponding $ref
string is returned.
:param str obj_type: "parameter" or "response"
:param dict|str obj: parameter or response in dict form or as ref_id string
:param int openapi_major_version: The major version of the OpenAPI standard
"""
if isinstance(obj, dict):
return obj
return build_reference(obj_type, openapi_major_version, obj)
for operation in (operations or {}).values():
if "parameters" in operation:
parameters = operation["parameters"]
for parameter in parameters:
if (
isinstance(parameter, dict)
and "in" in parameter
and parameter["in"] == "path"
):
parameter["required"] = True
operation["parameters"] = [
get_ref("parameter", p, openapi_major_version) for p in parameters
]
if "responses" in operation:
responses = OrderedDict()
for code, response in iteritems(operation["responses"]):
try:
code = int(code) # handles IntEnums like http.HTTPStatus
except (TypeError, ValueError):
if openapi_major_version < 3:
warnings.warn("Non-integer code not allowed in OpenAPI < 3")
responses[str(code)] = get_ref(
"response", response, openapi_major_version
)
operation["responses"] = responses | [
"def",
"clean_operations",
"(",
"operations",
",",
"openapi_major_version",
")",
":",
"invalid",
"=",
"{",
"key",
"for",
"key",
"in",
"set",
"(",
"iterkeys",
"(",
"operations",
")",
")",
"-",
"set",
"(",
"VALID_METHODS",
"[",
"openapi_major_version",
"]",
")",
"if",
"not",
"key",
".",
"startswith",
"(",
"\"x-\"",
")",
"}",
"if",
"invalid",
":",
"raise",
"APISpecError",
"(",
"\"One or more HTTP methods are invalid: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"invalid",
")",
")",
")",
"def",
"get_ref",
"(",
"obj_type",
",",
"obj",
",",
"openapi_major_version",
")",
":",
"\"\"\"Return object or rererence\n\n If obj is a dict, it is assumed to be a complete description and it is returned as is.\n Otherwise, it is assumed to be a reference name as string and the corresponding $ref\n string is returned.\n\n :param str obj_type: \"parameter\" or \"response\"\n :param dict|str obj: parameter or response in dict form or as ref_id string\n :param int openapi_major_version: The major version of the OpenAPI standard\n \"\"\"",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"obj",
"return",
"build_reference",
"(",
"obj_type",
",",
"openapi_major_version",
",",
"obj",
")",
"for",
"operation",
"in",
"(",
"operations",
"or",
"{",
"}",
")",
".",
"values",
"(",
")",
":",
"if",
"\"parameters\"",
"in",
"operation",
":",
"parameters",
"=",
"operation",
"[",
"\"parameters\"",
"]",
"for",
"parameter",
"in",
"parameters",
":",
"if",
"(",
"isinstance",
"(",
"parameter",
",",
"dict",
")",
"and",
"\"in\"",
"in",
"parameter",
"and",
"parameter",
"[",
"\"in\"",
"]",
"==",
"\"path\"",
")",
":",
"parameter",
"[",
"\"required\"",
"]",
"=",
"True",
"operation",
"[",
"\"parameters\"",
"]",
"=",
"[",
"get_ref",
"(",
"\"parameter\"",
",",
"p",
",",
"openapi_major_version",
")",
"for",
"p",
"in",
"parameters",
"]",
"if",
"\"responses\"",
"in",
"operation",
":",
"responses",
"=",
"OrderedDict",
"(",
")",
"for",
"code",
",",
"response",
"in",
"iteritems",
"(",
"operation",
"[",
"\"responses\"",
"]",
")",
":",
"try",
":",
"code",
"=",
"int",
"(",
"code",
")",
"# handles IntEnums like http.HTTPStatus",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"if",
"openapi_major_version",
"<",
"3",
":",
"warnings",
".",
"warn",
"(",
"\"Non-integer code not allowed in OpenAPI < 3\"",
")",
"responses",
"[",
"str",
"(",
"code",
")",
"]",
"=",
"get_ref",
"(",
"\"response\"",
",",
"response",
",",
"openapi_major_version",
")",
"operation",
"[",
"\"responses\"",
"]",
"=",
"responses"
] | Ensure that all parameters with "in" equal to "path" are also required
as required by the OpenAPI specification, as well as normalizing any
references to global parameters. Also checks for invalid HTTP methods.
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject.
:param dict operations: Dict mapping status codes to operations
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3. | [
"Ensure",
"that",
"all",
"parameters",
"with",
"in",
"equal",
"to",
"path",
"are",
"also",
"required",
"as",
"required",
"by",
"the",
"OpenAPI",
"specification",
"as",
"well",
"as",
"normalizing",
"any",
"references",
"to",
"global",
"parameters",
".",
"Also",
"checks",
"for",
"invalid",
"HTTP",
"methods",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L21-L82 |
229,655 | marshmallow-code/apispec | src/apispec/core.py | Components.schema | def schema(self, name, component=None, **kwargs):
"""Add a new schema to the spec.
:param str name: identifier by which schema may be referenced.
:param dict component: schema definition.
.. note::
If you are using `apispec.ext.marshmallow`, you can pass fields' metadata as
additional keyword arguments.
For example, to add ``enum`` and ``description`` to your field: ::
status = fields.String(
required=True,
enum=['open', 'closed'],
description='Status (open or closed)',
)
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject
"""
if name in self._schemas:
raise DuplicateComponentNameError(
'Another schema with name "{}" is already registered.'.format(name)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.schema_helper(name, component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._schemas[name] = ret
return self | python | def schema(self, name, component=None, **kwargs):
"""Add a new schema to the spec.
:param str name: identifier by which schema may be referenced.
:param dict component: schema definition.
.. note::
If you are using `apispec.ext.marshmallow`, you can pass fields' metadata as
additional keyword arguments.
For example, to add ``enum`` and ``description`` to your field: ::
status = fields.String(
required=True,
enum=['open', 'closed'],
description='Status (open or closed)',
)
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject
"""
if name in self._schemas:
raise DuplicateComponentNameError(
'Another schema with name "{}" is already registered.'.format(name)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.schema_helper(name, component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._schemas[name] = ret
return self | [
"def",
"schema",
"(",
"self",
",",
"name",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"in",
"self",
".",
"_schemas",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another schema with name \"{}\" is already registered.'",
".",
"format",
"(",
"name",
")",
")",
"component",
"=",
"component",
"or",
"{",
"}",
"ret",
"=",
"component",
".",
"copy",
"(",
")",
"# Execute all helpers from plugins",
"for",
"plugin",
"in",
"self",
".",
"_plugins",
":",
"try",
":",
"ret",
".",
"update",
"(",
"plugin",
".",
"schema_helper",
"(",
"name",
",",
"component",
",",
"*",
"*",
"kwargs",
")",
"or",
"{",
"}",
")",
"except",
"PluginMethodNotImplementedError",
":",
"continue",
"self",
".",
"_schemas",
"[",
"name",
"]",
"=",
"ret",
"return",
"self"
] | Add a new schema to the spec.
:param str name: identifier by which schema may be referenced.
:param dict component: schema definition.
.. note::
If you are using `apispec.ext.marshmallow`, you can pass fields' metadata as
additional keyword arguments.
For example, to add ``enum`` and ``description`` to your field: ::
status = fields.String(
required=True,
enum=['open', 'closed'],
description='Status (open or closed)',
)
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject | [
"Add",
"a",
"new",
"schema",
"to",
"the",
"spec",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L113-L147 |
229,656 | marshmallow-code/apispec | src/apispec/core.py | Components.parameter | def parameter(self, component_id, location, component=None, **kwargs):
""" Add a parameter which can be referenced.
:param str param_id: identifier by which parameter may be referenced.
:param str location: location of the parameter.
:param dict component: parameter fields.
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._parameters:
raise DuplicateComponentNameError(
'Another parameter with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
ret.setdefault("name", component_id)
ret["in"] = location
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.parameter_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._parameters[component_id] = ret
return self | python | def parameter(self, component_id, location, component=None, **kwargs):
""" Add a parameter which can be referenced.
:param str param_id: identifier by which parameter may be referenced.
:param str location: location of the parameter.
:param dict component: parameter fields.
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._parameters:
raise DuplicateComponentNameError(
'Another parameter with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
ret.setdefault("name", component_id)
ret["in"] = location
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.parameter_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._parameters[component_id] = ret
return self | [
"def",
"parameter",
"(",
"self",
",",
"component_id",
",",
"location",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"component_id",
"in",
"self",
".",
"_parameters",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another parameter with name \"{}\" is already registered.'",
".",
"format",
"(",
"component_id",
")",
")",
"component",
"=",
"component",
"or",
"{",
"}",
"ret",
"=",
"component",
".",
"copy",
"(",
")",
"ret",
".",
"setdefault",
"(",
"\"name\"",
",",
"component_id",
")",
"ret",
"[",
"\"in\"",
"]",
"=",
"location",
"# Execute all helpers from plugins",
"for",
"plugin",
"in",
"self",
".",
"_plugins",
":",
"try",
":",
"ret",
".",
"update",
"(",
"plugin",
".",
"parameter_helper",
"(",
"component",
",",
"*",
"*",
"kwargs",
")",
"or",
"{",
"}",
")",
"except",
"PluginMethodNotImplementedError",
":",
"continue",
"self",
".",
"_parameters",
"[",
"component_id",
"]",
"=",
"ret",
"return",
"self"
] | Add a parameter which can be referenced.
:param str param_id: identifier by which parameter may be referenced.
:param str location: location of the parameter.
:param dict component: parameter fields.
:param dict kwargs: plugin-specific arguments | [
"Add",
"a",
"parameter",
"which",
"can",
"be",
"referenced",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L149-L174 |
229,657 | marshmallow-code/apispec | src/apispec/core.py | Components.response | def response(self, component_id, component=None, **kwargs):
"""Add a response which can be referenced.
:param str component_id: ref_id to use as reference
:param dict component: response fields
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._responses:
raise DuplicateComponentNameError(
'Another response with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.response_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._responses[component_id] = ret
return self | python | def response(self, component_id, component=None, **kwargs):
"""Add a response which can be referenced.
:param str component_id: ref_id to use as reference
:param dict component: response fields
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._responses:
raise DuplicateComponentNameError(
'Another response with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.response_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._responses[component_id] = ret
return self | [
"def",
"response",
"(",
"self",
",",
"component_id",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"component_id",
"in",
"self",
".",
"_responses",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another response with name \"{}\" is already registered.'",
".",
"format",
"(",
"component_id",
")",
")",
"component",
"=",
"component",
"or",
"{",
"}",
"ret",
"=",
"component",
".",
"copy",
"(",
")",
"# Execute all helpers from plugins",
"for",
"plugin",
"in",
"self",
".",
"_plugins",
":",
"try",
":",
"ret",
".",
"update",
"(",
"plugin",
".",
"response_helper",
"(",
"component",
",",
"*",
"*",
"kwargs",
")",
"or",
"{",
"}",
")",
"except",
"PluginMethodNotImplementedError",
":",
"continue",
"self",
".",
"_responses",
"[",
"component_id",
"]",
"=",
"ret",
"return",
"self"
] | Add a response which can be referenced.
:param str component_id: ref_id to use as reference
:param dict component: response fields
:param dict kwargs: plugin-specific arguments | [
"Add",
"a",
"response",
"which",
"can",
"be",
"referenced",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L176-L198 |
229,658 | marshmallow-code/apispec | src/apispec/core.py | Components.security_scheme | def security_scheme(self, component_id, component):
"""Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields
"""
if component_id in self._security_schemes:
raise DuplicateComponentNameError(
'Another security scheme with name "{}" is already registered.'.format(
component_id
)
)
self._security_schemes[component_id] = component
return self | python | def security_scheme(self, component_id, component):
"""Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields
"""
if component_id in self._security_schemes:
raise DuplicateComponentNameError(
'Another security scheme with name "{}" is already registered.'.format(
component_id
)
)
self._security_schemes[component_id] = component
return self | [
"def",
"security_scheme",
"(",
"self",
",",
"component_id",
",",
"component",
")",
":",
"if",
"component_id",
"in",
"self",
".",
"_security_schemes",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another security scheme with name \"{}\" is already registered.'",
".",
"format",
"(",
"component_id",
")",
")",
"self",
".",
"_security_schemes",
"[",
"component_id",
"]",
"=",
"component",
"return",
"self"
] | Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields | [
"Add",
"a",
"security",
"scheme",
"which",
"can",
"be",
"referenced",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L200-L213 |
229,659 | marshmallow-code/apispec | src/apispec/core.py | APISpec.path | def path(
self, path=None, operations=None, summary=None, description=None, **kwargs
):
"""Add a new path object to the spec.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object
:param str|None path: URL path component
:param dict|None operations: describes the http methods and options for `path`
:param str summary: short summary relevant to all operations in this path
:param str description: long description relevant to all operations in this path
:param dict kwargs: parameters used by any path helpers see :meth:`register_path_helper`
"""
operations = operations or OrderedDict()
# Execute path helpers
for plugin in self.plugins:
try:
ret = plugin.path_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
if ret is not None:
path = ret
if not path:
raise APISpecError("Path template is not specified.")
# Execute operation helpers
for plugin in self.plugins:
try:
plugin.operation_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
clean_operations(operations, self.openapi_version.major)
self._paths.setdefault(path, operations).update(operations)
if summary is not None:
self._paths[path]["summary"] = summary
if description is not None:
self._paths[path]["description"] = description
return self | python | def path(
self, path=None, operations=None, summary=None, description=None, **kwargs
):
"""Add a new path object to the spec.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object
:param str|None path: URL path component
:param dict|None operations: describes the http methods and options for `path`
:param str summary: short summary relevant to all operations in this path
:param str description: long description relevant to all operations in this path
:param dict kwargs: parameters used by any path helpers see :meth:`register_path_helper`
"""
operations = operations or OrderedDict()
# Execute path helpers
for plugin in self.plugins:
try:
ret = plugin.path_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
if ret is not None:
path = ret
if not path:
raise APISpecError("Path template is not specified.")
# Execute operation helpers
for plugin in self.plugins:
try:
plugin.operation_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
clean_operations(operations, self.openapi_version.major)
self._paths.setdefault(path, operations).update(operations)
if summary is not None:
self._paths[path]["summary"] = summary
if description is not None:
self._paths[path]["description"] = description
return self | [
"def",
"path",
"(",
"self",
",",
"path",
"=",
"None",
",",
"operations",
"=",
"None",
",",
"summary",
"=",
"None",
",",
"description",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"operations",
"=",
"operations",
"or",
"OrderedDict",
"(",
")",
"# Execute path helpers",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"try",
":",
"ret",
"=",
"plugin",
".",
"path_helper",
"(",
"path",
"=",
"path",
",",
"operations",
"=",
"operations",
",",
"*",
"*",
"kwargs",
")",
"except",
"PluginMethodNotImplementedError",
":",
"continue",
"if",
"ret",
"is",
"not",
"None",
":",
"path",
"=",
"ret",
"if",
"not",
"path",
":",
"raise",
"APISpecError",
"(",
"\"Path template is not specified.\"",
")",
"# Execute operation helpers",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"try",
":",
"plugin",
".",
"operation_helper",
"(",
"path",
"=",
"path",
",",
"operations",
"=",
"operations",
",",
"*",
"*",
"kwargs",
")",
"except",
"PluginMethodNotImplementedError",
":",
"continue",
"clean_operations",
"(",
"operations",
",",
"self",
".",
"openapi_version",
".",
"major",
")",
"self",
".",
"_paths",
".",
"setdefault",
"(",
"path",
",",
"operations",
")",
".",
"update",
"(",
"operations",
")",
"if",
"summary",
"is",
"not",
"None",
":",
"self",
".",
"_paths",
"[",
"path",
"]",
"[",
"\"summary\"",
"]",
"=",
"summary",
"if",
"description",
"is",
"not",
"None",
":",
"self",
".",
"_paths",
"[",
"path",
"]",
"[",
"\"description\"",
"]",
"=",
"description",
"return",
"self"
] | Add a new path object to the spec.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object
:param str|None path: URL path component
:param dict|None operations: describes the http methods and options for `path`
:param str summary: short summary relevant to all operations in this path
:param str description: long description relevant to all operations in this path
:param dict kwargs: parameters used by any path helpers see :meth:`register_path_helper` | [
"Add",
"a",
"new",
"path",
"object",
"to",
"the",
"spec",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L279-L319 |
229,660 | marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | resolver | def resolver(schema):
"""Default implementation of a schema name resolver function
"""
name = schema.__name__
if name.endswith("Schema"):
return name[:-6] or name
return name | python | def resolver(schema):
"""Default implementation of a schema name resolver function
"""
name = schema.__name__
if name.endswith("Schema"):
return name[:-6] or name
return name | [
"def",
"resolver",
"(",
"schema",
")",
":",
"name",
"=",
"schema",
".",
"__name__",
"if",
"name",
".",
"endswith",
"(",
"\"Schema\"",
")",
":",
"return",
"name",
"[",
":",
"-",
"6",
"]",
"or",
"name",
"return",
"name"
] | Default implementation of a schema name resolver function | [
"Default",
"implementation",
"of",
"a",
"schema",
"name",
"resolver",
"function"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L43-L49 |
229,661 | marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | MarshmallowPlugin.resolve_schema_in_request_body | def resolve_schema_in_request_body(self, request_body):
"""Function to resolve a schema in a requestBody object - modifies then
response dict to convert Marshmallow Schema object or class into dict
"""
content = request_body["content"]
for content_type in content:
schema = content[content_type]["schema"]
content[content_type]["schema"] = self.openapi.resolve_schema_dict(schema) | python | def resolve_schema_in_request_body(self, request_body):
"""Function to resolve a schema in a requestBody object - modifies then
response dict to convert Marshmallow Schema object or class into dict
"""
content = request_body["content"]
for content_type in content:
schema = content[content_type]["schema"]
content[content_type]["schema"] = self.openapi.resolve_schema_dict(schema) | [
"def",
"resolve_schema_in_request_body",
"(",
"self",
",",
"request_body",
")",
":",
"content",
"=",
"request_body",
"[",
"\"content\"",
"]",
"for",
"content_type",
"in",
"content",
":",
"schema",
"=",
"content",
"[",
"content_type",
"]",
"[",
"\"schema\"",
"]",
"content",
"[",
"content_type",
"]",
"[",
"\"schema\"",
"]",
"=",
"self",
".",
"openapi",
".",
"resolve_schema_dict",
"(",
"schema",
")"
] | Function to resolve a schema in a requestBody object - modifies then
response dict to convert Marshmallow Schema object or class into dict | [
"Function",
"to",
"resolve",
"a",
"schema",
"in",
"a",
"requestBody",
"object",
"-",
"modifies",
"then",
"response",
"dict",
"to",
"convert",
"Marshmallow",
"Schema",
"object",
"or",
"class",
"into",
"dict"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L100-L107 |
229,662 | marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | MarshmallowPlugin.resolve_schema | def resolve_schema(self, data):
"""Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dictionary that may
contain a schema, or a reference provided as string
"""
if not isinstance(data, dict):
return
# OAS 2 component or OAS 3 header
if "schema" in data:
data["schema"] = self.openapi.resolve_schema_dict(data["schema"])
# OAS 3 component except header
if self.openapi_version.major >= 3:
if "content" in data:
for content_type in data["content"]:
schema = data["content"][content_type]["schema"]
data["content"][content_type][
"schema"
] = self.openapi.resolve_schema_dict(schema) | python | def resolve_schema(self, data):
"""Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dictionary that may
contain a schema, or a reference provided as string
"""
if not isinstance(data, dict):
return
# OAS 2 component or OAS 3 header
if "schema" in data:
data["schema"] = self.openapi.resolve_schema_dict(data["schema"])
# OAS 3 component except header
if self.openapi_version.major >= 3:
if "content" in data:
for content_type in data["content"]:
schema = data["content"][content_type]["schema"]
data["content"][content_type][
"schema"
] = self.openapi.resolve_schema_dict(schema) | [
"def",
"resolve_schema",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"# OAS 2 component or OAS 3 header",
"if",
"\"schema\"",
"in",
"data",
":",
"data",
"[",
"\"schema\"",
"]",
"=",
"self",
".",
"openapi",
".",
"resolve_schema_dict",
"(",
"data",
"[",
"\"schema\"",
"]",
")",
"# OAS 3 component except header",
"if",
"self",
".",
"openapi_version",
".",
"major",
">=",
"3",
":",
"if",
"\"content\"",
"in",
"data",
":",
"for",
"content_type",
"in",
"data",
"[",
"\"content\"",
"]",
":",
"schema",
"=",
"data",
"[",
"\"content\"",
"]",
"[",
"content_type",
"]",
"[",
"\"schema\"",
"]",
"data",
"[",
"\"content\"",
"]",
"[",
"content_type",
"]",
"[",
"\"schema\"",
"]",
"=",
"self",
".",
"openapi",
".",
"resolve_schema_dict",
"(",
"schema",
")"
] | Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dictionary that may
contain a schema, or a reference provided as string | [
"Function",
"to",
"resolve",
"a",
"schema",
"in",
"a",
"parameter",
"or",
"response",
"-",
"modifies",
"the",
"corresponding",
"dict",
"to",
"convert",
"Marshmallow",
"Schema",
"object",
"or",
"class",
"into",
"dict"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L109-L130 |
229,663 | marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | MarshmallowPlugin.warn_if_schema_already_in_spec | def warn_if_schema_already_in_spec(self, schema_key):
"""Method to warn the user if the schema has already been added to the
spec.
"""
if schema_key in self.openapi.refs:
warnings.warn(
"{} has already been added to the spec. Adding it twice may "
"cause references to not resolve properly.".format(schema_key[0]),
UserWarning,
) | python | def warn_if_schema_already_in_spec(self, schema_key):
"""Method to warn the user if the schema has already been added to the
spec.
"""
if schema_key in self.openapi.refs:
warnings.warn(
"{} has already been added to the spec. Adding it twice may "
"cause references to not resolve properly.".format(schema_key[0]),
UserWarning,
) | [
"def",
"warn_if_schema_already_in_spec",
"(",
"self",
",",
"schema_key",
")",
":",
"if",
"schema_key",
"in",
"self",
".",
"openapi",
".",
"refs",
":",
"warnings",
".",
"warn",
"(",
"\"{} has already been added to the spec. Adding it twice may \"",
"\"cause references to not resolve properly.\"",
".",
"format",
"(",
"schema_key",
"[",
"0",
"]",
")",
",",
"UserWarning",
",",
")"
] | Method to warn the user if the schema has already been added to the
spec. | [
"Method",
"to",
"warn",
"the",
"user",
"if",
"the",
"schema",
"has",
"already",
"been",
"added",
"to",
"the",
"spec",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L213-L222 |
229,664 | flyingrub/scdl | scdl/utils.py | size_in_bytes | def size_in_bytes(insize):
"""
Returns the size in bytes from strings such as '5 mb' into 5242880.
>>> size_in_bytes('1m')
1048576
>>> size_in_bytes('1.5m')
1572864
>>> size_in_bytes('2g')
2147483648
>>> size_in_bytes(None)
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
>>> size_in_bytes('')
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
"""
if insize is None or insize.strip() == '':
raise ValueError('no string specified')
units = {
'k': 1024,
'm': 1024 ** 2,
'g': 1024 ** 3,
't': 1024 ** 4,
'p': 1024 ** 5,
}
match = re.search('^\s*([0-9\.]+)\s*([kmgtp])?', insize, re.I)
if match is None:
raise ValueError('match not found')
size, unit = match.groups()
if size:
size = float(size)
if unit:
size = size * units[unit.lower().strip()]
return int(size) | python | def size_in_bytes(insize):
"""
Returns the size in bytes from strings such as '5 mb' into 5242880.
>>> size_in_bytes('1m')
1048576
>>> size_in_bytes('1.5m')
1572864
>>> size_in_bytes('2g')
2147483648
>>> size_in_bytes(None)
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
>>> size_in_bytes('')
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
"""
if insize is None or insize.strip() == '':
raise ValueError('no string specified')
units = {
'k': 1024,
'm': 1024 ** 2,
'g': 1024 ** 3,
't': 1024 ** 4,
'p': 1024 ** 5,
}
match = re.search('^\s*([0-9\.]+)\s*([kmgtp])?', insize, re.I)
if match is None:
raise ValueError('match not found')
size, unit = match.groups()
if size:
size = float(size)
if unit:
size = size * units[unit.lower().strip()]
return int(size) | [
"def",
"size_in_bytes",
"(",
"insize",
")",
":",
"if",
"insize",
"is",
"None",
"or",
"insize",
".",
"strip",
"(",
")",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"'no string specified'",
")",
"units",
"=",
"{",
"'k'",
":",
"1024",
",",
"'m'",
":",
"1024",
"**",
"2",
",",
"'g'",
":",
"1024",
"**",
"3",
",",
"'t'",
":",
"1024",
"**",
"4",
",",
"'p'",
":",
"1024",
"**",
"5",
",",
"}",
"match",
"=",
"re",
".",
"search",
"(",
"'^\\s*([0-9\\.]+)\\s*([kmgtp])?'",
",",
"insize",
",",
"re",
".",
"I",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'match not found'",
")",
"size",
",",
"unit",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"size",
":",
"size",
"=",
"float",
"(",
"size",
")",
"if",
"unit",
":",
"size",
"=",
"size",
"*",
"units",
"[",
"unit",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"]",
"return",
"int",
"(",
"size",
")"
] | Returns the size in bytes from strings such as '5 mb' into 5242880.
>>> size_in_bytes('1m')
1048576
>>> size_in_bytes('1.5m')
1572864
>>> size_in_bytes('2g')
2147483648
>>> size_in_bytes(None)
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
>>> size_in_bytes('')
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified | [
"Returns",
"the",
"size",
"in",
"bytes",
"from",
"strings",
"such",
"as",
"5",
"mb",
"into",
"5242880",
"."
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/utils.py#L31-L73 |
229,665 | flyingrub/scdl | scdl/scdl.py | main | def main():
"""
Main function, parses the URL from command line arguments
"""
signal.signal(signal.SIGINT, signal_handler)
global offset
global arguments
# Parse argument
arguments = docopt(__doc__, version=__version__)
if arguments['--debug']:
logger.level = logging.DEBUG
elif arguments['--error']:
logger.level = logging.ERROR
# import conf file
get_config()
logger.info('Soundcloud Downloader')
logger.debug(arguments)
if arguments['-o'] is not None:
try:
offset = int(arguments['-o'])
if offset < 0:
raise
except:
logger.error('Offset should be a positive integer...')
sys.exit()
logger.debug('offset: %d', offset)
if arguments['--min-size'] is not None:
try:
arguments['--min-size'] = utils.size_in_bytes(
arguments['--min-size']
)
except:
logger.exception(
'Min size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('min-size: %d', arguments['--min-size'])
if arguments['--max-size'] is not None:
try:
arguments['--max-size'] = utils.size_in_bytes(
arguments['--max-size']
)
except:
logger.error(
'Max size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('max-size: %d', arguments['--max-size'])
if arguments['--hidewarnings']:
warnings.filterwarnings('ignore')
if arguments['--path'] is not None:
if os.path.exists(arguments['--path']):
os.chdir(arguments['--path'])
else:
logger.error('Invalid path in arguments...')
sys.exit()
logger.debug('Downloading to '+os.getcwd()+'...')
if arguments['-l']:
parse_url(arguments['-l'])
elif arguments['me']:
if arguments['-f']:
download(who_am_i(), 'favorites', 'likes')
if arguments['-C']:
download(who_am_i(), 'commented', 'commented tracks')
elif arguments['-t']:
download(who_am_i(), 'tracks', 'uploaded tracks')
elif arguments['-a']:
download(who_am_i(), 'all', 'tracks and reposts')
elif arguments['-p']:
download(who_am_i(), 'playlists', 'playlists')
elif arguments['-m']:
download(who_am_i(), 'playlists-liked', 'my and liked playlists')
if arguments['--remove']:
remove_files() | python | def main():
"""
Main function, parses the URL from command line arguments
"""
signal.signal(signal.SIGINT, signal_handler)
global offset
global arguments
# Parse argument
arguments = docopt(__doc__, version=__version__)
if arguments['--debug']:
logger.level = logging.DEBUG
elif arguments['--error']:
logger.level = logging.ERROR
# import conf file
get_config()
logger.info('Soundcloud Downloader')
logger.debug(arguments)
if arguments['-o'] is not None:
try:
offset = int(arguments['-o'])
if offset < 0:
raise
except:
logger.error('Offset should be a positive integer...')
sys.exit()
logger.debug('offset: %d', offset)
if arguments['--min-size'] is not None:
try:
arguments['--min-size'] = utils.size_in_bytes(
arguments['--min-size']
)
except:
logger.exception(
'Min size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('min-size: %d', arguments['--min-size'])
if arguments['--max-size'] is not None:
try:
arguments['--max-size'] = utils.size_in_bytes(
arguments['--max-size']
)
except:
logger.error(
'Max size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('max-size: %d', arguments['--max-size'])
if arguments['--hidewarnings']:
warnings.filterwarnings('ignore')
if arguments['--path'] is not None:
if os.path.exists(arguments['--path']):
os.chdir(arguments['--path'])
else:
logger.error('Invalid path in arguments...')
sys.exit()
logger.debug('Downloading to '+os.getcwd()+'...')
if arguments['-l']:
parse_url(arguments['-l'])
elif arguments['me']:
if arguments['-f']:
download(who_am_i(), 'favorites', 'likes')
if arguments['-C']:
download(who_am_i(), 'commented', 'commented tracks')
elif arguments['-t']:
download(who_am_i(), 'tracks', 'uploaded tracks')
elif arguments['-a']:
download(who_am_i(), 'all', 'tracks and reposts')
elif arguments['-p']:
download(who_am_i(), 'playlists', 'playlists')
elif arguments['-m']:
download(who_am_i(), 'playlists-liked', 'my and liked playlists')
if arguments['--remove']:
remove_files() | [
"def",
"main",
"(",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal_handler",
")",
"global",
"offset",
"global",
"arguments",
"# Parse argument",
"arguments",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__version__",
")",
"if",
"arguments",
"[",
"'--debug'",
"]",
":",
"logger",
".",
"level",
"=",
"logging",
".",
"DEBUG",
"elif",
"arguments",
"[",
"'--error'",
"]",
":",
"logger",
".",
"level",
"=",
"logging",
".",
"ERROR",
"# import conf file",
"get_config",
"(",
")",
"logger",
".",
"info",
"(",
"'Soundcloud Downloader'",
")",
"logger",
".",
"debug",
"(",
"arguments",
")",
"if",
"arguments",
"[",
"'-o'",
"]",
"is",
"not",
"None",
":",
"try",
":",
"offset",
"=",
"int",
"(",
"arguments",
"[",
"'-o'",
"]",
")",
"if",
"offset",
"<",
"0",
":",
"raise",
"except",
":",
"logger",
".",
"error",
"(",
"'Offset should be a positive integer...'",
")",
"sys",
".",
"exit",
"(",
")",
"logger",
".",
"debug",
"(",
"'offset: %d'",
",",
"offset",
")",
"if",
"arguments",
"[",
"'--min-size'",
"]",
"is",
"not",
"None",
":",
"try",
":",
"arguments",
"[",
"'--min-size'",
"]",
"=",
"utils",
".",
"size_in_bytes",
"(",
"arguments",
"[",
"'--min-size'",
"]",
")",
"except",
":",
"logger",
".",
"exception",
"(",
"'Min size should be an integer with a possible unit suffix'",
")",
"sys",
".",
"exit",
"(",
")",
"logger",
".",
"debug",
"(",
"'min-size: %d'",
",",
"arguments",
"[",
"'--min-size'",
"]",
")",
"if",
"arguments",
"[",
"'--max-size'",
"]",
"is",
"not",
"None",
":",
"try",
":",
"arguments",
"[",
"'--max-size'",
"]",
"=",
"utils",
".",
"size_in_bytes",
"(",
"arguments",
"[",
"'--max-size'",
"]",
")",
"except",
":",
"logger",
".",
"error",
"(",
"'Max size should be an integer with a possible unit suffix'",
")",
"sys",
".",
"exit",
"(",
")",
"logger",
".",
"debug",
"(",
"'max-size: %d'",
",",
"arguments",
"[",
"'--max-size'",
"]",
")",
"if",
"arguments",
"[",
"'--hidewarnings'",
"]",
":",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
")",
"if",
"arguments",
"[",
"'--path'",
"]",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"arguments",
"[",
"'--path'",
"]",
")",
":",
"os",
".",
"chdir",
"(",
"arguments",
"[",
"'--path'",
"]",
")",
"else",
":",
"logger",
".",
"error",
"(",
"'Invalid path in arguments...'",
")",
"sys",
".",
"exit",
"(",
")",
"logger",
".",
"debug",
"(",
"'Downloading to '",
"+",
"os",
".",
"getcwd",
"(",
")",
"+",
"'...'",
")",
"if",
"arguments",
"[",
"'-l'",
"]",
":",
"parse_url",
"(",
"arguments",
"[",
"'-l'",
"]",
")",
"elif",
"arguments",
"[",
"'me'",
"]",
":",
"if",
"arguments",
"[",
"'-f'",
"]",
":",
"download",
"(",
"who_am_i",
"(",
")",
",",
"'favorites'",
",",
"'likes'",
")",
"if",
"arguments",
"[",
"'-C'",
"]",
":",
"download",
"(",
"who_am_i",
"(",
")",
",",
"'commented'",
",",
"'commented tracks'",
")",
"elif",
"arguments",
"[",
"'-t'",
"]",
":",
"download",
"(",
"who_am_i",
"(",
")",
",",
"'tracks'",
",",
"'uploaded tracks'",
")",
"elif",
"arguments",
"[",
"'-a'",
"]",
":",
"download",
"(",
"who_am_i",
"(",
")",
",",
"'all'",
",",
"'tracks and reposts'",
")",
"elif",
"arguments",
"[",
"'-p'",
"]",
":",
"download",
"(",
"who_am_i",
"(",
")",
",",
"'playlists'",
",",
"'playlists'",
")",
"elif",
"arguments",
"[",
"'-m'",
"]",
":",
"download",
"(",
"who_am_i",
"(",
")",
",",
"'playlists-liked'",
",",
"'my and liked playlists'",
")",
"if",
"arguments",
"[",
"'--remove'",
"]",
":",
"remove_files",
"(",
")"
] | Main function, parses the URL from command line arguments | [
"Main",
"function",
"parses",
"the",
"URL",
"from",
"command",
"line",
"arguments"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L111-L195 |
229,666 | flyingrub/scdl | scdl/scdl.py | get_config | def get_config():
"""
Reads the music download filepath from scdl.cfg
"""
global token
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg'))
try:
token = config['scdl']['auth_token']
path = config['scdl']['path']
except:
logger.error('Are you sure scdl.cfg is in $HOME/.config/scdl/ ?')
logger.error('Are both "auth_token" and "path" defined there?')
sys.exit()
if os.path.exists(path):
os.chdir(path)
else:
logger.error('Invalid path in scdl.cfg...')
sys.exit() | python | def get_config():
"""
Reads the music download filepath from scdl.cfg
"""
global token
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg'))
try:
token = config['scdl']['auth_token']
path = config['scdl']['path']
except:
logger.error('Are you sure scdl.cfg is in $HOME/.config/scdl/ ?')
logger.error('Are both "auth_token" and "path" defined there?')
sys.exit()
if os.path.exists(path):
os.chdir(path)
else:
logger.error('Invalid path in scdl.cfg...')
sys.exit() | [
"def",
"get_config",
"(",
")",
":",
"global",
"token",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.config/scdl/scdl.cfg'",
")",
")",
"try",
":",
"token",
"=",
"config",
"[",
"'scdl'",
"]",
"[",
"'auth_token'",
"]",
"path",
"=",
"config",
"[",
"'scdl'",
"]",
"[",
"'path'",
"]",
"except",
":",
"logger",
".",
"error",
"(",
"'Are you sure scdl.cfg is in $HOME/.config/scdl/ ?'",
")",
"logger",
".",
"error",
"(",
"'Are both \"auth_token\" and \"path\" defined there?'",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"chdir",
"(",
"path",
")",
"else",
":",
"logger",
".",
"error",
"(",
"'Invalid path in scdl.cfg...'",
")",
"sys",
".",
"exit",
"(",
")"
] | Reads the music download filepath from scdl.cfg | [
"Reads",
"the",
"music",
"download",
"filepath",
"from",
"scdl",
".",
"cfg"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L198-L216 |
229,667 | flyingrub/scdl | scdl/scdl.py | get_item | def get_item(track_url, client_id=CLIENT_ID):
"""
Fetches metadata for a track or playlist
"""
try:
item_url = url['resolve'].format(track_url)
r = requests.get(item_url, params={'client_id': client_id})
logger.debug(r.url)
if r.status_code == 403:
return get_item(track_url, ALT_CLIENT_ID)
item = r.json()
no_tracks = item['kind'] == 'playlist' and not item['tracks']
if no_tracks and client_id != ALT_CLIENT_ID:
return get_item(track_url, ALT_CLIENT_ID)
except Exception:
if client_id == ALT_CLIENT_ID:
logger.error('Failed to get item...')
return
logger.error('Error resolving url, retrying...')
time.sleep(5)
try:
return get_item(track_url, ALT_CLIENT_ID)
except Exception as e:
logger.error('Could not resolve url {0}'.format(track_url))
logger.exception(e)
sys.exit(0)
return item | python | def get_item(track_url, client_id=CLIENT_ID):
"""
Fetches metadata for a track or playlist
"""
try:
item_url = url['resolve'].format(track_url)
r = requests.get(item_url, params={'client_id': client_id})
logger.debug(r.url)
if r.status_code == 403:
return get_item(track_url, ALT_CLIENT_ID)
item = r.json()
no_tracks = item['kind'] == 'playlist' and not item['tracks']
if no_tracks and client_id != ALT_CLIENT_ID:
return get_item(track_url, ALT_CLIENT_ID)
except Exception:
if client_id == ALT_CLIENT_ID:
logger.error('Failed to get item...')
return
logger.error('Error resolving url, retrying...')
time.sleep(5)
try:
return get_item(track_url, ALT_CLIENT_ID)
except Exception as e:
logger.error('Could not resolve url {0}'.format(track_url))
logger.exception(e)
sys.exit(0)
return item | [
"def",
"get_item",
"(",
"track_url",
",",
"client_id",
"=",
"CLIENT_ID",
")",
":",
"try",
":",
"item_url",
"=",
"url",
"[",
"'resolve'",
"]",
".",
"format",
"(",
"track_url",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"item_url",
",",
"params",
"=",
"{",
"'client_id'",
":",
"client_id",
"}",
")",
"logger",
".",
"debug",
"(",
"r",
".",
"url",
")",
"if",
"r",
".",
"status_code",
"==",
"403",
":",
"return",
"get_item",
"(",
"track_url",
",",
"ALT_CLIENT_ID",
")",
"item",
"=",
"r",
".",
"json",
"(",
")",
"no_tracks",
"=",
"item",
"[",
"'kind'",
"]",
"==",
"'playlist'",
"and",
"not",
"item",
"[",
"'tracks'",
"]",
"if",
"no_tracks",
"and",
"client_id",
"!=",
"ALT_CLIENT_ID",
":",
"return",
"get_item",
"(",
"track_url",
",",
"ALT_CLIENT_ID",
")",
"except",
"Exception",
":",
"if",
"client_id",
"==",
"ALT_CLIENT_ID",
":",
"logger",
".",
"error",
"(",
"'Failed to get item...'",
")",
"return",
"logger",
".",
"error",
"(",
"'Error resolving url, retrying...'",
")",
"time",
".",
"sleep",
"(",
"5",
")",
"try",
":",
"return",
"get_item",
"(",
"track_url",
",",
"ALT_CLIENT_ID",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"'Could not resolve url {0}'",
".",
"format",
"(",
"track_url",
")",
")",
"logger",
".",
"exception",
"(",
"e",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"return",
"item"
] | Fetches metadata for a track or playlist | [
"Fetches",
"metadata",
"for",
"a",
"track",
"or",
"playlist"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L219-L247 |
229,668 | flyingrub/scdl | scdl/scdl.py | who_am_i | def who_am_i():
"""
Display username from current token and check for validity
"""
me = url['me'].format(token)
r = requests.get(me, params={'client_id': CLIENT_ID})
r.raise_for_status()
current_user = r.json()
logger.debug(me)
logger.info('Hello {0}!'.format(current_user['username']))
return current_user | python | def who_am_i():
"""
Display username from current token and check for validity
"""
me = url['me'].format(token)
r = requests.get(me, params={'client_id': CLIENT_ID})
r.raise_for_status()
current_user = r.json()
logger.debug(me)
logger.info('Hello {0}!'.format(current_user['username']))
return current_user | [
"def",
"who_am_i",
"(",
")",
":",
"me",
"=",
"url",
"[",
"'me'",
"]",
".",
"format",
"(",
"token",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"me",
",",
"params",
"=",
"{",
"'client_id'",
":",
"CLIENT_ID",
"}",
")",
"r",
".",
"raise_for_status",
"(",
")",
"current_user",
"=",
"r",
".",
"json",
"(",
")",
"logger",
".",
"debug",
"(",
"me",
")",
"logger",
".",
"info",
"(",
"'Hello {0}!'",
".",
"format",
"(",
"current_user",
"[",
"'username'",
"]",
")",
")",
"return",
"current_user"
] | Display username from current token and check for validity | [
"Display",
"username",
"from",
"current",
"token",
"and",
"check",
"for",
"validity"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L286-L297 |
229,669 | flyingrub/scdl | scdl/scdl.py | remove_files | def remove_files():
"""
Removes any pre-existing tracks that were not just downloaded
"""
logger.info("Removing local track files that were not downloaded...")
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f not in fileToKeep:
os.remove(f) | python | def remove_files():
"""
Removes any pre-existing tracks that were not just downloaded
"""
logger.info("Removing local track files that were not downloaded...")
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f not in fileToKeep:
os.remove(f) | [
"def",
"remove_files",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing local track files that were not downloaded...\"",
")",
"files",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"'.'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
"]",
"for",
"f",
"in",
"files",
":",
"if",
"f",
"not",
"in",
"fileToKeep",
":",
"os",
".",
"remove",
"(",
"f",
")"
] | Removes any pre-existing tracks that were not just downloaded | [
"Removes",
"any",
"pre",
"-",
"existing",
"tracks",
"that",
"were",
"not",
"just",
"downloaded"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L300-L308 |
229,670 | flyingrub/scdl | scdl/scdl.py | get_track_info | def get_track_info(track_id):
"""
Fetches track info from Soundcloud, given a track_id
"""
logger.info('Retrieving more info on the track')
info_url = url["trackinfo"].format(track_id)
r = requests.get(info_url, params={'client_id': CLIENT_ID}, stream=True)
item = r.json()
logger.debug(item)
return item | python | def get_track_info(track_id):
"""
Fetches track info from Soundcloud, given a track_id
"""
logger.info('Retrieving more info on the track')
info_url = url["trackinfo"].format(track_id)
r = requests.get(info_url, params={'client_id': CLIENT_ID}, stream=True)
item = r.json()
logger.debug(item)
return item | [
"def",
"get_track_info",
"(",
"track_id",
")",
":",
"logger",
".",
"info",
"(",
"'Retrieving more info on the track'",
")",
"info_url",
"=",
"url",
"[",
"\"trackinfo\"",
"]",
".",
"format",
"(",
"track_id",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"info_url",
",",
"params",
"=",
"{",
"'client_id'",
":",
"CLIENT_ID",
"}",
",",
"stream",
"=",
"True",
")",
"item",
"=",
"r",
".",
"json",
"(",
")",
"logger",
".",
"debug",
"(",
"item",
")",
"return",
"item"
] | Fetches track info from Soundcloud, given a track_id | [
"Fetches",
"track",
"info",
"from",
"Soundcloud",
"given",
"a",
"track_id"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L311-L320 |
229,671 | flyingrub/scdl | scdl/scdl.py | already_downloaded | def already_downloaded(track, title, filename):
"""
Returns True if the file has already been downloaded
"""
global arguments
already_downloaded = False
if os.path.isfile(filename):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) \
and os.path.isfile(filename[:-4] + ".flac"):
already_downloaded = True
if arguments['--download-archive'] and in_download_archive(track):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) and os.path.isfile(filename):
already_downloaded = False
if already_downloaded:
if arguments['-c'] or arguments['--remove']:
logger.info('Track "{0}" already downloaded.'.format(title))
return True
else:
logger.error('Track "{0}" already exists!'.format(title))
logger.error('Exiting... (run again with -c to continue)')
sys.exit(0)
return False | python | def already_downloaded(track, title, filename):
"""
Returns True if the file has already been downloaded
"""
global arguments
already_downloaded = False
if os.path.isfile(filename):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) \
and os.path.isfile(filename[:-4] + ".flac"):
already_downloaded = True
if arguments['--download-archive'] and in_download_archive(track):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) and os.path.isfile(filename):
already_downloaded = False
if already_downloaded:
if arguments['-c'] or arguments['--remove']:
logger.info('Track "{0}" already downloaded.'.format(title))
return True
else:
logger.error('Track "{0}" already exists!'.format(title))
logger.error('Exiting... (run again with -c to continue)')
sys.exit(0)
return False | [
"def",
"already_downloaded",
"(",
"track",
",",
"title",
",",
"filename",
")",
":",
"global",
"arguments",
"already_downloaded",
"=",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"already_downloaded",
"=",
"True",
"if",
"arguments",
"[",
"'--flac'",
"]",
"and",
"can_convert",
"(",
"filename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
"[",
":",
"-",
"4",
"]",
"+",
"\".flac\"",
")",
":",
"already_downloaded",
"=",
"True",
"if",
"arguments",
"[",
"'--download-archive'",
"]",
"and",
"in_download_archive",
"(",
"track",
")",
":",
"already_downloaded",
"=",
"True",
"if",
"arguments",
"[",
"'--flac'",
"]",
"and",
"can_convert",
"(",
"filename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"already_downloaded",
"=",
"False",
"if",
"already_downloaded",
":",
"if",
"arguments",
"[",
"'-c'",
"]",
"or",
"arguments",
"[",
"'--remove'",
"]",
":",
"logger",
".",
"info",
"(",
"'Track \"{0}\" already downloaded.'",
".",
"format",
"(",
"title",
")",
")",
"return",
"True",
"else",
":",
"logger",
".",
"error",
"(",
"'Track \"{0}\" already exists!'",
".",
"format",
"(",
"title",
")",
")",
"logger",
".",
"error",
"(",
"'Exiting... (run again with -c to continue)'",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"return",
"False"
] | Returns True if the file has already been downloaded | [
"Returns",
"True",
"if",
"the",
"file",
"has",
"already",
"been",
"downloaded"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L562-L588 |
229,672 | flyingrub/scdl | scdl/scdl.py | in_download_archive | def in_download_archive(track):
"""
Returns True if a track_id exists in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a+', encoding='utf-8') as file:
logger.debug('Contents of {0}:'.format(archive_filename))
file.seek(0)
track_id = '{0}'.format(track['id'])
for line in file:
logger.debug('"'+line.strip()+'"')
if line.strip() == track_id:
return True
except IOError as ioe:
logger.error('Error trying to read download archive...')
logger.debug(ioe)
return False | python | def in_download_archive(track):
"""
Returns True if a track_id exists in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a+', encoding='utf-8') as file:
logger.debug('Contents of {0}:'.format(archive_filename))
file.seek(0)
track_id = '{0}'.format(track['id'])
for line in file:
logger.debug('"'+line.strip()+'"')
if line.strip() == track_id:
return True
except IOError as ioe:
logger.error('Error trying to read download archive...')
logger.debug(ioe)
return False | [
"def",
"in_download_archive",
"(",
"track",
")",
":",
"global",
"arguments",
"if",
"not",
"arguments",
"[",
"'--download-archive'",
"]",
":",
"return",
"archive_filename",
"=",
"arguments",
".",
"get",
"(",
"'--download-archive'",
")",
"try",
":",
"with",
"open",
"(",
"archive_filename",
",",
"'a+'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file",
":",
"logger",
".",
"debug",
"(",
"'Contents of {0}:'",
".",
"format",
"(",
"archive_filename",
")",
")",
"file",
".",
"seek",
"(",
"0",
")",
"track_id",
"=",
"'{0}'",
".",
"format",
"(",
"track",
"[",
"'id'",
"]",
")",
"for",
"line",
"in",
"file",
":",
"logger",
".",
"debug",
"(",
"'\"'",
"+",
"line",
".",
"strip",
"(",
")",
"+",
"'\"'",
")",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"track_id",
":",
"return",
"True",
"except",
"IOError",
"as",
"ioe",
":",
"logger",
".",
"error",
"(",
"'Error trying to read download archive...'",
")",
"logger",
".",
"debug",
"(",
"ioe",
")",
"return",
"False"
] | Returns True if a track_id exists in the download archive | [
"Returns",
"True",
"if",
"a",
"track_id",
"exists",
"in",
"the",
"download",
"archive"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L591-L613 |
229,673 | flyingrub/scdl | scdl/scdl.py | record_download_archive | def record_download_archive(track):
"""
Write the track_id in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a', encoding='utf-8') as file:
file.write('{0}'.format(track['id'])+'\n')
except IOError as ioe:
logger.error('Error trying to write to download archive...')
logger.debug(ioe) | python | def record_download_archive(track):
"""
Write the track_id in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a', encoding='utf-8') as file:
file.write('{0}'.format(track['id'])+'\n')
except IOError as ioe:
logger.error('Error trying to write to download archive...')
logger.debug(ioe) | [
"def",
"record_download_archive",
"(",
"track",
")",
":",
"global",
"arguments",
"if",
"not",
"arguments",
"[",
"'--download-archive'",
"]",
":",
"return",
"archive_filename",
"=",
"arguments",
".",
"get",
"(",
"'--download-archive'",
")",
"try",
":",
"with",
"open",
"(",
"archive_filename",
",",
"'a'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"'{0}'",
".",
"format",
"(",
"track",
"[",
"'id'",
"]",
")",
"+",
"'\\n'",
")",
"except",
"IOError",
"as",
"ioe",
":",
"logger",
".",
"error",
"(",
"'Error trying to write to download archive...'",
")",
"logger",
".",
"debug",
"(",
"ioe",
")"
] | Write the track_id in the download archive | [
"Write",
"the",
"track_id",
"in",
"the",
"download",
"archive"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L616-L630 |
229,674 | lins05/slackbot | slackbot/dispatcher.py | unicode_compact | def unicode_compact(func):
"""
Make sure the first parameter of the decorated method to be a unicode
object.
"""
@wraps(func)
def wrapped(self, text, *a, **kw):
if not isinstance(text, six.text_type):
text = text.decode('utf-8')
return func(self, text, *a, **kw)
return wrapped | python | def unicode_compact(func):
"""
Make sure the first parameter of the decorated method to be a unicode
object.
"""
@wraps(func)
def wrapped(self, text, *a, **kw):
if not isinstance(text, six.text_type):
text = text.decode('utf-8')
return func(self, text, *a, **kw)
return wrapped | [
"def",
"unicode_compact",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"self",
",",
"text",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"func",
"(",
"self",
",",
"text",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"return",
"wrapped"
] | Make sure the first parameter of the decorated method to be a unicode
object. | [
"Make",
"sure",
"the",
"first",
"parameter",
"of",
"the",
"decorated",
"method",
"to",
"be",
"a",
"unicode",
"object",
"."
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L173-L185 |
229,675 | lins05/slackbot | slackbot/dispatcher.py | Message.reply_webapi | def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None):
"""
Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send_webapi(text, attachments=attachments, as_user=as_user, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send_webapi(text, attachments=attachments, as_user=as_user) | python | def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None):
"""
Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send_webapi(text, attachments=attachments, as_user=as_user, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send_webapi(text, attachments=attachments, as_user=as_user) | [
"def",
"reply_webapi",
"(",
"self",
",",
"text",
",",
"attachments",
"=",
"None",
",",
"as_user",
"=",
"True",
",",
"in_thread",
"=",
"None",
")",
":",
"if",
"in_thread",
"is",
"None",
":",
"in_thread",
"=",
"'thread_ts'",
"in",
"self",
".",
"body",
"if",
"in_thread",
":",
"self",
".",
"send_webapi",
"(",
"text",
",",
"attachments",
"=",
"attachments",
",",
"as_user",
"=",
"as_user",
",",
"thread_ts",
"=",
"self",
".",
"thread_ts",
")",
"else",
":",
"text",
"=",
"self",
".",
"gen_reply",
"(",
"text",
")",
"self",
".",
"send_webapi",
"(",
"text",
",",
"attachments",
"=",
"attachments",
",",
"as_user",
"=",
"as_user",
")"
] | Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default. | [
"Send",
"a",
"reply",
"to",
"the",
"sender",
"using",
"Web",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L214-L230 |
229,676 | lins05/slackbot | slackbot/dispatcher.py | Message.send_webapi | def send_webapi(self, text, attachments=None, as_user=True, thread_ts=None):
"""
Send a reply using Web API
(This function supports formatted message
when using a bot integration)
"""
self._client.send_message(
self._body['channel'],
text,
attachments=attachments,
as_user=as_user,
thread_ts=thread_ts) | python | def send_webapi(self, text, attachments=None, as_user=True, thread_ts=None):
"""
Send a reply using Web API
(This function supports formatted message
when using a bot integration)
"""
self._client.send_message(
self._body['channel'],
text,
attachments=attachments,
as_user=as_user,
thread_ts=thread_ts) | [
"def",
"send_webapi",
"(",
"self",
",",
"text",
",",
"attachments",
"=",
"None",
",",
"as_user",
"=",
"True",
",",
"thread_ts",
"=",
"None",
")",
":",
"self",
".",
"_client",
".",
"send_message",
"(",
"self",
".",
"_body",
"[",
"'channel'",
"]",
",",
"text",
",",
"attachments",
"=",
"attachments",
",",
"as_user",
"=",
"as_user",
",",
"thread_ts",
"=",
"thread_ts",
")"
] | Send a reply using Web API
(This function supports formatted message
when using a bot integration) | [
"Send",
"a",
"reply",
"using",
"Web",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L233-L245 |
229,677 | lins05/slackbot | slackbot/dispatcher.py | Message.reply | def reply(self, text, in_thread=None):
"""
Send a reply to the sender using RTM API
(This function doesn't supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send(text, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send(text) | python | def reply(self, text, in_thread=None):
"""
Send a reply to the sender using RTM API
(This function doesn't supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send(text, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send(text) | [
"def",
"reply",
"(",
"self",
",",
"text",
",",
"in_thread",
"=",
"None",
")",
":",
"if",
"in_thread",
"is",
"None",
":",
"in_thread",
"=",
"'thread_ts'",
"in",
"self",
".",
"body",
"if",
"in_thread",
":",
"self",
".",
"send",
"(",
"text",
",",
"thread_ts",
"=",
"self",
".",
"thread_ts",
")",
"else",
":",
"text",
"=",
"self",
".",
"gen_reply",
"(",
"text",
")",
"self",
".",
"send",
"(",
"text",
")"
] | Send a reply to the sender using RTM API
(This function doesn't supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default. | [
"Send",
"a",
"reply",
"to",
"the",
"sender",
"using",
"RTM",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L248-L264 |
229,678 | lins05/slackbot | slackbot/dispatcher.py | Message.direct_reply | def direct_reply(self, text):
"""
Send a reply via direct message using RTM API
"""
channel_id = self._client.open_dm_channel(self._get_user_id())
self._client.rtm_send_message(channel_id, text) | python | def direct_reply(self, text):
"""
Send a reply via direct message using RTM API
"""
channel_id = self._client.open_dm_channel(self._get_user_id())
self._client.rtm_send_message(channel_id, text) | [
"def",
"direct_reply",
"(",
"self",
",",
"text",
")",
":",
"channel_id",
"=",
"self",
".",
"_client",
".",
"open_dm_channel",
"(",
"self",
".",
"_get_user_id",
"(",
")",
")",
"self",
".",
"_client",
".",
"rtm_send_message",
"(",
"channel_id",
",",
"text",
")"
] | Send a reply via direct message using RTM API | [
"Send",
"a",
"reply",
"via",
"direct",
"message",
"using",
"RTM",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L267-L273 |
229,679 | lins05/slackbot | slackbot/dispatcher.py | Message.send | def send(self, text, thread_ts=None):
"""
Send a reply using RTM API
(This function doesn't supports formatted message
when using a bot integration)
"""
self._client.rtm_send_message(self._body['channel'], text, thread_ts=thread_ts) | python | def send(self, text, thread_ts=None):
"""
Send a reply using RTM API
(This function doesn't supports formatted message
when using a bot integration)
"""
self._client.rtm_send_message(self._body['channel'], text, thread_ts=thread_ts) | [
"def",
"send",
"(",
"self",
",",
"text",
",",
"thread_ts",
"=",
"None",
")",
":",
"self",
".",
"_client",
".",
"rtm_send_message",
"(",
"self",
".",
"_body",
"[",
"'channel'",
"]",
",",
"text",
",",
"thread_ts",
"=",
"thread_ts",
")"
] | Send a reply using RTM API
(This function doesn't supports formatted message
when using a bot integration) | [
"Send",
"a",
"reply",
"using",
"RTM",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L277-L284 |
229,680 | lins05/slackbot | slackbot/dispatcher.py | Message.react | def react(self, emojiname):
"""
React to a message using the web api
"""
self._client.react_to_message(
emojiname=emojiname,
channel=self._body['channel'],
timestamp=self._body['ts']) | python | def react(self, emojiname):
"""
React to a message using the web api
"""
self._client.react_to_message(
emojiname=emojiname,
channel=self._body['channel'],
timestamp=self._body['ts']) | [
"def",
"react",
"(",
"self",
",",
"emojiname",
")",
":",
"self",
".",
"_client",
".",
"react_to_message",
"(",
"emojiname",
"=",
"emojiname",
",",
"channel",
"=",
"self",
".",
"_body",
"[",
"'channel'",
"]",
",",
"timestamp",
"=",
"self",
".",
"_body",
"[",
"'ts'",
"]",
")"
] | React to a message using the web api | [
"React",
"to",
"a",
"message",
"using",
"the",
"web",
"api"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L286-L293 |
229,681 | lins05/slackbot | slackbot/bot.py | default_reply | def default_reply(*args, **kwargs):
"""
Decorator declaring the wrapped function to the default reply hanlder.
May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or
with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``).
"""
invoked = bool(not args or kwargs)
matchstr = kwargs.pop('matchstr', r'^.*$')
flags = kwargs.pop('flags', 0)
if not invoked:
func = args[0]
def wrapper(func):
PluginsManager.commands['default_reply'][
re.compile(matchstr, flags)] = func
logger.info('registered default_reply plugin "%s" to "%s"', func.__name__,
matchstr)
return func
return wrapper if invoked else wrapper(func) | python | def default_reply(*args, **kwargs):
"""
Decorator declaring the wrapped function to the default reply hanlder.
May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or
with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``).
"""
invoked = bool(not args or kwargs)
matchstr = kwargs.pop('matchstr', r'^.*$')
flags = kwargs.pop('flags', 0)
if not invoked:
func = args[0]
def wrapper(func):
PluginsManager.commands['default_reply'][
re.compile(matchstr, flags)] = func
logger.info('registered default_reply plugin "%s" to "%s"', func.__name__,
matchstr)
return func
return wrapper if invoked else wrapper(func) | [
"def",
"default_reply",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"invoked",
"=",
"bool",
"(",
"not",
"args",
"or",
"kwargs",
")",
"matchstr",
"=",
"kwargs",
".",
"pop",
"(",
"'matchstr'",
",",
"r'^.*$'",
")",
"flags",
"=",
"kwargs",
".",
"pop",
"(",
"'flags'",
",",
"0",
")",
"if",
"not",
"invoked",
":",
"func",
"=",
"args",
"[",
"0",
"]",
"def",
"wrapper",
"(",
"func",
")",
":",
"PluginsManager",
".",
"commands",
"[",
"'default_reply'",
"]",
"[",
"re",
".",
"compile",
"(",
"matchstr",
",",
"flags",
")",
"]",
"=",
"func",
"logger",
".",
"info",
"(",
"'registered default_reply plugin \"%s\" to \"%s\"'",
",",
"func",
".",
"__name__",
",",
"matchstr",
")",
"return",
"func",
"return",
"wrapper",
"if",
"invoked",
"else",
"wrapper",
"(",
"func",
")"
] | Decorator declaring the wrapped function to the default reply hanlder.
May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or
with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``). | [
"Decorator",
"declaring",
"the",
"wrapped",
"function",
"to",
"the",
"default",
"reply",
"hanlder",
"."
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/bot.py#L73-L94 |
229,682 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.get_previous_price | def get_previous_price(self, currency, date_obj):
"""
Get Price for one bit coin on given date
"""
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if self._force_decimal:
return Decimal(price)
return price
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def get_previous_price(self, currency, date_obj):
"""
Get Price for one bit coin on given date
"""
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if self._force_decimal:
return Decimal(price)
return price
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"get_previous_price",
"(",
"self",
",",
"currency",
",",
"date_obj",
")",
":",
"start",
"=",
"date_obj",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"end",
"=",
"date_obj",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"url",
"=",
"(",
"'https://api.coindesk.com/v1/bpi/historical/close.json'",
"'?start={}&end={}¤cy={}'",
".",
"format",
"(",
"start",
",",
"end",
",",
"currency",
")",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"price",
"=",
"data",
".",
"get",
"(",
"'bpi'",
",",
"{",
"}",
")",
".",
"get",
"(",
"start",
",",
"None",
")",
"if",
"self",
".",
"_force_decimal",
":",
"return",
"Decimal",
"(",
"price",
")",
"return",
"price",
"raise",
"RatesNotAvailableError",
"(",
"\"BitCoin Rates Source Not Ready For Given date\"",
")"
] | Get Price for one bit coin on given date | [
"Get",
"Price",
"for",
"one",
"bit",
"coin",
"on",
"given",
"date"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L35-L54 |
229,683 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.get_previous_price_list | def get_previous_price_list(self, currency, start_date, end_date):
"""
Get List of prices between two dates
"""
start = start_date.strftime('%Y-%m-%d')
end = end_date.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = self._decode_rates(response)
price_dict = data.get('bpi', {})
return price_dict
return {} | python | def get_previous_price_list(self, currency, start_date, end_date):
"""
Get List of prices between two dates
"""
start = start_date.strftime('%Y-%m-%d')
end = end_date.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = self._decode_rates(response)
price_dict = data.get('bpi', {})
return price_dict
return {} | [
"def",
"get_previous_price_list",
"(",
"self",
",",
"currency",
",",
"start_date",
",",
"end_date",
")",
":",
"start",
"=",
"start_date",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"end",
"=",
"end_date",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"url",
"=",
"(",
"'https://api.coindesk.com/v1/bpi/historical/close.json'",
"'?start={}&end={}¤cy={}'",
".",
"format",
"(",
"start",
",",
"end",
",",
"currency",
")",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"self",
".",
"_decode_rates",
"(",
"response",
")",
"price_dict",
"=",
"data",
".",
"get",
"(",
"'bpi'",
",",
"{",
"}",
")",
"return",
"price_dict",
"return",
"{",
"}"
] | Get List of prices between two dates | [
"Get",
"List",
"of",
"prices",
"between",
"two",
"dates"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L56-L73 |
229,684 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_to_btc | def convert_to_btc(self, amount, currency):
"""
Convert X amount to Bit Coins
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def convert_to_btc(self, amount, currency):
"""
Convert X amount to Bit Coins
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"convert_to_btc",
"(",
"self",
",",
"amount",
",",
"currency",
")",
":",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"url",
"=",
"'https://api.coindesk.com/v1/bpi/currentprice/{}.json'",
".",
"format",
"(",
"currency",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"price",
"=",
"data",
".",
"get",
"(",
"'bpi'",
")",
".",
"get",
"(",
"currency",
",",
"{",
"}",
")",
".",
"get",
"(",
"'rate_float'",
",",
"None",
")",
"if",
"price",
":",
"if",
"use_decimal",
":",
"price",
"=",
"Decimal",
"(",
"price",
")",
"try",
":",
"converted_btc",
"=",
"amount",
"/",
"price",
"return",
"converted_btc",
"except",
"TypeError",
":",
"raise",
"DecimalFloatMismatchError",
"(",
"\"convert_to_btc requires amount parameter is of type Decimal when force_decimal=True\"",
")",
"raise",
"RatesNotAvailableError",
"(",
"\"BitCoin Rates Source Not Ready For Given date\"",
")"
] | Convert X amount to Bit Coins | [
"Convert",
"X",
"amount",
"to",
"Bit",
"Coins"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L75-L97 |
229,685 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_btc_to_cur | def convert_btc_to_cur(self, coins, currency):
"""
Convert X bit coins to valid currency amount
"""
if isinstance(coins, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_amount = coins * price
return converted_amount
except TypeError:
raise DecimalFloatMismatchError("convert_btc_to_cur requires coins parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def convert_btc_to_cur(self, coins, currency):
"""
Convert X bit coins to valid currency amount
"""
if isinstance(coins, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_amount = coins * price
return converted_amount
except TypeError:
raise DecimalFloatMismatchError("convert_btc_to_cur requires coins parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"convert_btc_to_cur",
"(",
"self",
",",
"coins",
",",
"currency",
")",
":",
"if",
"isinstance",
"(",
"coins",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"url",
"=",
"'https://api.coindesk.com/v1/bpi/currentprice/{}.json'",
".",
"format",
"(",
"currency",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"price",
"=",
"data",
".",
"get",
"(",
"'bpi'",
")",
".",
"get",
"(",
"currency",
",",
"{",
"}",
")",
".",
"get",
"(",
"'rate_float'",
",",
"None",
")",
"if",
"price",
":",
"if",
"use_decimal",
":",
"price",
"=",
"Decimal",
"(",
"price",
")",
"try",
":",
"converted_amount",
"=",
"coins",
"*",
"price",
"return",
"converted_amount",
"except",
"TypeError",
":",
"raise",
"DecimalFloatMismatchError",
"(",
"\"convert_btc_to_cur requires coins parameter is of type Decimal when force_decimal=True\"",
")",
"raise",
"RatesNotAvailableError",
"(",
"\"BitCoin Rates Source Not Ready For Given date\"",
")"
] | Convert X bit coins to valid currency amount | [
"Convert",
"X",
"bit",
"coins",
"to",
"valid",
"currency",
"amount"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L99-L121 |
229,686 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_to_btc_on | def convert_to_btc_on(self, amount, currency, date_obj):
"""
Convert X amount to BTC based on given date rate
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date") | python | def convert_to_btc_on(self, amount, currency, date_obj):
"""
Convert X amount to BTC based on given date rate
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date") | [
"def",
"convert_to_btc_on",
"(",
"self",
",",
"amount",
",",
"currency",
",",
"date_obj",
")",
":",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"start",
"=",
"date_obj",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"end",
"=",
"date_obj",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"url",
"=",
"(",
"'https://api.coindesk.com/v1/bpi/historical/close.json'",
"'?start={}&end={}¤cy={}'",
".",
"format",
"(",
"start",
",",
"end",
",",
"currency",
")",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"price",
"=",
"data",
".",
"get",
"(",
"'bpi'",
",",
"{",
"}",
")",
".",
"get",
"(",
"start",
",",
"None",
")",
"if",
"price",
":",
"if",
"use_decimal",
":",
"price",
"=",
"Decimal",
"(",
"price",
")",
"try",
":",
"converted_btc",
"=",
"amount",
"/",
"price",
"return",
"converted_btc",
"except",
"TypeError",
":",
"raise",
"DecimalFloatMismatchError",
"(",
"\"convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True\"",
")",
"raise",
"RatesNotAvailableError",
"(",
"\"BitCoin Rates Source Not Ready For Given Date\"",
")"
] | Convert X amount to BTC based on given date rate | [
"Convert",
"X",
"amount",
"to",
"BTC",
"based",
"on",
"given",
"date",
"rate"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L123-L152 |
229,687 | DocNow/twarc | twarc/decorators.py | rate_limit | def rate_limit(f):
"""
A decorator to handle rate limiting from the Twitter API. If
a rate limit error is encountered we will sleep until we can
issue the API call again.
"""
def new_f(*args, **kwargs):
errors = 0
while True:
resp = f(*args, **kwargs)
if resp.status_code == 200:
errors = 0
return resp
elif resp.status_code == 401:
# Hack to retain the original exception, but augment it with
# additional context for the user to interpret it. In a Python
# 3 only future we can raise a new exception of the same type
# with a new message from the old error.
try:
resp.raise_for_status()
except requests.HTTPError as e:
message = "\nThis is a protected or locked account, or" +\
" the credentials provided are no longer valid."
e.args = (e.args[0] + message,) + e.args[1:]
log.warning("401 Authentication required for %s", resp.url)
raise
elif resp.status_code == 429:
reset = int(resp.headers['x-rate-limit-reset'])
now = time.time()
seconds = reset - now + 10
if seconds < 1:
seconds = 10
log.warning("rate limit exceeded: sleeping %s secs", seconds)
time.sleep(seconds)
elif resp.status_code >= 500:
errors += 1
if errors > 30:
log.warning("too many errors from Twitter, giving up")
resp.raise_for_status()
seconds = 60 * errors
log.warning("%s from Twitter API, sleeping %s",
resp.status_code, seconds)
time.sleep(seconds)
else:
resp.raise_for_status()
return new_f | python | def rate_limit(f):
"""
A decorator to handle rate limiting from the Twitter API. If
a rate limit error is encountered we will sleep until we can
issue the API call again.
"""
def new_f(*args, **kwargs):
errors = 0
while True:
resp = f(*args, **kwargs)
if resp.status_code == 200:
errors = 0
return resp
elif resp.status_code == 401:
# Hack to retain the original exception, but augment it with
# additional context for the user to interpret it. In a Python
# 3 only future we can raise a new exception of the same type
# with a new message from the old error.
try:
resp.raise_for_status()
except requests.HTTPError as e:
message = "\nThis is a protected or locked account, or" +\
" the credentials provided are no longer valid."
e.args = (e.args[0] + message,) + e.args[1:]
log.warning("401 Authentication required for %s", resp.url)
raise
elif resp.status_code == 429:
reset = int(resp.headers['x-rate-limit-reset'])
now = time.time()
seconds = reset - now + 10
if seconds < 1:
seconds = 10
log.warning("rate limit exceeded: sleeping %s secs", seconds)
time.sleep(seconds)
elif resp.status_code >= 500:
errors += 1
if errors > 30:
log.warning("too many errors from Twitter, giving up")
resp.raise_for_status()
seconds = 60 * errors
log.warning("%s from Twitter API, sleeping %s",
resp.status_code, seconds)
time.sleep(seconds)
else:
resp.raise_for_status()
return new_f | [
"def",
"rate_limit",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"errors",
"=",
"0",
"return",
"resp",
"elif",
"resp",
".",
"status_code",
"==",
"401",
":",
"# Hack to retain the original exception, but augment it with",
"# additional context for the user to interpret it. In a Python",
"# 3 only future we can raise a new exception of the same type",
"# with a new message from the old error.",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"message",
"=",
"\"\\nThis is a protected or locked account, or\"",
"+",
"\" the credentials provided are no longer valid.\"",
"e",
".",
"args",
"=",
"(",
"e",
".",
"args",
"[",
"0",
"]",
"+",
"message",
",",
")",
"+",
"e",
".",
"args",
"[",
"1",
":",
"]",
"log",
".",
"warning",
"(",
"\"401 Authentication required for %s\"",
",",
"resp",
".",
"url",
")",
"raise",
"elif",
"resp",
".",
"status_code",
"==",
"429",
":",
"reset",
"=",
"int",
"(",
"resp",
".",
"headers",
"[",
"'x-rate-limit-reset'",
"]",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"seconds",
"=",
"reset",
"-",
"now",
"+",
"10",
"if",
"seconds",
"<",
"1",
":",
"seconds",
"=",
"10",
"log",
".",
"warning",
"(",
"\"rate limit exceeded: sleeping %s secs\"",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"elif",
"resp",
".",
"status_code",
">=",
"500",
":",
"errors",
"+=",
"1",
"if",
"errors",
">",
"30",
":",
"log",
".",
"warning",
"(",
"\"too many errors from Twitter, giving up\"",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"seconds",
"=",
"60",
"*",
"errors",
"log",
".",
"warning",
"(",
"\"%s from Twitter API, sleeping %s\"",
",",
"resp",
".",
"status_code",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"else",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"new_f"
] | A decorator to handle rate limiting from the Twitter API. If
a rate limit error is encountered we will sleep until we can
issue the API call again. | [
"A",
"decorator",
"to",
"handle",
"rate",
"limiting",
"from",
"the",
"Twitter",
"API",
".",
"If",
"a",
"rate",
"limit",
"error",
"is",
"encountered",
"we",
"will",
"sleep",
"until",
"we",
"can",
"issue",
"the",
"API",
"call",
"again",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L8-L53 |
229,688 | DocNow/twarc | twarc/decorators.py | catch_timeout | def catch_timeout(f):
"""
A decorator to handle read timeouts from Twitter.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except (requests.exceptions.ReadTimeout,
requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
log.warning("caught read timeout: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | python | def catch_timeout(f):
"""
A decorator to handle read timeouts from Twitter.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except (requests.exceptions.ReadTimeout,
requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
log.warning("caught read timeout: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | [
"def",
"catch_timeout",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"requests",
".",
"exceptions",
".",
"ReadTimeout",
",",
"requests",
".",
"packages",
".",
"urllib3",
".",
"exceptions",
".",
"ReadTimeoutError",
")",
"as",
"e",
":",
"log",
".",
"warning",
"(",
"\"caught read timeout: %s\"",
",",
"e",
")",
"self",
".",
"connect",
"(",
")",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_f"
] | A decorator to handle read timeouts from Twitter. | [
"A",
"decorator",
"to",
"handle",
"read",
"timeouts",
"from",
"Twitter",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L81-L93 |
229,689 | DocNow/twarc | twarc/decorators.py | catch_gzip_errors | def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warning("caught gzip error: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | python | def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warning("caught gzip error: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | [
"def",
"catch_gzip_errors",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"requests",
".",
"exceptions",
".",
"ContentDecodingError",
"as",
"e",
":",
"log",
".",
"warning",
"(",
"\"caught gzip error: %s\"",
",",
"e",
")",
"self",
".",
"connect",
"(",
")",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_f"
] | A decorator to handle gzip encoding errors which have been known to
happen during hydration. | [
"A",
"decorator",
"to",
"handle",
"gzip",
"encoding",
"errors",
"which",
"have",
"been",
"known",
"to",
"happen",
"during",
"hydration",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L96-L108 |
229,690 | DocNow/twarc | twarc/decorators.py | interruptible_sleep | def interruptible_sleep(t, event=None):
"""
Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted
"""
log.info("sleeping %s", t)
if event is None:
time.sleep(t)
return False
else:
return not event.wait(t) | python | def interruptible_sleep(t, event=None):
"""
Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted
"""
log.info("sleeping %s", t)
if event is None:
time.sleep(t)
return False
else:
return not event.wait(t) | [
"def",
"interruptible_sleep",
"(",
"t",
",",
"event",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"sleeping %s\"",
",",
"t",
")",
"if",
"event",
"is",
"None",
":",
"time",
".",
"sleep",
"(",
"t",
")",
"return",
"False",
"else",
":",
"return",
"not",
"event",
".",
"wait",
"(",
"t",
")"
] | Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted | [
"Sleeps",
"for",
"a",
"specified",
"duration",
"optionally",
"stopping",
"early",
"for",
"event",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L111-L123 |
229,691 | DocNow/twarc | twarc/decorators.py | filter_protected | def filter_protected(f):
"""
filter_protected will filter out protected tweets and users unless
explicitly requested not to.
"""
def new_f(self, *args, **kwargs):
for obj in f(self, *args, **kwargs):
if self.protected == False:
if 'user' in obj and obj['user']['protected']:
continue
elif 'protected' in obj and obj['protected']:
continue
yield obj
return new_f | python | def filter_protected(f):
"""
filter_protected will filter out protected tweets and users unless
explicitly requested not to.
"""
def new_f(self, *args, **kwargs):
for obj in f(self, *args, **kwargs):
if self.protected == False:
if 'user' in obj and obj['user']['protected']:
continue
elif 'protected' in obj and obj['protected']:
continue
yield obj
return new_f | [
"def",
"filter_protected",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"obj",
"in",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"protected",
"==",
"False",
":",
"if",
"'user'",
"in",
"obj",
"and",
"obj",
"[",
"'user'",
"]",
"[",
"'protected'",
"]",
":",
"continue",
"elif",
"'protected'",
"in",
"obj",
"and",
"obj",
"[",
"'protected'",
"]",
":",
"continue",
"yield",
"obj",
"return",
"new_f"
] | filter_protected will filter out protected tweets and users unless
explicitly requested not to. | [
"filter_protected",
"will",
"filter",
"out",
"protected",
"tweets",
"and",
"users",
"unless",
"explicitly",
"requested",
"not",
"to",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L125-L139 |
229,692 | DocNow/twarc | utils/extractor.py | tweets_files | def tweets_files(string, path):
"""Iterates over json files in path."""
for filename in os.listdir(path):
if re.match(string, filename) and ".jsonl" in filename:
f = gzip.open if ".gz" in filename else open
yield path + filename, f
Ellipsis | python | def tweets_files(string, path):
"""Iterates over json files in path."""
for filename in os.listdir(path):
if re.match(string, filename) and ".jsonl" in filename:
f = gzip.open if ".gz" in filename else open
yield path + filename, f
Ellipsis | [
"def",
"tweets_files",
"(",
"string",
",",
"path",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"re",
".",
"match",
"(",
"string",
",",
"filename",
")",
"and",
"\".jsonl\"",
"in",
"filename",
":",
"f",
"=",
"gzip",
".",
"open",
"if",
"\".gz\"",
"in",
"filename",
"else",
"open",
"yield",
"path",
"+",
"filename",
",",
"f",
"Ellipsis"
] | Iterates over json files in path. | [
"Iterates",
"over",
"json",
"files",
"in",
"path",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/extractor.py#L38-L45 |
229,693 | DocNow/twarc | utils/extractor.py | extract | def extract(json_object, args, csv_writer):
"""Extract and write found attributes."""
found = [[]]
for attribute in args.attributes:
item = attribute.getElement(json_object)
if len(item) == 0:
for row in found:
row.append("NA")
else:
found1 = []
for value in item:
if value is None:
value = "NA"
new = copy.deepcopy(found)
for row in new:
row.append(value)
found1.extend(new)
found = found1
for row in found:
csv_writer.writerow(row)
return len(found) | python | def extract(json_object, args, csv_writer):
"""Extract and write found attributes."""
found = [[]]
for attribute in args.attributes:
item = attribute.getElement(json_object)
if len(item) == 0:
for row in found:
row.append("NA")
else:
found1 = []
for value in item:
if value is None:
value = "NA"
new = copy.deepcopy(found)
for row in new:
row.append(value)
found1.extend(new)
found = found1
for row in found:
csv_writer.writerow(row)
return len(found) | [
"def",
"extract",
"(",
"json_object",
",",
"args",
",",
"csv_writer",
")",
":",
"found",
"=",
"[",
"[",
"]",
"]",
"for",
"attribute",
"in",
"args",
".",
"attributes",
":",
"item",
"=",
"attribute",
".",
"getElement",
"(",
"json_object",
")",
"if",
"len",
"(",
"item",
")",
"==",
"0",
":",
"for",
"row",
"in",
"found",
":",
"row",
".",
"append",
"(",
"\"NA\"",
")",
"else",
":",
"found1",
"=",
"[",
"]",
"for",
"value",
"in",
"item",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"\"NA\"",
"new",
"=",
"copy",
".",
"deepcopy",
"(",
"found",
")",
"for",
"row",
"in",
"new",
":",
"row",
".",
"append",
"(",
"value",
")",
"found1",
".",
"extend",
"(",
"new",
")",
"found",
"=",
"found1",
"for",
"row",
"in",
"found",
":",
"csv_writer",
".",
"writerow",
"(",
"row",
")",
"return",
"len",
"(",
"found",
")"
] | Extract and write found attributes. | [
"Extract",
"and",
"write",
"found",
"attributes",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/extractor.py#L91-L113 |
229,694 | DocNow/twarc | utils/network.py | add | def add(from_user, from_id, to_user, to_id, type):
"adds a relation to the graph"
if options.users and to_user:
G.add_node(from_user, screen_name=from_user)
G.add_node(to_user, screen_name=to_user)
if G.has_edge(from_user, to_user):
weight = G[from_user][to_user]['weight'] + 1
else:
weight = 1
G.add_edge(from_user, to_user, type=type, weight=weight)
elif not options.users and to_id:
G.add_node(from_id, screen_name=from_user, type=type)
if to_user:
G.add_node(to_id, screen_name=to_user)
else:
G.add_node(to_id)
G.add_edge(from_id, to_id, type=type) | python | def add(from_user, from_id, to_user, to_id, type):
"adds a relation to the graph"
if options.users and to_user:
G.add_node(from_user, screen_name=from_user)
G.add_node(to_user, screen_name=to_user)
if G.has_edge(from_user, to_user):
weight = G[from_user][to_user]['weight'] + 1
else:
weight = 1
G.add_edge(from_user, to_user, type=type, weight=weight)
elif not options.users and to_id:
G.add_node(from_id, screen_name=from_user, type=type)
if to_user:
G.add_node(to_id, screen_name=to_user)
else:
G.add_node(to_id)
G.add_edge(from_id, to_id, type=type) | [
"def",
"add",
"(",
"from_user",
",",
"from_id",
",",
"to_user",
",",
"to_id",
",",
"type",
")",
":",
"if",
"options",
".",
"users",
"and",
"to_user",
":",
"G",
".",
"add_node",
"(",
"from_user",
",",
"screen_name",
"=",
"from_user",
")",
"G",
".",
"add_node",
"(",
"to_user",
",",
"screen_name",
"=",
"to_user",
")",
"if",
"G",
".",
"has_edge",
"(",
"from_user",
",",
"to_user",
")",
":",
"weight",
"=",
"G",
"[",
"from_user",
"]",
"[",
"to_user",
"]",
"[",
"'weight'",
"]",
"+",
"1",
"else",
":",
"weight",
"=",
"1",
"G",
".",
"add_edge",
"(",
"from_user",
",",
"to_user",
",",
"type",
"=",
"type",
",",
"weight",
"=",
"weight",
")",
"elif",
"not",
"options",
".",
"users",
"and",
"to_id",
":",
"G",
".",
"add_node",
"(",
"from_id",
",",
"screen_name",
"=",
"from_user",
",",
"type",
"=",
"type",
")",
"if",
"to_user",
":",
"G",
".",
"add_node",
"(",
"to_id",
",",
"screen_name",
"=",
"to_user",
")",
"else",
":",
"G",
".",
"add_node",
"(",
"to_id",
")",
"G",
".",
"add_edge",
"(",
"from_id",
",",
"to_id",
",",
"type",
"=",
"type",
")"
] | adds a relation to the graph | [
"adds",
"a",
"relation",
"to",
"the",
"graph"
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/network.py#L72-L91 |
229,695 | DocNow/twarc | twarc/client.py | Twarc.timeline | def timeline(self, user_id=None, screen_name=None, max_id=None,
since_id=None, max_pages=None):
"""
Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name.
"""
if user_id and screen_name:
raise ValueError('only user_id or screen_name may be passed')
# Strip if screen_name is prefixed with '@'
if screen_name:
screen_name = screen_name.lstrip('@')
id = screen_name or str(user_id)
id_type = "screen_name" if screen_name else "user_id"
log.info("starting user timeline for user %s", id)
if screen_name or user_id:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
else:
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {"count": 200, id_type: id, "include_ext_alt_text": "true"}
retrieved_pages = 0
reached_end = False
while True:
if since_id:
# Make the since_id inclusive, so we can avoid retrieving
# an empty page of results in some cases
params['since_id'] = str(int(since_id) - 1)
if max_id:
params['max_id'] = max_id
try:
resp = self.get(url, params=params, allow_404=True)
retrieved_pages += 1
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.warn("no timeline available for %s", id)
break
elif e.response.status_code == 401:
log.warn("protected account %s", id)
break
raise e
statuses = resp.json()
if len(statuses) == 0:
log.info("no new tweets matching %s", params)
break
for status in statuses:
# We've certainly reached the end of new results
if since_id is not None and status['id_str'] == str(since_id):
reached_end = True
break
# If you request an invalid user_id, you may still get
# results so need to check.
if not user_id or id == status.get("user",
{}).get("id_str"):
yield status
if reached_end:
log.info("no new tweets matching %s", params)
break
if max_pages is not None and retrieved_pages == max_pages:
log.info("reached max page limit for %s", params)
break
max_id = str(int(status["id_str"]) - 1) | python | def timeline(self, user_id=None, screen_name=None, max_id=None,
since_id=None, max_pages=None):
"""
Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name.
"""
if user_id and screen_name:
raise ValueError('only user_id or screen_name may be passed')
# Strip if screen_name is prefixed with '@'
if screen_name:
screen_name = screen_name.lstrip('@')
id = screen_name or str(user_id)
id_type = "screen_name" if screen_name else "user_id"
log.info("starting user timeline for user %s", id)
if screen_name or user_id:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
else:
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {"count": 200, id_type: id, "include_ext_alt_text": "true"}
retrieved_pages = 0
reached_end = False
while True:
if since_id:
# Make the since_id inclusive, so we can avoid retrieving
# an empty page of results in some cases
params['since_id'] = str(int(since_id) - 1)
if max_id:
params['max_id'] = max_id
try:
resp = self.get(url, params=params, allow_404=True)
retrieved_pages += 1
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.warn("no timeline available for %s", id)
break
elif e.response.status_code == 401:
log.warn("protected account %s", id)
break
raise e
statuses = resp.json()
if len(statuses) == 0:
log.info("no new tweets matching %s", params)
break
for status in statuses:
# We've certainly reached the end of new results
if since_id is not None and status['id_str'] == str(since_id):
reached_end = True
break
# If you request an invalid user_id, you may still get
# results so need to check.
if not user_id or id == status.get("user",
{}).get("id_str"):
yield status
if reached_end:
log.info("no new tweets matching %s", params)
break
if max_pages is not None and retrieved_pages == max_pages:
log.info("reached max page limit for %s", params)
break
max_id = str(int(status["id_str"]) - 1) | [
"def",
"timeline",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"max_pages",
"=",
"None",
")",
":",
"if",
"user_id",
"and",
"screen_name",
":",
"raise",
"ValueError",
"(",
"'only user_id or screen_name may be passed'",
")",
"# Strip if screen_name is prefixed with '@'",
"if",
"screen_name",
":",
"screen_name",
"=",
"screen_name",
".",
"lstrip",
"(",
"'@'",
")",
"id",
"=",
"screen_name",
"or",
"str",
"(",
"user_id",
")",
"id_type",
"=",
"\"screen_name\"",
"if",
"screen_name",
"else",
"\"user_id\"",
"log",
".",
"info",
"(",
"\"starting user timeline for user %s\"",
",",
"id",
")",
"if",
"screen_name",
"or",
"user_id",
":",
"url",
"=",
"\"https://api.twitter.com/1.1/statuses/user_timeline.json\"",
"else",
":",
"url",
"=",
"\"https://api.twitter.com/1.1/statuses/home_timeline.json\"",
"params",
"=",
"{",
"\"count\"",
":",
"200",
",",
"id_type",
":",
"id",
",",
"\"include_ext_alt_text\"",
":",
"\"true\"",
"}",
"retrieved_pages",
"=",
"0",
"reached_end",
"=",
"False",
"while",
"True",
":",
"if",
"since_id",
":",
"# Make the since_id inclusive, so we can avoid retrieving",
"# an empty page of results in some cases",
"params",
"[",
"'since_id'",
"]",
"=",
"str",
"(",
"int",
"(",
"since_id",
")",
"-",
"1",
")",
"if",
"max_id",
":",
"params",
"[",
"'max_id'",
"]",
"=",
"max_id",
"try",
":",
"resp",
"=",
"self",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
",",
"allow_404",
"=",
"True",
")",
"retrieved_pages",
"+=",
"1",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"if",
"e",
".",
"response",
".",
"status_code",
"==",
"404",
":",
"log",
".",
"warn",
"(",
"\"no timeline available for %s\"",
",",
"id",
")",
"break",
"elif",
"e",
".",
"response",
".",
"status_code",
"==",
"401",
":",
"log",
".",
"warn",
"(",
"\"protected account %s\"",
",",
"id",
")",
"break",
"raise",
"e",
"statuses",
"=",
"resp",
".",
"json",
"(",
")",
"if",
"len",
"(",
"statuses",
")",
"==",
"0",
":",
"log",
".",
"info",
"(",
"\"no new tweets matching %s\"",
",",
"params",
")",
"break",
"for",
"status",
"in",
"statuses",
":",
"# We've certainly reached the end of new results",
"if",
"since_id",
"is",
"not",
"None",
"and",
"status",
"[",
"'id_str'",
"]",
"==",
"str",
"(",
"since_id",
")",
":",
"reached_end",
"=",
"True",
"break",
"# If you request an invalid user_id, you may still get",
"# results so need to check.",
"if",
"not",
"user_id",
"or",
"id",
"==",
"status",
".",
"get",
"(",
"\"user\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"id_str\"",
")",
":",
"yield",
"status",
"if",
"reached_end",
":",
"log",
".",
"info",
"(",
"\"no new tweets matching %s\"",
",",
"params",
")",
"break",
"if",
"max_pages",
"is",
"not",
"None",
"and",
"retrieved_pages",
"==",
"max_pages",
":",
"log",
".",
"info",
"(",
"\"reached max page limit for %s\"",
",",
"params",
")",
"break",
"max_id",
"=",
"str",
"(",
"int",
"(",
"status",
"[",
"\"id_str\"",
"]",
")",
"-",
"1",
")"
] | Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name. | [
"Returns",
"a",
"collection",
"of",
"the",
"most",
"recent",
"tweets",
"posted",
"by",
"the",
"user",
"indicated",
"by",
"the",
"user_id",
"or",
"screen_name",
"parameter",
".",
"Provide",
"a",
"user_id",
"or",
"screen_name",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L138-L211 |
229,696 | DocNow/twarc | twarc/client.py | Twarc.follower_ids | def follower_ids(self, user):
"""
Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id
"""
user = str(user)
user = user.lstrip('@')
url = 'https://api.twitter.com/1.1/followers/ids.json'
if re.match(r'^\d+$', user):
params = {'user_id': user, 'cursor': -1}
else:
params = {'screen_name': user, 'cursor': -1}
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no users matching %s", screen_name)
raise e
user_ids = resp.json()
for user_id in user_ids['ids']:
yield str_type(user_id)
params['cursor'] = user_ids['next_cursor'] | python | def follower_ids(self, user):
"""
Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id
"""
user = str(user)
user = user.lstrip('@')
url = 'https://api.twitter.com/1.1/followers/ids.json'
if re.match(r'^\d+$', user):
params = {'user_id': user, 'cursor': -1}
else:
params = {'screen_name': user, 'cursor': -1}
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no users matching %s", screen_name)
raise e
user_ids = resp.json()
for user_id in user_ids['ids']:
yield str_type(user_id)
params['cursor'] = user_ids['next_cursor'] | [
"def",
"follower_ids",
"(",
"self",
",",
"user",
")",
":",
"user",
"=",
"str",
"(",
"user",
")",
"user",
"=",
"user",
".",
"lstrip",
"(",
"'@'",
")",
"url",
"=",
"'https://api.twitter.com/1.1/followers/ids.json'",
"if",
"re",
".",
"match",
"(",
"r'^\\d+$'",
",",
"user",
")",
":",
"params",
"=",
"{",
"'user_id'",
":",
"user",
",",
"'cursor'",
":",
"-",
"1",
"}",
"else",
":",
"params",
"=",
"{",
"'screen_name'",
":",
"user",
",",
"'cursor'",
":",
"-",
"1",
"}",
"while",
"params",
"[",
"'cursor'",
"]",
"!=",
"0",
":",
"try",
":",
"resp",
"=",
"self",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
",",
"allow_404",
"=",
"True",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"if",
"e",
".",
"response",
".",
"status_code",
"==",
"404",
":",
"log",
".",
"info",
"(",
"\"no users matching %s\"",
",",
"screen_name",
")",
"raise",
"e",
"user_ids",
"=",
"resp",
".",
"json",
"(",
")",
"for",
"user_id",
"in",
"user_ids",
"[",
"'ids'",
"]",
":",
"yield",
"str_type",
"(",
"user_id",
")",
"params",
"[",
"'cursor'",
"]",
"=",
"user_ids",
"[",
"'next_cursor'",
"]"
] | Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id | [
"Returns",
"Twitter",
"user",
"id",
"lists",
"for",
"the",
"specified",
"user",
"s",
"followers",
".",
"A",
"user",
"can",
"be",
"a",
"specific",
"using",
"their",
"screen_name",
"or",
"user_id"
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L254-L278 |
229,697 | DocNow/twarc | twarc/client.py | Twarc.filter | def filter(self, track=None, follow=None, locations=None, event=None,
record_keepalive=False):
"""
Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is set,
the filter will be interrupted.
"""
if locations is not None:
if type(locations) == list:
locations = ','.join(locations)
locations = locations.replace('\\', '')
url = 'https://stream.twitter.com/1.1/statuses/filter.json'
params = {
"stall_warning": True,
"include_ext_alt_text": True
}
if track:
params["track"] = track
if follow:
params["follow"] = follow
if locations:
params["locations"] = locations
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to filter stream for %s", params)
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=1024):
if event and event.is_set():
log.info("stopping filter")
# Explicitly close response
resp.close()
return
if not line:
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many exceptions")
raise e
log.error(e)
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | python | def filter(self, track=None, follow=None, locations=None, event=None,
record_keepalive=False):
"""
Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is set,
the filter will be interrupted.
"""
if locations is not None:
if type(locations) == list:
locations = ','.join(locations)
locations = locations.replace('\\', '')
url = 'https://stream.twitter.com/1.1/statuses/filter.json'
params = {
"stall_warning": True,
"include_ext_alt_text": True
}
if track:
params["track"] = track
if follow:
params["follow"] = follow
if locations:
params["locations"] = locations
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to filter stream for %s", params)
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=1024):
if event and event.is_set():
log.info("stopping filter")
# Explicitly close response
resp.close()
return
if not line:
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many exceptions")
raise e
log.error(e)
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | [
"def",
"filter",
"(",
"self",
",",
"track",
"=",
"None",
",",
"follow",
"=",
"None",
",",
"locations",
"=",
"None",
",",
"event",
"=",
"None",
",",
"record_keepalive",
"=",
"False",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"if",
"type",
"(",
"locations",
")",
"==",
"list",
":",
"locations",
"=",
"','",
".",
"join",
"(",
"locations",
")",
"locations",
"=",
"locations",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
"url",
"=",
"'https://stream.twitter.com/1.1/statuses/filter.json'",
"params",
"=",
"{",
"\"stall_warning\"",
":",
"True",
",",
"\"include_ext_alt_text\"",
":",
"True",
"}",
"if",
"track",
":",
"params",
"[",
"\"track\"",
"]",
"=",
"track",
"if",
"follow",
":",
"params",
"[",
"\"follow\"",
"]",
"=",
"follow",
"if",
"locations",
":",
"params",
"[",
"\"locations\"",
"]",
"=",
"locations",
"headers",
"=",
"{",
"'accept-encoding'",
":",
"'deflate, gzip'",
"}",
"errors",
"=",
"0",
"while",
"True",
":",
"try",
":",
"log",
".",
"info",
"(",
"\"connecting to filter stream for %s\"",
",",
"params",
")",
"resp",
"=",
"self",
".",
"post",
"(",
"url",
",",
"params",
",",
"headers",
"=",
"headers",
",",
"stream",
"=",
"True",
")",
"errors",
"=",
"0",
"for",
"line",
"in",
"resp",
".",
"iter_lines",
"(",
"chunk_size",
"=",
"1024",
")",
":",
"if",
"event",
"and",
"event",
".",
"is_set",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"stopping filter\"",
")",
"# Explicitly close response",
"resp",
".",
"close",
"(",
")",
"return",
"if",
"not",
"line",
":",
"log",
".",
"info",
"(",
"\"keep-alive\"",
")",
"if",
"record_keepalive",
":",
"yield",
"\"keep-alive\"",
"continue",
"try",
":",
"yield",
"json",
".",
"loads",
"(",
"line",
".",
"decode",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"\"json parse error: %s - %s\"",
",",
"e",
",",
"line",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"errors",
"+=",
"1",
"log",
".",
"error",
"(",
"\"caught http error %s on %s try\"",
",",
"e",
",",
"errors",
")",
"if",
"self",
".",
"http_errors",
"and",
"errors",
"==",
"self",
".",
"http_errors",
":",
"log",
".",
"warning",
"(",
"\"too many errors\"",
")",
"raise",
"e",
"if",
"e",
".",
"response",
".",
"status_code",
"==",
"420",
":",
"if",
"interruptible_sleep",
"(",
"errors",
"*",
"60",
",",
"event",
")",
":",
"log",
".",
"info",
"(",
"\"stopping filter\"",
")",
"return",
"else",
":",
"if",
"interruptible_sleep",
"(",
"errors",
"*",
"5",
",",
"event",
")",
":",
"log",
".",
"info",
"(",
"\"stopping filter\"",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"errors",
"+=",
"1",
"log",
".",
"error",
"(",
"\"caught exception %s on %s try\"",
",",
"e",
",",
"errors",
")",
"if",
"self",
".",
"http_errors",
"and",
"errors",
"==",
"self",
".",
"http_errors",
":",
"log",
".",
"warning",
"(",
"\"too many exceptions\"",
")",
"raise",
"e",
"log",
".",
"error",
"(",
"e",
")",
"if",
"interruptible_sleep",
"(",
"errors",
",",
"event",
")",
":",
"log",
".",
"info",
"(",
"\"stopping filter\"",
")",
"return"
] | Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is set,
the filter will be interrupted. | [
"Returns",
"an",
"iterator",
"for",
"tweets",
"that",
"match",
"a",
"given",
"filter",
"track",
"from",
"the",
"livestream",
"of",
"tweets",
"happening",
"right",
"now",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L308-L378 |
229,698 | DocNow/twarc | twarc/client.py | Twarc.sample | def sample(self, event=None, record_keepalive=False):
"""
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event is provided for event and the event is set,
the sample will be interrupted.
"""
url = 'https://stream.twitter.com/1.1/statuses/sample.json'
params = {"stall_warning": True}
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to sample stream")
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=512):
if event and event.is_set():
log.info("stopping sample")
# Explicitly close response
resp.close()
return
if line == "":
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | python | def sample(self, event=None, record_keepalive=False):
"""
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event is provided for event and the event is set,
the sample will be interrupted.
"""
url = 'https://stream.twitter.com/1.1/statuses/sample.json'
params = {"stall_warning": True}
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to sample stream")
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=512):
if event and event.is_set():
log.info("stopping sample")
# Explicitly close response
resp.close()
return
if line == "":
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | [
"def",
"sample",
"(",
"self",
",",
"event",
"=",
"None",
",",
"record_keepalive",
"=",
"False",
")",
":",
"url",
"=",
"'https://stream.twitter.com/1.1/statuses/sample.json'",
"params",
"=",
"{",
"\"stall_warning\"",
":",
"True",
"}",
"headers",
"=",
"{",
"'accept-encoding'",
":",
"'deflate, gzip'",
"}",
"errors",
"=",
"0",
"while",
"True",
":",
"try",
":",
"log",
".",
"info",
"(",
"\"connecting to sample stream\"",
")",
"resp",
"=",
"self",
".",
"post",
"(",
"url",
",",
"params",
",",
"headers",
"=",
"headers",
",",
"stream",
"=",
"True",
")",
"errors",
"=",
"0",
"for",
"line",
"in",
"resp",
".",
"iter_lines",
"(",
"chunk_size",
"=",
"512",
")",
":",
"if",
"event",
"and",
"event",
".",
"is_set",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"stopping sample\"",
")",
"# Explicitly close response",
"resp",
".",
"close",
"(",
")",
"return",
"if",
"line",
"==",
"\"\"",
":",
"log",
".",
"info",
"(",
"\"keep-alive\"",
")",
"if",
"record_keepalive",
":",
"yield",
"\"keep-alive\"",
"continue",
"try",
":",
"yield",
"json",
".",
"loads",
"(",
"line",
".",
"decode",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"\"json parse error: %s - %s\"",
",",
"e",
",",
"line",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"errors",
"+=",
"1",
"log",
".",
"error",
"(",
"\"caught http error %s on %s try\"",
",",
"e",
",",
"errors",
")",
"if",
"self",
".",
"http_errors",
"and",
"errors",
"==",
"self",
".",
"http_errors",
":",
"log",
".",
"warning",
"(",
"\"too many errors\"",
")",
"raise",
"e",
"if",
"e",
".",
"response",
".",
"status_code",
"==",
"420",
":",
"if",
"interruptible_sleep",
"(",
"errors",
"*",
"60",
",",
"event",
")",
":",
"log",
".",
"info",
"(",
"\"stopping filter\"",
")",
"return",
"else",
":",
"if",
"interruptible_sleep",
"(",
"errors",
"*",
"5",
",",
"event",
")",
":",
"log",
".",
"info",
"(",
"\"stopping filter\"",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"errors",
"+=",
"1",
"log",
".",
"error",
"(",
"\"caught exception %s on %s try\"",
",",
"e",
",",
"errors",
")",
"if",
"self",
".",
"http_errors",
"and",
"errors",
"==",
"self",
".",
"http_errors",
":",
"log",
".",
"warning",
"(",
"\"too many errors\"",
")",
"raise",
"e",
"if",
"interruptible_sleep",
"(",
"errors",
",",
"event",
")",
":",
"log",
".",
"info",
"(",
"\"stopping filter\"",
")",
"return"
] | Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event is provided for event and the event is set,
the sample will be interrupted. | [
"Returns",
"a",
"small",
"random",
"sample",
"of",
"all",
"public",
"statuses",
".",
"The",
"Tweets",
"returned",
"by",
"the",
"default",
"access",
"level",
"are",
"the",
"same",
"so",
"if",
"two",
"different",
"clients",
"connect",
"to",
"this",
"endpoint",
"they",
"will",
"see",
"the",
"same",
"Tweets",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L380-L436 |
229,699 | DocNow/twarc | twarc/client.py | Twarc.dehydrate | def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh: %s\n" % e) | python | def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh: %s\n" % e) | [
"def",
"dehydrate",
"(",
"self",
",",
"iterator",
")",
":",
"for",
"line",
"in",
"iterator",
":",
"try",
":",
"yield",
"json",
".",
"loads",
"(",
"line",
")",
"[",
"'id_str'",
"]",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"\"uhoh: %s\\n\"",
"%",
"e",
")"
] | Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet. | [
"Pass",
"in",
"an",
"iterator",
"of",
"tweets",
"JSON",
"and",
"get",
"back",
"an",
"iterator",
"of",
"the",
"IDs",
"of",
"each",
"tweet",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L438-L447 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.