partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
JsonCodec.decode
|
Convert a generic JSON message
* The entire message is converted to JSON and treated as the message data
* The timestamp of the message is the time that the message is RECEIVED
|
src/wiotp/sdk/messages.py
|
def decode(message):
"""
Convert a generic JSON message
* The entire message is converted to JSON and treated as the message data
* The timestamp of the message is the time that the message is RECEIVED
"""
try:
data = json.loads(message.payload.decode("utf-8"))
except ValueError as e:
raise InvalidEventException('Unable to parse JSON. payload="%s" error=%s' % (message.payload, str(e)))
timestamp = datetime.now(pytz.timezone("UTC"))
# TODO: Flatten JSON, covert into array of key/value pairs
return Message(data, timestamp)
|
def decode(message):
"""
Convert a generic JSON message
* The entire message is converted to JSON and treated as the message data
* The timestamp of the message is the time that the message is RECEIVED
"""
try:
data = json.loads(message.payload.decode("utf-8"))
except ValueError as e:
raise InvalidEventException('Unable to parse JSON. payload="%s" error=%s' % (message.payload, str(e)))
timestamp = datetime.now(pytz.timezone("UTC"))
# TODO: Flatten JSON, covert into array of key/value pairs
return Message(data, timestamp)
|
[
"Convert",
"a",
"generic",
"JSON",
"message",
"*",
"The",
"entire",
"message",
"is",
"converted",
"to",
"JSON",
"and",
"treated",
"as",
"the",
"message",
"data",
"*",
"The",
"timestamp",
"of",
"the",
"message",
"is",
"the",
"time",
"that",
"the",
"message",
"is",
"RECEIVED"
] |
ibm-watson-iot/iot-python
|
python
|
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/messages.py#L43-L58
|
[
"def",
"decode",
"(",
"message",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"message",
".",
"payload",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"InvalidEventException",
"(",
"'Unable to parse JSON. payload=\"%s\" error=%s'",
"%",
"(",
"message",
".",
"payload",
",",
"str",
"(",
"e",
")",
")",
")",
"timestamp",
"=",
"datetime",
".",
"now",
"(",
"pytz",
".",
"timezone",
"(",
"\"UTC\"",
")",
")",
"# TODO: Flatten JSON, covert into array of key/value pairs",
"return",
"Message",
"(",
"data",
",",
"timestamp",
")"
] |
195f05adce3fba4ec997017e41e02ebd85c0c4cc
|
test
|
MyCodec.decode
|
The decoder understands the comma-seperated format produced by the encoder and
allocates the two values to the correct keys:
data['hello'] = 'world'
data['x'] = 10
|
samples/customMessageFormat/myCustomCodec.py
|
def decode(message):
'''
The decoder understands the comma-seperated format produced by the encoder and
allocates the two values to the correct keys:
data['hello'] = 'world'
data['x'] = 10
'''
(hello, x) = message.payload.split(",")
data = {}
data['hello'] = hello
data['x'] = x
timestamp = datetime.now(pytz.timezone('UTC'))
return Message(data, timestamp)
|
def decode(message):
'''
The decoder understands the comma-seperated format produced by the encoder and
allocates the two values to the correct keys:
data['hello'] = 'world'
data['x'] = 10
'''
(hello, x) = message.payload.split(",")
data = {}
data['hello'] = hello
data['x'] = x
timestamp = datetime.now(pytz.timezone('UTC'))
return Message(data, timestamp)
|
[
"The",
"decoder",
"understands",
"the",
"comma",
"-",
"seperated",
"format",
"produced",
"by",
"the",
"encoder",
"and",
"allocates",
"the",
"two",
"values",
"to",
"the",
"correct",
"keys",
":",
"data",
"[",
"hello",
"]",
"=",
"world",
"data",
"[",
"x",
"]",
"=",
"10"
] |
ibm-watson-iot/iot-python
|
python
|
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/samples/customMessageFormat/myCustomCodec.py#L45-L61
|
[
"def",
"decode",
"(",
"message",
")",
":",
"(",
"hello",
",",
"x",
")",
"=",
"message",
".",
"payload",
".",
"split",
"(",
"\",\"",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'hello'",
"]",
"=",
"hello",
"data",
"[",
"'x'",
"]",
"=",
"x",
"timestamp",
"=",
"datetime",
".",
"now",
"(",
"pytz",
".",
"timezone",
"(",
"'UTC'",
")",
")",
"return",
"Message",
"(",
"data",
",",
"timestamp",
")"
] |
195f05adce3fba4ec997017e41e02ebd85c0c4cc
|
test
|
Usage.dataTransfer
|
Retrieve the organization-specific status of each of the services offered by the IBM Watson IoT Platform.
In case of failure it throws APIException
|
src/wiotp/sdk/api/usage/__init__.py
|
def dataTransfer(self, start, end, detail=False):
"""
Retrieve the organization-specific status of each of the services offered by the IBM Watson IoT Platform.
In case of failure it throws APIException
"""
r = self._apiClient.get(
"api/v0002/usage/data-traffic?start=%s&end=%s&detail=%s"
% (start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"), detail)
)
if r.status_code == 200:
return DataTransferSummary(**r.json())
else:
raise ApiException(r)
|
def dataTransfer(self, start, end, detail=False):
"""
Retrieve the organization-specific status of each of the services offered by the IBM Watson IoT Platform.
In case of failure it throws APIException
"""
r = self._apiClient.get(
"api/v0002/usage/data-traffic?start=%s&end=%s&detail=%s"
% (start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"), detail)
)
if r.status_code == 200:
return DataTransferSummary(**r.json())
else:
raise ApiException(r)
|
[
"Retrieve",
"the",
"organization",
"-",
"specific",
"status",
"of",
"each",
"of",
"the",
"services",
"offered",
"by",
"the",
"IBM",
"Watson",
"IoT",
"Platform",
".",
"In",
"case",
"of",
"failure",
"it",
"throws",
"APIException"
] |
ibm-watson-iot/iot-python
|
python
|
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/usage/__init__.py#L62-L76
|
[
"def",
"dataTransfer",
"(",
"self",
",",
"start",
",",
"end",
",",
"detail",
"=",
"False",
")",
":",
"r",
"=",
"self",
".",
"_apiClient",
".",
"get",
"(",
"\"api/v0002/usage/data-traffic?start=%s&end=%s&detail=%s\"",
"%",
"(",
"start",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
",",
"end",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
",",
"detail",
")",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"return",
"DataTransferSummary",
"(",
"*",
"*",
"r",
".",
"json",
"(",
")",
")",
"else",
":",
"raise",
"ApiException",
"(",
"r",
")"
] |
195f05adce3fba4ec997017e41e02ebd85c0c4cc
|
test
|
MgmtRequests.initiate
|
Initiates a device management request, such as reboot.
In case of failure it throws APIException
|
src/wiotp/sdk/api/mgmt/requests.py
|
def initiate(self, request):
"""
Initiates a device management request, such as reboot.
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtRequests
r = self._apiClient.post(url, request)
if r.status_code == 202:
return r.json()
else:
raise ApiException(r)
|
def initiate(self, request):
"""
Initiates a device management request, such as reboot.
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtRequests
r = self._apiClient.post(url, request)
if r.status_code == 202:
return r.json()
else:
raise ApiException(r)
|
[
"Initiates",
"a",
"device",
"management",
"request",
"such",
"as",
"reboot",
".",
"In",
"case",
"of",
"failure",
"it",
"throws",
"APIException"
] |
ibm-watson-iot/iot-python
|
python
|
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/mgmt/requests.py#L45-L56
|
[
"def",
"initiate",
"(",
"self",
",",
"request",
")",
":",
"url",
"=",
"MgmtRequests",
".",
"mgmtRequests",
"r",
"=",
"self",
".",
"_apiClient",
".",
"post",
"(",
"url",
",",
"request",
")",
"if",
"r",
".",
"status_code",
"==",
"202",
":",
"return",
"r",
".",
"json",
"(",
")",
"else",
":",
"raise",
"ApiException",
"(",
"r",
")"
] |
195f05adce3fba4ec997017e41e02ebd85c0c4cc
|
test
|
MgmtRequests.delete
|
Clears the status of a device management request.
You can use this operation to clear the status for a completed request, or for an in-progress request which may never complete due to a problem.
It accepts requestId (string) as parameters
In case of failure it throws APIException
|
src/wiotp/sdk/api/mgmt/requests.py
|
def delete(self, requestId):
"""
Clears the status of a device management request.
You can use this operation to clear the status for a completed request, or for an in-progress request which may never complete due to a problem.
It accepts requestId (string) as parameters
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtSingleRequest % (requestId)
r = self._apiClient.delete(url)
if r.status_code == 204:
return True
else:
raise ApiException(r)
|
def delete(self, requestId):
"""
Clears the status of a device management request.
You can use this operation to clear the status for a completed request, or for an in-progress request which may never complete due to a problem.
It accepts requestId (string) as parameters
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtSingleRequest % (requestId)
r = self._apiClient.delete(url)
if r.status_code == 204:
return True
else:
raise ApiException(r)
|
[
"Clears",
"the",
"status",
"of",
"a",
"device",
"management",
"request",
".",
"You",
"can",
"use",
"this",
"operation",
"to",
"clear",
"the",
"status",
"for",
"a",
"completed",
"request",
"or",
"for",
"an",
"in",
"-",
"progress",
"request",
"which",
"may",
"never",
"complete",
"due",
"to",
"a",
"problem",
".",
"It",
"accepts",
"requestId",
"(",
"string",
")",
"as",
"parameters",
"In",
"case",
"of",
"failure",
"it",
"throws",
"APIException"
] |
ibm-watson-iot/iot-python
|
python
|
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/mgmt/requests.py#L58-L71
|
[
"def",
"delete",
"(",
"self",
",",
"requestId",
")",
":",
"url",
"=",
"MgmtRequests",
".",
"mgmtSingleRequest",
"%",
"(",
"requestId",
")",
"r",
"=",
"self",
".",
"_apiClient",
".",
"delete",
"(",
"url",
")",
"if",
"r",
".",
"status_code",
"==",
"204",
":",
"return",
"True",
"else",
":",
"raise",
"ApiException",
"(",
"r",
")"
] |
195f05adce3fba4ec997017e41e02ebd85c0c4cc
|
test
|
MgmtRequests.get
|
Gets details of a device management request.
It accepts requestId (string) as parameters
In case of failure it throws APIException
|
src/wiotp/sdk/api/mgmt/requests.py
|
def get(self, requestId):
"""
Gets details of a device management request.
It accepts requestId (string) as parameters
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtSingleRequest % (requestId)
r = self._apiClient.get(url)
if r.status_code == 200:
return r.json()
else:
raise ApiException(r)
|
def get(self, requestId):
"""
Gets details of a device management request.
It accepts requestId (string) as parameters
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtSingleRequest % (requestId)
r = self._apiClient.get(url)
if r.status_code == 200:
return r.json()
else:
raise ApiException(r)
|
[
"Gets",
"details",
"of",
"a",
"device",
"management",
"request",
".",
"It",
"accepts",
"requestId",
"(",
"string",
")",
"as",
"parameters",
"In",
"case",
"of",
"failure",
"it",
"throws",
"APIException"
] |
ibm-watson-iot/iot-python
|
python
|
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/mgmt/requests.py#L73-L85
|
[
"def",
"get",
"(",
"self",
",",
"requestId",
")",
":",
"url",
"=",
"MgmtRequests",
".",
"mgmtSingleRequest",
"%",
"(",
"requestId",
")",
"r",
"=",
"self",
".",
"_apiClient",
".",
"get",
"(",
"url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"return",
"r",
".",
"json",
"(",
")",
"else",
":",
"raise",
"ApiException",
"(",
"r",
")"
] |
195f05adce3fba4ec997017e41e02ebd85c0c4cc
|
test
|
MgmtRequests.getStatus
|
Get a list of device management request device statuses.
Get an individual device mangaement request device status.
|
src/wiotp/sdk/api/mgmt/requests.py
|
def getStatus(self, requestId, typeId=None, deviceId=None):
"""
Get a list of device management request device statuses.
Get an individual device mangaement request device status.
"""
if typeId is None or deviceId is None:
url = MgmtRequests.mgmtRequestStatus % (requestId)
r = self._apiClient.get(url)
if r.status_code == 200:
return r.json()
else:
raise ApiException(r)
else:
url = MgmtRequests.mgmtRequestSingleDeviceStatus % (requestId, typeId, deviceId)
r = self._apiClient.get(url)
if r.status_code == 200:
return r.json()
else:
raise ApiException(r)
|
def getStatus(self, requestId, typeId=None, deviceId=None):
"""
Get a list of device management request device statuses.
Get an individual device mangaement request device status.
"""
if typeId is None or deviceId is None:
url = MgmtRequests.mgmtRequestStatus % (requestId)
r = self._apiClient.get(url)
if r.status_code == 200:
return r.json()
else:
raise ApiException(r)
else:
url = MgmtRequests.mgmtRequestSingleDeviceStatus % (requestId, typeId, deviceId)
r = self._apiClient.get(url)
if r.status_code == 200:
return r.json()
else:
raise ApiException(r)
|
[
"Get",
"a",
"list",
"of",
"device",
"management",
"request",
"device",
"statuses",
".",
"Get",
"an",
"individual",
"device",
"mangaement",
"request",
"device",
"status",
"."
] |
ibm-watson-iot/iot-python
|
python
|
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/mgmt/requests.py#L87-L107
|
[
"def",
"getStatus",
"(",
"self",
",",
"requestId",
",",
"typeId",
"=",
"None",
",",
"deviceId",
"=",
"None",
")",
":",
"if",
"typeId",
"is",
"None",
"or",
"deviceId",
"is",
"None",
":",
"url",
"=",
"MgmtRequests",
".",
"mgmtRequestStatus",
"%",
"(",
"requestId",
")",
"r",
"=",
"self",
".",
"_apiClient",
".",
"get",
"(",
"url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"return",
"r",
".",
"json",
"(",
")",
"else",
":",
"raise",
"ApiException",
"(",
"r",
")",
"else",
":",
"url",
"=",
"MgmtRequests",
".",
"mgmtRequestSingleDeviceStatus",
"%",
"(",
"requestId",
",",
"typeId",
",",
"deviceId",
")",
"r",
"=",
"self",
".",
"_apiClient",
".",
"get",
"(",
"url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"return",
"r",
".",
"json",
"(",
")",
"else",
":",
"raise",
"ApiException",
"(",
"r",
")"
] |
195f05adce3fba4ec997017e41e02ebd85c0c4cc
|
test
|
Index.close
|
Force a flush of the index to storage. Renders index
inaccessible.
|
rtree/index.py
|
def close(self):
"""Force a flush of the index to storage. Renders index
inaccessible."""
if self.handle:
self.handle.destroy()
self.handle = None
else:
raise IOError("Unclosable index")
|
def close(self):
"""Force a flush of the index to storage. Renders index
inaccessible."""
if self.handle:
self.handle.destroy()
self.handle = None
else:
raise IOError("Unclosable index")
|
[
"Force",
"a",
"flush",
"of",
"the",
"index",
"to",
"storage",
".",
"Renders",
"index",
"inaccessible",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L298-L305
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
":",
"self",
".",
"handle",
".",
"destroy",
"(",
")",
"self",
".",
"handle",
"=",
"None",
"else",
":",
"raise",
"IOError",
"(",
"\"Unclosable index\"",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.insert
|
Inserts an item into the index with the given coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it is up
to the user to ensure they are unique if this is a requirement.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param obj: a pickleable object. If not None, this object will be
stored in the index with the :attr:`id`.
The following example inserts an entry into the index with id `4321`,
and the object it stores with that id is the number `42`. The
coordinate ordering in this instance is the default (interleaved=True)
ordering::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
|
rtree/index.py
|
def insert(self, id, coordinates, obj=None):
"""Inserts an item into the index with the given coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it is up
to the user to ensure they are unique if this is a requirement.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param obj: a pickleable object. If not None, this object will be
stored in the index with the :attr:`id`.
The following example inserts an entry into the index with id `4321`,
and the object it stores with that id is the number `42`. The
coordinate ordering in this instance is the default (interleaved=True)
ordering::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
"""
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
data = ctypes.c_ubyte(0)
size = 0
pyserialized = None
if obj is not None:
size, data, pyserialized = self._serialize(obj)
core.rt.Index_InsertData(self.handle, id, p_mins, p_maxs,
self.properties.dimension, data, size)
|
def insert(self, id, coordinates, obj=None):
"""Inserts an item into the index with the given coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it is up
to the user to ensure they are unique if this is a requirement.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param obj: a pickleable object. If not None, this object will be
stored in the index with the :attr:`id`.
The following example inserts an entry into the index with id `4321`,
and the object it stores with that id is the number `42`. The
coordinate ordering in this instance is the default (interleaved=True)
ordering::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
"""
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
data = ctypes.c_ubyte(0)
size = 0
pyserialized = None
if obj is not None:
size, data, pyserialized = self._serialize(obj)
core.rt.Index_InsertData(self.handle, id, p_mins, p_maxs,
self.properties.dimension, data, size)
|
[
"Inserts",
"an",
"item",
"into",
"the",
"index",
"with",
"the",
"given",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L356-L393
|
[
"def",
"insert",
"(",
"self",
",",
"id",
",",
"coordinates",
",",
"obj",
"=",
"None",
")",
":",
"p_mins",
",",
"p_maxs",
"=",
"self",
".",
"get_coordinate_pointers",
"(",
"coordinates",
")",
"data",
"=",
"ctypes",
".",
"c_ubyte",
"(",
"0",
")",
"size",
"=",
"0",
"pyserialized",
"=",
"None",
"if",
"obj",
"is",
"not",
"None",
":",
"size",
",",
"data",
",",
"pyserialized",
"=",
"self",
".",
"_serialize",
"(",
"obj",
")",
"core",
".",
"rt",
".",
"Index_InsertData",
"(",
"self",
".",
"handle",
",",
"id",
",",
"p_mins",
",",
"p_maxs",
",",
"self",
".",
"properties",
".",
"dimension",
",",
"data",
",",
"size",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.count
|
Return number of objects that intersect the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
The following example queries the index for any objects any objects
that were stored in the index intersect the bounds given in the
coordinates::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
>>> print(idx.count((0, 0, 60, 60)))
1
|
rtree/index.py
|
def count(self, coordinates):
"""Return number of objects that intersect the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
The following example queries the index for any objects any objects
that were stored in the index intersect the bounds given in the
coordinates::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
>>> print(idx.count((0, 0, 60, 60)))
1
"""
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
p_num_results = ctypes.c_uint64(0)
core.rt.Index_Intersects_count(self.handle,
p_mins,
p_maxs,
self.properties.dimension,
ctypes.byref(p_num_results))
return p_num_results.value
|
def count(self, coordinates):
"""Return number of objects that intersect the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
The following example queries the index for any objects any objects
that were stored in the index intersect the bounds given in the
coordinates::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
>>> print(idx.count((0, 0, 60, 60)))
1
"""
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
p_num_results = ctypes.c_uint64(0)
core.rt.Index_Intersects_count(self.handle,
p_mins,
p_maxs,
self.properties.dimension,
ctypes.byref(p_num_results))
return p_num_results.value
|
[
"Return",
"number",
"of",
"objects",
"that",
"intersect",
"the",
"given",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L396-L430
|
[
"def",
"count",
"(",
"self",
",",
"coordinates",
")",
":",
"p_mins",
",",
"p_maxs",
"=",
"self",
".",
"get_coordinate_pointers",
"(",
"coordinates",
")",
"p_num_results",
"=",
"ctypes",
".",
"c_uint64",
"(",
"0",
")",
"core",
".",
"rt",
".",
"Index_Intersects_count",
"(",
"self",
".",
"handle",
",",
"p_mins",
",",
"p_maxs",
",",
"self",
".",
"properties",
".",
"dimension",
",",
"ctypes",
".",
"byref",
"(",
"p_num_results",
")",
")",
"return",
"p_num_results",
".",
"value"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.intersection
|
Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param objects: True or False or 'raw'
If True, the intersection method will return index objects that
were pickled when they were stored with each index entry, as well
as the id and bounds of the index entries. If 'raw', the objects
will be returned without the :class:`rtree.index.Item` wrapper.
The following example queries the index for any objects any objects
that were stored in the index intersect the bounds given in the
coordinates::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
>>> hits = list(idx.intersection((0, 0, 60, 60), objects=True))
>>> [(item.object, item.bbox) for item in hits if item.id == 4321]
... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
[(42, [34.37768294..., 26.73758537..., 49.37768294...,
41.73758537...])]
If the :class:`rtree.index.Item` wrapper is not used, it is faster to
request the 'raw' objects::
>>> list(idx.intersection((0, 0, 60, 60), objects="raw"))
[42]
|
rtree/index.py
|
def intersection(self, coordinates, objects=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param objects: True or False or 'raw'
If True, the intersection method will return index objects that
were pickled when they were stored with each index entry, as well
as the id and bounds of the index entries. If 'raw', the objects
will be returned without the :class:`rtree.index.Item` wrapper.
The following example queries the index for any objects any objects
that were stored in the index intersect the bounds given in the
coordinates::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
>>> hits = list(idx.intersection((0, 0, 60, 60), objects=True))
>>> [(item.object, item.bbox) for item in hits if item.id == 4321]
... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
[(42, [34.37768294..., 26.73758537..., 49.37768294...,
41.73758537...])]
If the :class:`rtree.index.Item` wrapper is not used, it is faster to
request the 'raw' objects::
>>> list(idx.intersection((0, 0, 60, 60), objects="raw"))
[42]
"""
if objects:
return self._intersection_obj(coordinates, objects)
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
p_num_results = ctypes.c_uint64(0)
it = ctypes.pointer(ctypes.c_int64())
core.rt.Index_Intersects_id(self.handle,
p_mins,
p_maxs,
self.properties.dimension,
ctypes.byref(it),
ctypes.byref(p_num_results))
return self._get_ids(it, p_num_results.value)
|
def intersection(self, coordinates, objects=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param objects: True or False or 'raw'
If True, the intersection method will return index objects that
were pickled when they were stored with each index entry, as well
as the id and bounds of the index entries. If 'raw', the objects
will be returned without the :class:`rtree.index.Item` wrapper.
The following example queries the index for any objects any objects
that were stored in the index intersect the bounds given in the
coordinates::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734),
... obj=42)
>>> hits = list(idx.intersection((0, 0, 60, 60), objects=True))
>>> [(item.object, item.bbox) for item in hits if item.id == 4321]
... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
[(42, [34.37768294..., 26.73758537..., 49.37768294...,
41.73758537...])]
If the :class:`rtree.index.Item` wrapper is not used, it is faster to
request the 'raw' objects::
>>> list(idx.intersection((0, 0, 60, 60), objects="raw"))
[42]
"""
if objects:
return self._intersection_obj(coordinates, objects)
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
p_num_results = ctypes.c_uint64(0)
it = ctypes.pointer(ctypes.c_int64())
core.rt.Index_Intersects_id(self.handle,
p_mins,
p_maxs,
self.properties.dimension,
ctypes.byref(it),
ctypes.byref(p_num_results))
return self._get_ids(it, p_num_results.value)
|
[
"Return",
"ids",
"or",
"objects",
"in",
"the",
"index",
"that",
"intersect",
"the",
"given",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L432-L488
|
[
"def",
"intersection",
"(",
"self",
",",
"coordinates",
",",
"objects",
"=",
"False",
")",
":",
"if",
"objects",
":",
"return",
"self",
".",
"_intersection_obj",
"(",
"coordinates",
",",
"objects",
")",
"p_mins",
",",
"p_maxs",
"=",
"self",
".",
"get_coordinate_pointers",
"(",
"coordinates",
")",
"p_num_results",
"=",
"ctypes",
".",
"c_uint64",
"(",
"0",
")",
"it",
"=",
"ctypes",
".",
"pointer",
"(",
"ctypes",
".",
"c_int64",
"(",
")",
")",
"core",
".",
"rt",
".",
"Index_Intersects_id",
"(",
"self",
".",
"handle",
",",
"p_mins",
",",
"p_maxs",
",",
"self",
".",
"properties",
".",
"dimension",
",",
"ctypes",
".",
"byref",
"(",
"it",
")",
",",
"ctypes",
".",
"byref",
"(",
"p_num_results",
")",
")",
"return",
"self",
".",
"_get_ids",
"(",
"it",
",",
"p_num_results",
".",
"value",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.nearest
|
Returns the ``k``-nearest objects to the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param num_results: integer
The number of results to return nearest to the given coordinates.
If two index entries are equidistant, *both* are returned.
This property means that :attr:`num_results` may return more
items than specified
:param objects: True / False / 'raw'
If True, the nearest method will return index objects that
were pickled when they were stored with each index entry, as
well as the id and bounds of the index entries.
If 'raw', it will return the object as entered into the database
without the :class:`rtree.index.Item` wrapper.
Example of finding the three items nearest to this one::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321, (34.37, 26.73, 49.37, 41.73), obj=42)
>>> hits = idx.nearest((0, 0, 10, 10), 3, objects=True)
|
rtree/index.py
|
def nearest(self, coordinates, num_results=1, objects=False):
"""Returns the ``k``-nearest objects to the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param num_results: integer
The number of results to return nearest to the given coordinates.
If two index entries are equidistant, *both* are returned.
This property means that :attr:`num_results` may return more
items than specified
:param objects: True / False / 'raw'
If True, the nearest method will return index objects that
were pickled when they were stored with each index entry, as
well as the id and bounds of the index entries.
If 'raw', it will return the object as entered into the database
without the :class:`rtree.index.Item` wrapper.
Example of finding the three items nearest to this one::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321, (34.37, 26.73, 49.37, 41.73), obj=42)
>>> hits = idx.nearest((0, 0, 10, 10), 3, objects=True)
"""
if objects:
return self._nearest_obj(coordinates, num_results, objects)
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
p_num_results = ctypes.pointer(ctypes.c_uint64(num_results))
it = ctypes.pointer(ctypes.c_int64())
core.rt.Index_NearestNeighbors_id(self.handle,
p_mins,
p_maxs,
self.properties.dimension,
ctypes.byref(it),
p_num_results)
return self._get_ids(it, p_num_results.contents.value)
|
def nearest(self, coordinates, num_results=1, objects=False):
"""Returns the ``k``-nearest objects to the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param num_results: integer
The number of results to return nearest to the given coordinates.
If two index entries are equidistant, *both* are returned.
This property means that :attr:`num_results` may return more
items than specified
:param objects: True / False / 'raw'
If True, the nearest method will return index objects that
were pickled when they were stored with each index entry, as
well as the id and bounds of the index entries.
If 'raw', it will return the object as entered into the database
without the :class:`rtree.index.Item` wrapper.
Example of finding the three items nearest to this one::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321, (34.37, 26.73, 49.37, 41.73), obj=42)
>>> hits = idx.nearest((0, 0, 10, 10), 3, objects=True)
"""
if objects:
return self._nearest_obj(coordinates, num_results, objects)
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
p_num_results = ctypes.pointer(ctypes.c_uint64(num_results))
it = ctypes.pointer(ctypes.c_int64())
core.rt.Index_NearestNeighbors_id(self.handle,
p_mins,
p_maxs,
self.properties.dimension,
ctypes.byref(it),
p_num_results)
return self._get_ids(it, p_num_results.contents.value)
|
[
"Returns",
"the",
"k",
"-",
"nearest",
"objects",
"to",
"the",
"given",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L560-L604
|
[
"def",
"nearest",
"(",
"self",
",",
"coordinates",
",",
"num_results",
"=",
"1",
",",
"objects",
"=",
"False",
")",
":",
"if",
"objects",
":",
"return",
"self",
".",
"_nearest_obj",
"(",
"coordinates",
",",
"num_results",
",",
"objects",
")",
"p_mins",
",",
"p_maxs",
"=",
"self",
".",
"get_coordinate_pointers",
"(",
"coordinates",
")",
"p_num_results",
"=",
"ctypes",
".",
"pointer",
"(",
"ctypes",
".",
"c_uint64",
"(",
"num_results",
")",
")",
"it",
"=",
"ctypes",
".",
"pointer",
"(",
"ctypes",
".",
"c_int64",
"(",
")",
")",
"core",
".",
"rt",
".",
"Index_NearestNeighbors_id",
"(",
"self",
".",
"handle",
",",
"p_mins",
",",
"p_maxs",
",",
"self",
".",
"properties",
".",
"dimension",
",",
"ctypes",
".",
"byref",
"(",
"it",
")",
",",
"p_num_results",
")",
"return",
"self",
".",
"_get_ids",
"(",
"it",
",",
"p_num_results",
".",
"contents",
".",
"value",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.get_bounds
|
Returns the bounds of the index
:param coordinate_interleaved: If True, the coordinates are turned
in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax],
otherwise they are returned as
[xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If not specified,
the :attr:`interleaved` member of the index is used, which
defaults to True.
|
rtree/index.py
|
def get_bounds(self, coordinate_interleaved=None):
"""Returns the bounds of the index
:param coordinate_interleaved: If True, the coordinates are turned
in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax],
otherwise they are returned as
[xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If not specified,
the :attr:`interleaved` member of the index is used, which
defaults to True.
"""
if coordinate_interleaved is None:
coordinate_interleaved = self.interleaved
return _get_bounds(
self.handle, core.rt.Index_GetBounds, coordinate_interleaved)
|
def get_bounds(self, coordinate_interleaved=None):
"""Returns the bounds of the index
:param coordinate_interleaved: If True, the coordinates are turned
in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax],
otherwise they are returned as
[xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If not specified,
the :attr:`interleaved` member of the index is used, which
defaults to True.
"""
if coordinate_interleaved is None:
coordinate_interleaved = self.interleaved
return _get_bounds(
self.handle, core.rt.Index_GetBounds, coordinate_interleaved)
|
[
"Returns",
"the",
"bounds",
"of",
"the",
"index"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L606-L619
|
[
"def",
"get_bounds",
"(",
"self",
",",
"coordinate_interleaved",
"=",
"None",
")",
":",
"if",
"coordinate_interleaved",
"is",
"None",
":",
"coordinate_interleaved",
"=",
"self",
".",
"interleaved",
"return",
"_get_bounds",
"(",
"self",
".",
"handle",
",",
"core",
".",
"rt",
".",
"Index_GetBounds",
",",
"coordinate_interleaved",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.delete
|
Deletes items from the index with the given ``'id'`` within the
specified coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it is up
to the user to ensure they are unique if this is a requirement.
:param coordinates: sequence or array
Dimension * 2 coordinate pairs, representing the min
and max coordinates in each dimension of the item to be
deleted from the index. Their ordering will depend on the
index's :attr:`interleaved` data member.
These are not the coordinates of a space containing the
item, but those of the item itself. Together with the
id parameter, they determine which item will be deleted.
This may be an object that satisfies the numpy array protocol.
Example::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.delete(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
|
rtree/index.py
|
def delete(self, id, coordinates):
"""Deletes items from the index with the given ``'id'`` within the
specified coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it is up
to the user to ensure they are unique if this is a requirement.
:param coordinates: sequence or array
Dimension * 2 coordinate pairs, representing the min
and max coordinates in each dimension of the item to be
deleted from the index. Their ordering will depend on the
index's :attr:`interleaved` data member.
These are not the coordinates of a space containing the
item, but those of the item itself. Together with the
id parameter, they determine which item will be deleted.
This may be an object that satisfies the numpy array protocol.
Example::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.delete(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
"""
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
core.rt.Index_DeleteData(
self.handle, id, p_mins, p_maxs, self.properties.dimension)
|
def delete(self, id, coordinates):
"""Deletes items from the index with the given ``'id'`` within the
specified coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it is up
to the user to ensure they are unique if this is a requirement.
:param coordinates: sequence or array
Dimension * 2 coordinate pairs, representing the min
and max coordinates in each dimension of the item to be
deleted from the index. Their ordering will depend on the
index's :attr:`interleaved` data member.
These are not the coordinates of a space containing the
item, but those of the item itself. Together with the
id parameter, they determine which item will be deleted.
This may be an object that satisfies the numpy array protocol.
Example::
>>> from rtree import index
>>> idx = index.Index()
>>> idx.delete(4321,
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
"""
p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
core.rt.Index_DeleteData(
self.handle, id, p_mins, p_maxs, self.properties.dimension)
|
[
"Deletes",
"items",
"from",
"the",
"index",
"with",
"the",
"given",
"id",
"within",
"the",
"specified",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L622-L652
|
[
"def",
"delete",
"(",
"self",
",",
"id",
",",
"coordinates",
")",
":",
"p_mins",
",",
"p_maxs",
"=",
"self",
".",
"get_coordinate_pointers",
"(",
"coordinates",
")",
"core",
".",
"rt",
".",
"Index_DeleteData",
"(",
"self",
".",
"handle",
",",
"id",
",",
"p_mins",
",",
"p_maxs",
",",
"self",
".",
"properties",
".",
"dimension",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.deinterleave
|
[xmin, ymin, xmax, ymax] => [xmin, xmax, ymin, ymax]
>>> Index.deinterleave([0, 10, 1, 11])
[0, 1, 10, 11]
>>> Index.deinterleave([0, 1, 2, 10, 11, 12])
[0, 10, 1, 11, 2, 12]
|
rtree/index.py
|
def deinterleave(self, interleaved):
"""
[xmin, ymin, xmax, ymax] => [xmin, xmax, ymin, ymax]
>>> Index.deinterleave([0, 10, 1, 11])
[0, 1, 10, 11]
>>> Index.deinterleave([0, 1, 2, 10, 11, 12])
[0, 10, 1, 11, 2, 12]
"""
assert len(interleaved) % 2 == 0, ("must be a pairwise list")
dimension = len(interleaved) // 2
di = []
for i in range(dimension):
di.extend([interleaved[i], interleaved[i + dimension]])
return di
|
def deinterleave(self, interleaved):
"""
[xmin, ymin, xmax, ymax] => [xmin, xmax, ymin, ymax]
>>> Index.deinterleave([0, 10, 1, 11])
[0, 1, 10, 11]
>>> Index.deinterleave([0, 1, 2, 10, 11, 12])
[0, 10, 1, 11, 2, 12]
"""
assert len(interleaved) % 2 == 0, ("must be a pairwise list")
dimension = len(interleaved) // 2
di = []
for i in range(dimension):
di.extend([interleaved[i], interleaved[i + dimension]])
return di
|
[
"[",
"xmin",
"ymin",
"xmax",
"ymax",
"]",
"=",
">",
"[",
"xmin",
"xmax",
"ymin",
"ymax",
"]"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L661-L677
|
[
"def",
"deinterleave",
"(",
"self",
",",
"interleaved",
")",
":",
"assert",
"len",
"(",
"interleaved",
")",
"%",
"2",
"==",
"0",
",",
"(",
"\"must be a pairwise list\"",
")",
"dimension",
"=",
"len",
"(",
"interleaved",
")",
"//",
"2",
"di",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"dimension",
")",
":",
"di",
".",
"extend",
"(",
"[",
"interleaved",
"[",
"i",
"]",
",",
"interleaved",
"[",
"i",
"+",
"dimension",
"]",
"]",
")",
"return",
"di"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index.interleave
|
[xmin, xmax, ymin, ymax, zmin, zmax]
=> [xmin, ymin, zmin, xmax, ymax, zmax]
>>> Index.interleave([0, 1, 10, 11])
[0, 10, 1, 11]
>>> Index.interleave([0, 10, 1, 11, 2, 12])
[0, 1, 2, 10, 11, 12]
>>> Index.interleave((-1, 1, 58, 62, 22, 24))
[-1, 58, 22, 1, 62, 24]
|
rtree/index.py
|
def interleave(self, deinterleaved):
"""
[xmin, xmax, ymin, ymax, zmin, zmax]
=> [xmin, ymin, zmin, xmax, ymax, zmax]
>>> Index.interleave([0, 1, 10, 11])
[0, 10, 1, 11]
>>> Index.interleave([0, 10, 1, 11, 2, 12])
[0, 1, 2, 10, 11, 12]
>>> Index.interleave((-1, 1, 58, 62, 22, 24))
[-1, 58, 22, 1, 62, 24]
"""
assert len(deinterleaved) % 2 == 0, ("must be a pairwise list")
# dimension = len(deinterleaved) / 2
interleaved = []
for i in range(2):
interleaved.extend([deinterleaved[i + j]
for j in range(0, len(deinterleaved), 2)])
return interleaved
|
def interleave(self, deinterleaved):
"""
[xmin, xmax, ymin, ymax, zmin, zmax]
=> [xmin, ymin, zmin, xmax, ymax, zmax]
>>> Index.interleave([0, 1, 10, 11])
[0, 10, 1, 11]
>>> Index.interleave([0, 10, 1, 11, 2, 12])
[0, 1, 2, 10, 11, 12]
>>> Index.interleave((-1, 1, 58, 62, 22, 24))
[-1, 58, 22, 1, 62, 24]
"""
assert len(deinterleaved) % 2 == 0, ("must be a pairwise list")
# dimension = len(deinterleaved) / 2
interleaved = []
for i in range(2):
interleaved.extend([deinterleaved[i + j]
for j in range(0, len(deinterleaved), 2)])
return interleaved
|
[
"[",
"xmin",
"xmax",
"ymin",
"ymax",
"zmin",
"zmax",
"]",
"=",
">",
"[",
"xmin",
"ymin",
"zmin",
"xmax",
"ymax",
"zmax",
"]"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L680-L701
|
[
"def",
"interleave",
"(",
"self",
",",
"deinterleaved",
")",
":",
"assert",
"len",
"(",
"deinterleaved",
")",
"%",
"2",
"==",
"0",
",",
"(",
"\"must be a pairwise list\"",
")",
"# dimension = len(deinterleaved) / 2",
"interleaved",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
")",
":",
"interleaved",
".",
"extend",
"(",
"[",
"deinterleaved",
"[",
"i",
"+",
"j",
"]",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"deinterleaved",
")",
",",
"2",
")",
"]",
")",
"return",
"interleaved"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
Index._create_idx_from_stream
|
This function is used to instantiate the index given an
iterable stream of data.
|
rtree/index.py
|
def _create_idx_from_stream(self, stream):
"""This function is used to instantiate the index given an
iterable stream of data."""
stream_iter = iter(stream)
dimension = self.properties.dimension
darray = ctypes.c_double * dimension
mins = darray()
maxs = darray()
no_data = ctypes.cast(ctypes.pointer(ctypes.c_ubyte(0)),
ctypes.POINTER(ctypes.c_ubyte))
def py_next_item(p_id, p_mins, p_maxs, p_dimension, p_data, p_length):
"""This function must fill pointers to individual entries that will
be added to the index. The C API will actually call this function
to fill out the pointers. If this function returns anything other
than 0, it is assumed that the stream of data is done."""
try:
p_id[0], coordinates, obj = next(stream_iter)
except StopIteration:
# we're done
return -1
except Exception as exc:
self._exception = exc
return -1
if self.interleaved:
coordinates = Index.deinterleave(coordinates)
# this code assumes the coords are not interleaved.
# xmin, xmax, ymin, ymax, zmin, zmax
for i in range(dimension):
mins[i] = coordinates[i*2]
maxs[i] = coordinates[(i*2)+1]
p_mins[0] = ctypes.cast(mins, ctypes.POINTER(ctypes.c_double))
p_maxs[0] = ctypes.cast(maxs, ctypes.POINTER(ctypes.c_double))
# set the dimension
p_dimension[0] = dimension
if obj is None:
p_data[0] = no_data
p_length[0] = 0
else:
p_length[0], data, _ = self._serialize(obj)
p_data[0] = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte))
return 0
stream = core.NEXTFUNC(py_next_item)
return IndexStreamHandle(self.properties.handle, stream)
|
def _create_idx_from_stream(self, stream):
"""This function is used to instantiate the index given an
iterable stream of data."""
stream_iter = iter(stream)
dimension = self.properties.dimension
darray = ctypes.c_double * dimension
mins = darray()
maxs = darray()
no_data = ctypes.cast(ctypes.pointer(ctypes.c_ubyte(0)),
ctypes.POINTER(ctypes.c_ubyte))
def py_next_item(p_id, p_mins, p_maxs, p_dimension, p_data, p_length):
"""This function must fill pointers to individual entries that will
be added to the index. The C API will actually call this function
to fill out the pointers. If this function returns anything other
than 0, it is assumed that the stream of data is done."""
try:
p_id[0], coordinates, obj = next(stream_iter)
except StopIteration:
# we're done
return -1
except Exception as exc:
self._exception = exc
return -1
if self.interleaved:
coordinates = Index.deinterleave(coordinates)
# this code assumes the coords are not interleaved.
# xmin, xmax, ymin, ymax, zmin, zmax
for i in range(dimension):
mins[i] = coordinates[i*2]
maxs[i] = coordinates[(i*2)+1]
p_mins[0] = ctypes.cast(mins, ctypes.POINTER(ctypes.c_double))
p_maxs[0] = ctypes.cast(maxs, ctypes.POINTER(ctypes.c_double))
# set the dimension
p_dimension[0] = dimension
if obj is None:
p_data[0] = no_data
p_length[0] = 0
else:
p_length[0], data, _ = self._serialize(obj)
p_data[0] = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte))
return 0
stream = core.NEXTFUNC(py_next_item)
return IndexStreamHandle(self.properties.handle, stream)
|
[
"This",
"function",
"is",
"used",
"to",
"instantiate",
"the",
"index",
"given",
"an",
"iterable",
"stream",
"of",
"data",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L703-L754
|
[
"def",
"_create_idx_from_stream",
"(",
"self",
",",
"stream",
")",
":",
"stream_iter",
"=",
"iter",
"(",
"stream",
")",
"dimension",
"=",
"self",
".",
"properties",
".",
"dimension",
"darray",
"=",
"ctypes",
".",
"c_double",
"*",
"dimension",
"mins",
"=",
"darray",
"(",
")",
"maxs",
"=",
"darray",
"(",
")",
"no_data",
"=",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"ctypes",
".",
"c_ubyte",
"(",
"0",
")",
")",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_ubyte",
")",
")",
"def",
"py_next_item",
"(",
"p_id",
",",
"p_mins",
",",
"p_maxs",
",",
"p_dimension",
",",
"p_data",
",",
"p_length",
")",
":",
"\"\"\"This function must fill pointers to individual entries that will\n be added to the index. The C API will actually call this function\n to fill out the pointers. If this function returns anything other\n than 0, it is assumed that the stream of data is done.\"\"\"",
"try",
":",
"p_id",
"[",
"0",
"]",
",",
"coordinates",
",",
"obj",
"=",
"next",
"(",
"stream_iter",
")",
"except",
"StopIteration",
":",
"# we're done",
"return",
"-",
"1",
"except",
"Exception",
"as",
"exc",
":",
"self",
".",
"_exception",
"=",
"exc",
"return",
"-",
"1",
"if",
"self",
".",
"interleaved",
":",
"coordinates",
"=",
"Index",
".",
"deinterleave",
"(",
"coordinates",
")",
"# this code assumes the coords are not interleaved.",
"# xmin, xmax, ymin, ymax, zmin, zmax",
"for",
"i",
"in",
"range",
"(",
"dimension",
")",
":",
"mins",
"[",
"i",
"]",
"=",
"coordinates",
"[",
"i",
"*",
"2",
"]",
"maxs",
"[",
"i",
"]",
"=",
"coordinates",
"[",
"(",
"i",
"*",
"2",
")",
"+",
"1",
"]",
"p_mins",
"[",
"0",
"]",
"=",
"ctypes",
".",
"cast",
"(",
"mins",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_double",
")",
")",
"p_maxs",
"[",
"0",
"]",
"=",
"ctypes",
".",
"cast",
"(",
"maxs",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_double",
")",
")",
"# set the dimension",
"p_dimension",
"[",
"0",
"]",
"=",
"dimension",
"if",
"obj",
"is",
"None",
":",
"p_data",
"[",
"0",
"]",
"=",
"no_data",
"p_length",
"[",
"0",
"]",
"=",
"0",
"else",
":",
"p_length",
"[",
"0",
"]",
",",
"data",
",",
"_",
"=",
"self",
".",
"_serialize",
"(",
"obj",
")",
"p_data",
"[",
"0",
"]",
"=",
"ctypes",
".",
"cast",
"(",
"data",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_ubyte",
")",
")",
"return",
"0",
"stream",
"=",
"core",
".",
"NEXTFUNC",
"(",
"py_next_item",
")",
"return",
"IndexStreamHandle",
"(",
"self",
".",
"properties",
".",
"handle",
",",
"stream",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
CustomStorageBase.destroy
|
please override
|
rtree/index.py
|
def destroy(self, context, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
def destroy(self, context, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
[
"please",
"override"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1348-L1351
|
[
"def",
"destroy",
"(",
"self",
",",
"context",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must override this method.\"",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
CustomStorageBase.loadByteArray
|
please override
|
rtree/index.py
|
def loadByteArray(self, context, page, resultLen, resultData, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
def loadByteArray(self, context, page, resultLen, resultData, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
[
"please",
"override"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1353-L1356
|
[
"def",
"loadByteArray",
"(",
"self",
",",
"context",
",",
"page",
",",
"resultLen",
",",
"resultData",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must override this method.\"",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
CustomStorageBase.storeByteArray
|
please override
|
rtree/index.py
|
def storeByteArray(self, context, page, len, data, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
def storeByteArray(self, context, page, len, data, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
[
"please",
"override"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1358-L1361
|
[
"def",
"storeByteArray",
"(",
"self",
",",
"context",
",",
"page",
",",
"len",
",",
"data",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must override this method.\"",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
CustomStorageBase.deleteByteArray
|
please override
|
rtree/index.py
|
def deleteByteArray(self, context, page, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
def deleteByteArray(self, context, page, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
[
"please",
"override"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1363-L1366
|
[
"def",
"deleteByteArray",
"(",
"self",
",",
"context",
",",
"page",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must override this method.\"",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
CustomStorageBase.flush
|
please override
|
rtree/index.py
|
def flush(self, context, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
def flush(self, context, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
|
[
"please",
"override"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1368-L1371
|
[
"def",
"flush",
"(",
"self",
",",
"context",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must override this method.\"",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
CustomStorage.loadByteArray
|
Must be overridden. Must return a string with the loaded data.
|
rtree/index.py
|
def loadByteArray(self, page, returnError):
"""Must be overridden. Must return a string with the loaded data."""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
return ''
|
def loadByteArray(self, page, returnError):
"""Must be overridden. Must return a string with the loaded data."""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
return ''
|
[
"Must",
"be",
"overridden",
".",
"Must",
"return",
"a",
"string",
"with",
"the",
"loaded",
"data",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1441-L1445
|
[
"def",
"loadByteArray",
"(",
"self",
",",
"page",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must override this method.\"",
")",
"return",
"''"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
RtreeContainer.insert
|
Inserts an item into the index with the given coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
The following example inserts a simple object into the container.
The coordinate ordering in this instance is the default
(interleaved=True) ordering::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.insert(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
|
rtree/index.py
|
def insert(self, obj, coordinates):
"""Inserts an item into the index with the given coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
The following example inserts a simple object into the container.
The coordinate ordering in this instance is the default
(interleaved=True) ordering::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.insert(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
"""
try:
count = self._objects[id(obj)] + 1
except KeyError:
count = 1
self._objects[id(obj)] = (count, obj)
return super(RtreeContainer, self).insert(id(obj), coordinates, None)
|
def insert(self, obj, coordinates):
"""Inserts an item into the index with the given coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
The following example inserts a simple object into the container.
The coordinate ordering in this instance is the default
(interleaved=True) ordering::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.insert(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
"""
try:
count = self._objects[id(obj)] + 1
except KeyError:
count = 1
self._objects[id(obj)] = (count, obj)
return super(RtreeContainer, self).insert(id(obj), coordinates, None)
|
[
"Inserts",
"an",
"item",
"into",
"the",
"index",
"with",
"the",
"given",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1529-L1557
|
[
"def",
"insert",
"(",
"self",
",",
"obj",
",",
"coordinates",
")",
":",
"try",
":",
"count",
"=",
"self",
".",
"_objects",
"[",
"id",
"(",
"obj",
")",
"]",
"+",
"1",
"except",
"KeyError",
":",
"count",
"=",
"1",
"self",
".",
"_objects",
"[",
"id",
"(",
"obj",
")",
"]",
"=",
"(",
"count",
",",
"obj",
")",
"return",
"super",
"(",
"RtreeContainer",
",",
"self",
")",
".",
"insert",
"(",
"id",
"(",
"obj",
")",
",",
"coordinates",
",",
"None",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
RtreeContainer.intersection
|
Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param bbox: True or False
If True, the intersection method will return the stored objects,
as well as the bounds of the entry.
The following example queries the container for any stored objects that
intersect the bounds given in the coordinates::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.insert(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
>>> hits = list(idx.intersection((0, 0, 60, 60), bbox=True))
>>> [(item.object, item.bbox) for item in hits]
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
[(<object object at 0x...>, [34.3776829412, 26.7375853734,
49.3776829412, 41.7375853734])]
If the :class:`rtree.index.Item` wrapper is not used, it is faster to
request only the stored objects::
>>> list(idx.intersection((0, 0, 60, 60))) # doctest: +ELLIPSIS
[<object object at 0x...>]
|
rtree/index.py
|
def intersection(self, coordinates, bbox=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param bbox: True or False
If True, the intersection method will return the stored objects,
as well as the bounds of the entry.
The following example queries the container for any stored objects that
intersect the bounds given in the coordinates::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.insert(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
>>> hits = list(idx.intersection((0, 0, 60, 60), bbox=True))
>>> [(item.object, item.bbox) for item in hits]
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
[(<object object at 0x...>, [34.3776829412, 26.7375853734,
49.3776829412, 41.7375853734])]
If the :class:`rtree.index.Item` wrapper is not used, it is faster to
request only the stored objects::
>>> list(idx.intersection((0, 0, 60, 60))) # doctest: +ELLIPSIS
[<object object at 0x...>]
"""
if bbox == False:
for id in super(RtreeContainer,
self).intersection(coordinates, bbox):
yield self._objects[id][1]
elif bbox == True:
for value in super(RtreeContainer,
self).intersection(coordinates, bbox):
value.object = self._objects[value.id][1]
value.id = None
yield value
else:
raise ValueError(
"valid values for the bbox argument are True and False")
|
def intersection(self, coordinates, bbox=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the `mink` and `maxk` coordinates in
each dimension defining the bounds of the query window.
:param bbox: True or False
If True, the intersection method will return the stored objects,
as well as the bounds of the entry.
The following example queries the container for any stored objects that
intersect the bounds given in the coordinates::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.insert(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
>>> hits = list(idx.intersection((0, 0, 60, 60), bbox=True))
>>> [(item.object, item.bbox) for item in hits]
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
[(<object object at 0x...>, [34.3776829412, 26.7375853734,
49.3776829412, 41.7375853734])]
If the :class:`rtree.index.Item` wrapper is not used, it is faster to
request only the stored objects::
>>> list(idx.intersection((0, 0, 60, 60))) # doctest: +ELLIPSIS
[<object object at 0x...>]
"""
if bbox == False:
for id in super(RtreeContainer,
self).intersection(coordinates, bbox):
yield self._objects[id][1]
elif bbox == True:
for value in super(RtreeContainer,
self).intersection(coordinates, bbox):
value.object = self._objects[value.id][1]
value.id = None
yield value
else:
raise ValueError(
"valid values for the bbox argument are True and False")
|
[
"Return",
"ids",
"or",
"objects",
"in",
"the",
"index",
"that",
"intersect",
"the",
"given",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1561-L1609
|
[
"def",
"intersection",
"(",
"self",
",",
"coordinates",
",",
"bbox",
"=",
"False",
")",
":",
"if",
"bbox",
"==",
"False",
":",
"for",
"id",
"in",
"super",
"(",
"RtreeContainer",
",",
"self",
")",
".",
"intersection",
"(",
"coordinates",
",",
"bbox",
")",
":",
"yield",
"self",
".",
"_objects",
"[",
"id",
"]",
"[",
"1",
"]",
"elif",
"bbox",
"==",
"True",
":",
"for",
"value",
"in",
"super",
"(",
"RtreeContainer",
",",
"self",
")",
".",
"intersection",
"(",
"coordinates",
",",
"bbox",
")",
":",
"value",
".",
"object",
"=",
"self",
".",
"_objects",
"[",
"value",
".",
"id",
"]",
"[",
"1",
"]",
"value",
".",
"id",
"=",
"None",
"yield",
"value",
"else",
":",
"raise",
"ValueError",
"(",
"\"valid values for the bbox argument are True and False\"",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
RtreeContainer.delete
|
Deletes the item from the container within the specified
coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
Dimension * 2 coordinate pairs, representing the min
and max coordinates in each dimension of the item to be
deleted from the index. Their ordering will depend on the
index's :attr:`interleaved` data member.
These are not the coordinates of a space containing the
item, but those of the item itself. Together with the
id parameter, they determine which item will be deleted.
This may be an object that satisfies the numpy array protocol.
Example::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.delete(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
Traceback (most recent call last):
...
IndexError: object is not in the index
|
rtree/index.py
|
def delete(self, obj, coordinates):
"""Deletes the item from the container within the specified
coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
Dimension * 2 coordinate pairs, representing the min
and max coordinates in each dimension of the item to be
deleted from the index. Their ordering will depend on the
index's :attr:`interleaved` data member.
These are not the coordinates of a space containing the
item, but those of the item itself. Together with the
id parameter, they determine which item will be deleted.
This may be an object that satisfies the numpy array protocol.
Example::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.delete(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
Traceback (most recent call last):
...
IndexError: object is not in the index
"""
try:
count = self._objects[id(obj)] - 1
except KeyError:
raise IndexError('object is not in the index')
if count == 0:
del self._objects[obj]
else:
self._objects[id(obj)] = (count, obj)
return super(RtreeContainer, self).delete(id, coordinates)
|
def delete(self, obj, coordinates):
"""Deletes the item from the container within the specified
coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
Dimension * 2 coordinate pairs, representing the min
and max coordinates in each dimension of the item to be
deleted from the index. Their ordering will depend on the
index's :attr:`interleaved` data member.
These are not the coordinates of a space containing the
item, but those of the item itself. Together with the
id parameter, they determine which item will be deleted.
This may be an object that satisfies the numpy array protocol.
Example::
>>> from rtree import index
>>> idx = index.RtreeContainer()
>>> idx.delete(object(),
... (34.3776829412, 26.7375853734, 49.3776829412,
... 41.7375853734))
Traceback (most recent call last):
...
IndexError: object is not in the index
"""
try:
count = self._objects[id(obj)] - 1
except KeyError:
raise IndexError('object is not in the index')
if count == 0:
del self._objects[obj]
else:
self._objects[id(obj)] = (count, obj)
return super(RtreeContainer, self).delete(id, coordinates)
|
[
"Deletes",
"the",
"item",
"from",
"the",
"container",
"within",
"the",
"specified",
"coordinates",
"."
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/index.py#L1651-L1688
|
[
"def",
"delete",
"(",
"self",
",",
"obj",
",",
"coordinates",
")",
":",
"try",
":",
"count",
"=",
"self",
".",
"_objects",
"[",
"id",
"(",
"obj",
")",
"]",
"-",
"1",
"except",
"KeyError",
":",
"raise",
"IndexError",
"(",
"'object is not in the index'",
")",
"if",
"count",
"==",
"0",
":",
"del",
"self",
".",
"_objects",
"[",
"obj",
"]",
"else",
":",
"self",
".",
"_objects",
"[",
"id",
"(",
"obj",
")",
"]",
"=",
"(",
"count",
",",
"obj",
")",
"return",
"super",
"(",
"RtreeContainer",
",",
"self",
")",
".",
"delete",
"(",
"id",
",",
"coordinates",
")"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
check_return
|
Error checking for Error calls
|
rtree/core.py
|
def check_return(result, func, cargs):
"Error checking for Error calls"
if result != 0:
s = rt.Error_GetLastErrorMsg().decode()
msg = 'LASError in "%s": %s' % \
(func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return True
|
def check_return(result, func, cargs):
"Error checking for Error calls"
if result != 0:
s = rt.Error_GetLastErrorMsg().decode()
msg = 'LASError in "%s": %s' % \
(func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return True
|
[
"Error",
"checking",
"for",
"Error",
"calls"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/core.py#L11-L19
|
[
"def",
"check_return",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"result",
"!=",
"0",
":",
"s",
"=",
"rt",
".",
"Error_GetLastErrorMsg",
"(",
")",
".",
"decode",
"(",
")",
"msg",
"=",
"'LASError in \"%s\": %s'",
"%",
"(",
"func",
".",
"__name__",
",",
"s",
")",
"rt",
".",
"Error_Reset",
"(",
")",
"raise",
"RTreeError",
"(",
"msg",
")",
"return",
"True"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
check_void
|
Error checking for void* returns
|
rtree/core.py
|
def check_void(result, func, cargs):
"Error checking for void* returns"
if not bool(result):
s = rt.Error_GetLastErrorMsg().decode()
msg = 'Error in "%s": %s' % (func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return result
|
def check_void(result, func, cargs):
"Error checking for void* returns"
if not bool(result):
s = rt.Error_GetLastErrorMsg().decode()
msg = 'Error in "%s": %s' % (func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return result
|
[
"Error",
"checking",
"for",
"void",
"*",
"returns"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/core.py#L22-L29
|
[
"def",
"check_void",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"not",
"bool",
"(",
"result",
")",
":",
"s",
"=",
"rt",
".",
"Error_GetLastErrorMsg",
"(",
")",
".",
"decode",
"(",
")",
"msg",
"=",
"'Error in \"%s\": %s'",
"%",
"(",
"func",
".",
"__name__",
",",
"s",
")",
"rt",
".",
"Error_Reset",
"(",
")",
"raise",
"RTreeError",
"(",
"msg",
")",
"return",
"result"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
check_void_done
|
Error checking for void* returns that might be empty with no error
|
rtree/core.py
|
def check_void_done(result, func, cargs):
"Error checking for void* returns that might be empty with no error"
if rt.Error_GetErrorCount():
s = rt.Error_GetLastErrorMsg().decode()
msg = 'Error in "%s": %s' % (func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return result
|
def check_void_done(result, func, cargs):
"Error checking for void* returns that might be empty with no error"
if rt.Error_GetErrorCount():
s = rt.Error_GetLastErrorMsg().decode()
msg = 'Error in "%s": %s' % (func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return result
|
[
"Error",
"checking",
"for",
"void",
"*",
"returns",
"that",
"might",
"be",
"empty",
"with",
"no",
"error"
] |
Toblerity/rtree
|
python
|
https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/core.py#L32-L39
|
[
"def",
"check_void_done",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"rt",
".",
"Error_GetErrorCount",
"(",
")",
":",
"s",
"=",
"rt",
".",
"Error_GetLastErrorMsg",
"(",
")",
".",
"decode",
"(",
")",
"msg",
"=",
"'Error in \"%s\": %s'",
"%",
"(",
"func",
".",
"__name__",
",",
"s",
")",
"rt",
".",
"Error_Reset",
"(",
")",
"raise",
"RTreeError",
"(",
"msg",
")",
"return",
"result"
] |
5d33357c8e88f1a8344415dc15a7d2440211b281
|
test
|
WSGIApp.load
|
Attempt an import of the specified application
|
flask_common.py
|
def load(self):
""" Attempt an import of the specified application """
if isinstance(self.application, str):
return util.import_app(self.application)
else:
return self.application
|
def load(self):
""" Attempt an import of the specified application """
if isinstance(self.application, str):
return util.import_app(self.application)
else:
return self.application
|
[
"Attempt",
"an",
"import",
"of",
"the",
"specified",
"application"
] |
kennethreitz/flask-common
|
python
|
https://github.com/kennethreitz/flask-common/blob/7345514942f863396056e0fd252f29082623cec6/flask_common.py#L69-L75
|
[
"def",
"load",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"application",
",",
"str",
")",
":",
"return",
"util",
".",
"import_app",
"(",
"self",
".",
"application",
")",
"else",
":",
"return",
"self",
".",
"application"
] |
7345514942f863396056e0fd252f29082623cec6
|
test
|
Common.init_app
|
Initializes the Flask application with Common.
|
flask_common.py
|
def init_app(self, app):
"""Initializes the Flask application with Common."""
if not hasattr(app, 'extensions'):
app.extensions = {}
if 'common' in app.extensions:
raise RuntimeError("Flask-Common extension already initialized")
app.extensions['common'] = self
self.app = app
if 'COMMON_FILESERVER_DISABLED' not in app.config:
with app.test_request_context():
# Configure WhiteNoise.
app.wsgi_app = WhiteNoise(app.wsgi_app, root=url_for('static', filename='')[1:])
self.cache = Cache(app, config={'CACHE_TYPE': app.config.get("COMMON_CACHE_TYPE", 'simple')})
@app.before_request
def before_request_callback():
request.start_time = maya.now()
@app.after_request
def after_request_callback(response):
if 'COMMON_POWERED_BY_DISABLED' not in current_app.config:
response.headers['X-Powered-By'] = 'Flask'
if 'COMMON_PROCESSED_TIME_DISABLED' not in current_app.config:
response.headers['X-Processed-Time'] = maya.now().epoch - request.start_time.epoch
return response
@app.route('/favicon.ico')
def favicon():
return redirect(url_for('static', filename='favicon.ico'), code=301)
|
def init_app(self, app):
"""Initializes the Flask application with Common."""
if not hasattr(app, 'extensions'):
app.extensions = {}
if 'common' in app.extensions:
raise RuntimeError("Flask-Common extension already initialized")
app.extensions['common'] = self
self.app = app
if 'COMMON_FILESERVER_DISABLED' not in app.config:
with app.test_request_context():
# Configure WhiteNoise.
app.wsgi_app = WhiteNoise(app.wsgi_app, root=url_for('static', filename='')[1:])
self.cache = Cache(app, config={'CACHE_TYPE': app.config.get("COMMON_CACHE_TYPE", 'simple')})
@app.before_request
def before_request_callback():
request.start_time = maya.now()
@app.after_request
def after_request_callback(response):
if 'COMMON_POWERED_BY_DISABLED' not in current_app.config:
response.headers['X-Powered-By'] = 'Flask'
if 'COMMON_PROCESSED_TIME_DISABLED' not in current_app.config:
response.headers['X-Processed-Time'] = maya.now().epoch - request.start_time.epoch
return response
@app.route('/favicon.ico')
def favicon():
return redirect(url_for('static', filename='favicon.ico'), code=301)
|
[
"Initializes",
"the",
"Flask",
"application",
"with",
"Common",
"."
] |
kennethreitz/flask-common
|
python
|
https://github.com/kennethreitz/flask-common/blob/7345514942f863396056e0fd252f29082623cec6/flask_common.py#L101-L134
|
[
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"if",
"'common'",
"in",
"app",
".",
"extensions",
":",
"raise",
"RuntimeError",
"(",
"\"Flask-Common extension already initialized\"",
")",
"app",
".",
"extensions",
"[",
"'common'",
"]",
"=",
"self",
"self",
".",
"app",
"=",
"app",
"if",
"'COMMON_FILESERVER_DISABLED'",
"not",
"in",
"app",
".",
"config",
":",
"with",
"app",
".",
"test_request_context",
"(",
")",
":",
"# Configure WhiteNoise.",
"app",
".",
"wsgi_app",
"=",
"WhiteNoise",
"(",
"app",
".",
"wsgi_app",
",",
"root",
"=",
"url_for",
"(",
"'static'",
",",
"filename",
"=",
"''",
")",
"[",
"1",
":",
"]",
")",
"self",
".",
"cache",
"=",
"Cache",
"(",
"app",
",",
"config",
"=",
"{",
"'CACHE_TYPE'",
":",
"app",
".",
"config",
".",
"get",
"(",
"\"COMMON_CACHE_TYPE\"",
",",
"'simple'",
")",
"}",
")",
"@",
"app",
".",
"before_request",
"def",
"before_request_callback",
"(",
")",
":",
"request",
".",
"start_time",
"=",
"maya",
".",
"now",
"(",
")",
"@",
"app",
".",
"after_request",
"def",
"after_request_callback",
"(",
"response",
")",
":",
"if",
"'COMMON_POWERED_BY_DISABLED'",
"not",
"in",
"current_app",
".",
"config",
":",
"response",
".",
"headers",
"[",
"'X-Powered-By'",
"]",
"=",
"'Flask'",
"if",
"'COMMON_PROCESSED_TIME_DISABLED'",
"not",
"in",
"current_app",
".",
"config",
":",
"response",
".",
"headers",
"[",
"'X-Processed-Time'",
"]",
"=",
"maya",
".",
"now",
"(",
")",
".",
"epoch",
"-",
"request",
".",
"start_time",
".",
"epoch",
"return",
"response",
"@",
"app",
".",
"route",
"(",
"'/favicon.ico'",
")",
"def",
"favicon",
"(",
")",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'static'",
",",
"filename",
"=",
"'favicon.ico'",
")",
",",
"code",
"=",
"301",
")"
] |
7345514942f863396056e0fd252f29082623cec6
|
test
|
Common.serve
|
Serves the Flask application.
|
flask_common.py
|
def serve(self, workers=None, **kwargs):
"""Serves the Flask application."""
if self.app.debug:
print(crayons.yellow('Booting Flask development server...'))
self.app.run()
else:
print(crayons.yellow('Booting Gunicorn...'))
# Start the web server.
server = GunicornServer(
self.app, workers=workers or number_of_gunicorn_workers(),
worker_class='egg:meinheld#gunicorn_worker', **kwargs)
server.run()
|
def serve(self, workers=None, **kwargs):
"""Serves the Flask application."""
if self.app.debug:
print(crayons.yellow('Booting Flask development server...'))
self.app.run()
else:
print(crayons.yellow('Booting Gunicorn...'))
# Start the web server.
server = GunicornServer(
self.app, workers=workers or number_of_gunicorn_workers(),
worker_class='egg:meinheld#gunicorn_worker', **kwargs)
server.run()
|
[
"Serves",
"the",
"Flask",
"application",
"."
] |
kennethreitz/flask-common
|
python
|
https://github.com/kennethreitz/flask-common/blob/7345514942f863396056e0fd252f29082623cec6/flask_common.py#L136-L149
|
[
"def",
"serve",
"(",
"self",
",",
"workers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"app",
".",
"debug",
":",
"print",
"(",
"crayons",
".",
"yellow",
"(",
"'Booting Flask development server...'",
")",
")",
"self",
".",
"app",
".",
"run",
"(",
")",
"else",
":",
"print",
"(",
"crayons",
".",
"yellow",
"(",
"'Booting Gunicorn...'",
")",
")",
"# Start the web server.",
"server",
"=",
"GunicornServer",
"(",
"self",
".",
"app",
",",
"workers",
"=",
"workers",
"or",
"number_of_gunicorn_workers",
"(",
")",
",",
"worker_class",
"=",
"'egg:meinheld#gunicorn_worker'",
",",
"*",
"*",
"kwargs",
")",
"server",
".",
"run",
"(",
")"
] |
7345514942f863396056e0fd252f29082623cec6
|
test
|
VersatileImageFieldSerializer.to_native
|
For djangorestframework <=2.3.14
|
versatileimagefield/serializers.py
|
def to_native(self, value):
"""For djangorestframework <=2.3.14"""
context_request = None
if self.context:
context_request = self.context.get('request', None)
return build_versatileimagefield_url_set(
value,
self.sizes,
request=context_request
)
|
def to_native(self, value):
"""For djangorestframework <=2.3.14"""
context_request = None
if self.context:
context_request = self.context.get('request', None)
return build_versatileimagefield_url_set(
value,
self.sizes,
request=context_request
)
|
[
"For",
"djangorestframework",
"<",
"=",
"2",
".",
"3",
".",
"14"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/serializers.py#L42-L51
|
[
"def",
"to_native",
"(",
"self",
",",
"value",
")",
":",
"context_request",
"=",
"None",
"if",
"self",
".",
"context",
":",
"context_request",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'request'",
",",
"None",
")",
"return",
"build_versatileimagefield_url_set",
"(",
"value",
",",
"self",
".",
"sizes",
",",
"request",
"=",
"context_request",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
CroppedImage.crop_on_centerpoint
|
Return a PIL Image instance cropped from `image`.
Image has an aspect ratio provided by dividing `width` / `height`),
sized down to `width`x`height`. Any 'excess pixels' are trimmed away
in respect to the pixel of `image` that corresponds to `ppoi` (Primary
Point of Interest).
`image`: A PIL Image instance
`width`: Integer, width of the image to return (in pixels)
`height`: Integer, height of the image to return (in pixels)
`ppoi`: A 2-tuple of floats with values greater than 0 and less than 1
These values are converted into a cartesian coordinate that
signifies the 'center pixel' which the crop will center on
(to trim the excess from the 'long side').
Determines whether to trim away pixels from either the left/right or
top/bottom sides by comparing the aspect ratio of `image` vs the
aspect ratio of `width`x`height`.
Will trim from the left/right sides if the aspect ratio of `image`
is greater-than-or-equal-to the aspect ratio of `width`x`height`.
Will trim from the top/bottom sides if the aspect ration of `image`
is less-than the aspect ratio or `width`x`height`.
Similar to Kevin Cazabon's ImageOps.fit method but uses the
ppoi value as an absolute centerpoint (as opposed as a
percentage to trim off the 'long sides').
|
versatileimagefield/versatileimagefield.py
|
def crop_on_centerpoint(self, image, width, height, ppoi=(0.5, 0.5)):
"""
Return a PIL Image instance cropped from `image`.
Image has an aspect ratio provided by dividing `width` / `height`),
sized down to `width`x`height`. Any 'excess pixels' are trimmed away
in respect to the pixel of `image` that corresponds to `ppoi` (Primary
Point of Interest).
`image`: A PIL Image instance
`width`: Integer, width of the image to return (in pixels)
`height`: Integer, height of the image to return (in pixels)
`ppoi`: A 2-tuple of floats with values greater than 0 and less than 1
These values are converted into a cartesian coordinate that
signifies the 'center pixel' which the crop will center on
(to trim the excess from the 'long side').
Determines whether to trim away pixels from either the left/right or
top/bottom sides by comparing the aspect ratio of `image` vs the
aspect ratio of `width`x`height`.
Will trim from the left/right sides if the aspect ratio of `image`
is greater-than-or-equal-to the aspect ratio of `width`x`height`.
Will trim from the top/bottom sides if the aspect ration of `image`
is less-than the aspect ratio or `width`x`height`.
Similar to Kevin Cazabon's ImageOps.fit method but uses the
ppoi value as an absolute centerpoint (as opposed as a
percentage to trim off the 'long sides').
"""
ppoi_x_axis = int(image.size[0] * ppoi[0])
ppoi_y_axis = int(image.size[1] * ppoi[1])
center_pixel_coord = (ppoi_x_axis, ppoi_y_axis)
# Calculate the aspect ratio of `image`
orig_aspect_ratio = float(
image.size[0]
) / float(
image.size[1]
)
crop_aspect_ratio = float(width) / float(height)
# Figure out if we're trimming from the left/right or top/bottom
if orig_aspect_ratio >= crop_aspect_ratio:
# `image` is wider than what's needed,
# crop from left/right sides
orig_crop_width = int(
(crop_aspect_ratio * float(image.size[1])) + 0.5
)
orig_crop_height = image.size[1]
crop_boundary_top = 0
crop_boundary_bottom = orig_crop_height
crop_boundary_left = center_pixel_coord[0] - (orig_crop_width // 2)
crop_boundary_right = crop_boundary_left + orig_crop_width
if crop_boundary_left < 0:
crop_boundary_left = 0
crop_boundary_right = crop_boundary_left + orig_crop_width
elif crop_boundary_right > image.size[0]:
crop_boundary_right = image.size[0]
crop_boundary_left = image.size[0] - orig_crop_width
else:
# `image` is taller than what's needed,
# crop from top/bottom sides
orig_crop_width = image.size[0]
orig_crop_height = int(
(float(image.size[0]) / crop_aspect_ratio) + 0.5
)
crop_boundary_left = 0
crop_boundary_right = orig_crop_width
crop_boundary_top = center_pixel_coord[1] - (orig_crop_height // 2)
crop_boundary_bottom = crop_boundary_top + orig_crop_height
if crop_boundary_top < 0:
crop_boundary_top = 0
crop_boundary_bottom = crop_boundary_top + orig_crop_height
elif crop_boundary_bottom > image.size[1]:
crop_boundary_bottom = image.size[1]
crop_boundary_top = image.size[1] - orig_crop_height
# Cropping the image from the original image
cropped_image = image.crop(
(
crop_boundary_left,
crop_boundary_top,
crop_boundary_right,
crop_boundary_bottom
)
)
# Resizing the newly cropped image to the size specified
# (as determined by `width`x`height`)
return cropped_image.resize(
(width, height),
Image.ANTIALIAS
)
|
def crop_on_centerpoint(self, image, width, height, ppoi=(0.5, 0.5)):
"""
Return a PIL Image instance cropped from `image`.
Image has an aspect ratio provided by dividing `width` / `height`),
sized down to `width`x`height`. Any 'excess pixels' are trimmed away
in respect to the pixel of `image` that corresponds to `ppoi` (Primary
Point of Interest).
`image`: A PIL Image instance
`width`: Integer, width of the image to return (in pixels)
`height`: Integer, height of the image to return (in pixels)
`ppoi`: A 2-tuple of floats with values greater than 0 and less than 1
These values are converted into a cartesian coordinate that
signifies the 'center pixel' which the crop will center on
(to trim the excess from the 'long side').
Determines whether to trim away pixels from either the left/right or
top/bottom sides by comparing the aspect ratio of `image` vs the
aspect ratio of `width`x`height`.
Will trim from the left/right sides if the aspect ratio of `image`
is greater-than-or-equal-to the aspect ratio of `width`x`height`.
Will trim from the top/bottom sides if the aspect ration of `image`
is less-than the aspect ratio or `width`x`height`.
Similar to Kevin Cazabon's ImageOps.fit method but uses the
ppoi value as an absolute centerpoint (as opposed as a
percentage to trim off the 'long sides').
"""
ppoi_x_axis = int(image.size[0] * ppoi[0])
ppoi_y_axis = int(image.size[1] * ppoi[1])
center_pixel_coord = (ppoi_x_axis, ppoi_y_axis)
# Calculate the aspect ratio of `image`
orig_aspect_ratio = float(
image.size[0]
) / float(
image.size[1]
)
crop_aspect_ratio = float(width) / float(height)
# Figure out if we're trimming from the left/right or top/bottom
if orig_aspect_ratio >= crop_aspect_ratio:
# `image` is wider than what's needed,
# crop from left/right sides
orig_crop_width = int(
(crop_aspect_ratio * float(image.size[1])) + 0.5
)
orig_crop_height = image.size[1]
crop_boundary_top = 0
crop_boundary_bottom = orig_crop_height
crop_boundary_left = center_pixel_coord[0] - (orig_crop_width // 2)
crop_boundary_right = crop_boundary_left + orig_crop_width
if crop_boundary_left < 0:
crop_boundary_left = 0
crop_boundary_right = crop_boundary_left + orig_crop_width
elif crop_boundary_right > image.size[0]:
crop_boundary_right = image.size[0]
crop_boundary_left = image.size[0] - orig_crop_width
else:
# `image` is taller than what's needed,
# crop from top/bottom sides
orig_crop_width = image.size[0]
orig_crop_height = int(
(float(image.size[0]) / crop_aspect_ratio) + 0.5
)
crop_boundary_left = 0
crop_boundary_right = orig_crop_width
crop_boundary_top = center_pixel_coord[1] - (orig_crop_height // 2)
crop_boundary_bottom = crop_boundary_top + orig_crop_height
if crop_boundary_top < 0:
crop_boundary_top = 0
crop_boundary_bottom = crop_boundary_top + orig_crop_height
elif crop_boundary_bottom > image.size[1]:
crop_boundary_bottom = image.size[1]
crop_boundary_top = image.size[1] - orig_crop_height
# Cropping the image from the original image
cropped_image = image.crop(
(
crop_boundary_left,
crop_boundary_top,
crop_boundary_right,
crop_boundary_bottom
)
)
# Resizing the newly cropped image to the size specified
# (as determined by `width`x`height`)
return cropped_image.resize(
(width, height),
Image.ANTIALIAS
)
|
[
"Return",
"a",
"PIL",
"Image",
"instance",
"cropped",
"from",
"image",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/versatileimagefield.py#L30-L122
|
[
"def",
"crop_on_centerpoint",
"(",
"self",
",",
"image",
",",
"width",
",",
"height",
",",
"ppoi",
"=",
"(",
"0.5",
",",
"0.5",
")",
")",
":",
"ppoi_x_axis",
"=",
"int",
"(",
"image",
".",
"size",
"[",
"0",
"]",
"*",
"ppoi",
"[",
"0",
"]",
")",
"ppoi_y_axis",
"=",
"int",
"(",
"image",
".",
"size",
"[",
"1",
"]",
"*",
"ppoi",
"[",
"1",
"]",
")",
"center_pixel_coord",
"=",
"(",
"ppoi_x_axis",
",",
"ppoi_y_axis",
")",
"# Calculate the aspect ratio of `image`",
"orig_aspect_ratio",
"=",
"float",
"(",
"image",
".",
"size",
"[",
"0",
"]",
")",
"/",
"float",
"(",
"image",
".",
"size",
"[",
"1",
"]",
")",
"crop_aspect_ratio",
"=",
"float",
"(",
"width",
")",
"/",
"float",
"(",
"height",
")",
"# Figure out if we're trimming from the left/right or top/bottom",
"if",
"orig_aspect_ratio",
">=",
"crop_aspect_ratio",
":",
"# `image` is wider than what's needed,",
"# crop from left/right sides",
"orig_crop_width",
"=",
"int",
"(",
"(",
"crop_aspect_ratio",
"*",
"float",
"(",
"image",
".",
"size",
"[",
"1",
"]",
")",
")",
"+",
"0.5",
")",
"orig_crop_height",
"=",
"image",
".",
"size",
"[",
"1",
"]",
"crop_boundary_top",
"=",
"0",
"crop_boundary_bottom",
"=",
"orig_crop_height",
"crop_boundary_left",
"=",
"center_pixel_coord",
"[",
"0",
"]",
"-",
"(",
"orig_crop_width",
"//",
"2",
")",
"crop_boundary_right",
"=",
"crop_boundary_left",
"+",
"orig_crop_width",
"if",
"crop_boundary_left",
"<",
"0",
":",
"crop_boundary_left",
"=",
"0",
"crop_boundary_right",
"=",
"crop_boundary_left",
"+",
"orig_crop_width",
"elif",
"crop_boundary_right",
">",
"image",
".",
"size",
"[",
"0",
"]",
":",
"crop_boundary_right",
"=",
"image",
".",
"size",
"[",
"0",
"]",
"crop_boundary_left",
"=",
"image",
".",
"size",
"[",
"0",
"]",
"-",
"orig_crop_width",
"else",
":",
"# `image` is taller than what's needed,",
"# crop from top/bottom sides",
"orig_crop_width",
"=",
"image",
".",
"size",
"[",
"0",
"]",
"orig_crop_height",
"=",
"int",
"(",
"(",
"float",
"(",
"image",
".",
"size",
"[",
"0",
"]",
")",
"/",
"crop_aspect_ratio",
")",
"+",
"0.5",
")",
"crop_boundary_left",
"=",
"0",
"crop_boundary_right",
"=",
"orig_crop_width",
"crop_boundary_top",
"=",
"center_pixel_coord",
"[",
"1",
"]",
"-",
"(",
"orig_crop_height",
"//",
"2",
")",
"crop_boundary_bottom",
"=",
"crop_boundary_top",
"+",
"orig_crop_height",
"if",
"crop_boundary_top",
"<",
"0",
":",
"crop_boundary_top",
"=",
"0",
"crop_boundary_bottom",
"=",
"crop_boundary_top",
"+",
"orig_crop_height",
"elif",
"crop_boundary_bottom",
">",
"image",
".",
"size",
"[",
"1",
"]",
":",
"crop_boundary_bottom",
"=",
"image",
".",
"size",
"[",
"1",
"]",
"crop_boundary_top",
"=",
"image",
".",
"size",
"[",
"1",
"]",
"-",
"orig_crop_height",
"# Cropping the image from the original image",
"cropped_image",
"=",
"image",
".",
"crop",
"(",
"(",
"crop_boundary_left",
",",
"crop_boundary_top",
",",
"crop_boundary_right",
",",
"crop_boundary_bottom",
")",
")",
"# Resizing the newly cropped image to the size specified",
"# (as determined by `width`x`height`)",
"return",
"cropped_image",
".",
"resize",
"(",
"(",
"width",
",",
"height",
")",
",",
"Image",
".",
"ANTIALIAS",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
CroppedImage.process_image
|
Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of Interest
(as specified by `self.ppoi`)
|
versatileimagefield/versatileimagefield.py
|
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of Interest
(as specified by `self.ppoi`)
"""
imagefile = BytesIO()
palette = image.getpalette()
cropped_image = self.crop_on_centerpoint(
image,
width,
height,
self.ppoi
)
# Using ImageOps.fit on GIFs can introduce issues with their palette
# Solution derived from: http://stackoverflow.com/a/4905209/1149774
if image_format == 'GIF':
cropped_image.putpalette(palette)
cropped_image.save(
imagefile,
**save_kwargs
)
return imagefile
|
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of Interest
(as specified by `self.ppoi`)
"""
imagefile = BytesIO()
palette = image.getpalette()
cropped_image = self.crop_on_centerpoint(
image,
width,
height,
self.ppoi
)
# Using ImageOps.fit on GIFs can introduce issues with their palette
# Solution derived from: http://stackoverflow.com/a/4905209/1149774
if image_format == 'GIF':
cropped_image.putpalette(palette)
cropped_image.save(
imagefile,
**save_kwargs
)
return imagefile
|
[
"Return",
"a",
"BytesIO",
"instance",
"of",
"image",
"cropped",
"to",
"width",
"and",
"height",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/versatileimagefield.py#L124-L152
|
[
"def",
"process_image",
"(",
"self",
",",
"image",
",",
"image_format",
",",
"save_kwargs",
",",
"width",
",",
"height",
")",
":",
"imagefile",
"=",
"BytesIO",
"(",
")",
"palette",
"=",
"image",
".",
"getpalette",
"(",
")",
"cropped_image",
"=",
"self",
".",
"crop_on_centerpoint",
"(",
"image",
",",
"width",
",",
"height",
",",
"self",
".",
"ppoi",
")",
"# Using ImageOps.fit on GIFs can introduce issues with their palette",
"# Solution derived from: http://stackoverflow.com/a/4905209/1149774",
"if",
"image_format",
"==",
"'GIF'",
":",
"cropped_image",
".",
"putpalette",
"(",
"palette",
")",
"cropped_image",
".",
"save",
"(",
"imagefile",
",",
"*",
"*",
"save_kwargs",
")",
"return",
"imagefile"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ThumbnailImage.process_image
|
Return a BytesIO instance of `image` that fits in a bounding box.
Bounding box dimensions are `width`x`height`.
|
versatileimagefield/versatileimagefield.py
|
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` that fits in a bounding box.
Bounding box dimensions are `width`x`height`.
"""
imagefile = BytesIO()
image.thumbnail(
(width, height),
Image.ANTIALIAS
)
image.save(
imagefile,
**save_kwargs
)
return imagefile
|
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` that fits in a bounding box.
Bounding box dimensions are `width`x`height`.
"""
imagefile = BytesIO()
image.thumbnail(
(width, height),
Image.ANTIALIAS
)
image.save(
imagefile,
**save_kwargs
)
return imagefile
|
[
"Return",
"a",
"BytesIO",
"instance",
"of",
"image",
"that",
"fits",
"in",
"a",
"bounding",
"box",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/versatileimagefield.py#L164-L180
|
[
"def",
"process_image",
"(",
"self",
",",
"image",
",",
"image_format",
",",
"save_kwargs",
",",
"width",
",",
"height",
")",
":",
"imagefile",
"=",
"BytesIO",
"(",
")",
"image",
".",
"thumbnail",
"(",
"(",
"width",
",",
"height",
")",
",",
"Image",
".",
"ANTIALIAS",
")",
"image",
".",
"save",
"(",
"imagefile",
",",
"*",
"*",
"save_kwargs",
")",
"return",
"imagefile"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
InvertImage.process_image
|
Return a BytesIO instance of `image` with inverted colors.
|
versatileimagefield/versatileimagefield.py
|
def process_image(self, image, image_format, save_kwargs={}):
"""Return a BytesIO instance of `image` with inverted colors."""
imagefile = BytesIO()
inv_image = ImageOps.invert(image)
inv_image.save(
imagefile,
**save_kwargs
)
return imagefile
|
def process_image(self, image, image_format, save_kwargs={}):
"""Return a BytesIO instance of `image` with inverted colors."""
imagefile = BytesIO()
inv_image = ImageOps.invert(image)
inv_image.save(
imagefile,
**save_kwargs
)
return imagefile
|
[
"Return",
"a",
"BytesIO",
"instance",
"of",
"image",
"with",
"inverted",
"colors",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/versatileimagefield.py#L190-L198
|
[
"def",
"process_image",
"(",
"self",
",",
"image",
",",
"image_format",
",",
"save_kwargs",
"=",
"{",
"}",
")",
":",
"imagefile",
"=",
"BytesIO",
"(",
")",
"inv_image",
"=",
"ImageOps",
".",
"invert",
"(",
"image",
")",
"inv_image",
".",
"save",
"(",
"imagefile",
",",
"*",
"*",
"save_kwargs",
")",
"return",
"imagefile"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageFormField.to_python
|
Ensure data is prepped properly before handing off to ImageField.
|
versatileimagefield/forms.py
|
def to_python(self, data):
"""Ensure data is prepped properly before handing off to ImageField."""
if data is not None:
if hasattr(data, 'open'):
data.open()
return super(VersatileImageFormField, self).to_python(data)
|
def to_python(self, data):
"""Ensure data is prepped properly before handing off to ImageField."""
if data is not None:
if hasattr(data, 'open'):
data.open()
return super(VersatileImageFormField, self).to_python(data)
|
[
"Ensure",
"data",
"is",
"prepped",
"properly",
"before",
"handing",
"off",
"to",
"ImageField",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/forms.py#L19-L24
|
[
"def",
"to_python",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"data",
",",
"'open'",
")",
":",
"data",
".",
"open",
"(",
")",
"return",
"super",
"(",
"VersatileImageFormField",
",",
"self",
")",
".",
"to_python",
"(",
"data",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageField.process_placeholder_image
|
Process the field's placeholder image.
Ensures the placeholder image has been saved to the same storage class
as the field in a top level folder with a name specified by
settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name']
This should be called by the VersatileImageFileDescriptor __get__.
If self.placeholder_image_name is already set it just returns right away.
|
versatileimagefield/fields.py
|
def process_placeholder_image(self):
"""
Process the field's placeholder image.
Ensures the placeholder image has been saved to the same storage class
as the field in a top level folder with a name specified by
settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name']
This should be called by the VersatileImageFileDescriptor __get__.
If self.placeholder_image_name is already set it just returns right away.
"""
if self.placeholder_image_name:
return
placeholder_image_name = None
placeholder_image = self.placeholder_image
if placeholder_image:
if isinstance(placeholder_image, OnStoragePlaceholderImage):
name = placeholder_image.path
else:
name = placeholder_image.image_data.name
placeholder_image_name = os.path.join(
VERSATILEIMAGEFIELD_PLACEHOLDER_DIRNAME, name
)
if not self.storage.exists(placeholder_image_name):
self.storage.save(
placeholder_image_name,
placeholder_image.image_data
)
self.placeholder_image_name = placeholder_image_name
|
def process_placeholder_image(self):
"""
Process the field's placeholder image.
Ensures the placeholder image has been saved to the same storage class
as the field in a top level folder with a name specified by
settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name']
This should be called by the VersatileImageFileDescriptor __get__.
If self.placeholder_image_name is already set it just returns right away.
"""
if self.placeholder_image_name:
return
placeholder_image_name = None
placeholder_image = self.placeholder_image
if placeholder_image:
if isinstance(placeholder_image, OnStoragePlaceholderImage):
name = placeholder_image.path
else:
name = placeholder_image.image_data.name
placeholder_image_name = os.path.join(
VERSATILEIMAGEFIELD_PLACEHOLDER_DIRNAME, name
)
if not self.storage.exists(placeholder_image_name):
self.storage.save(
placeholder_image_name,
placeholder_image.image_data
)
self.placeholder_image_name = placeholder_image_name
|
[
"Process",
"the",
"field",
"s",
"placeholder",
"image",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/fields.py#L50-L79
|
[
"def",
"process_placeholder_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"placeholder_image_name",
":",
"return",
"placeholder_image_name",
"=",
"None",
"placeholder_image",
"=",
"self",
".",
"placeholder_image",
"if",
"placeholder_image",
":",
"if",
"isinstance",
"(",
"placeholder_image",
",",
"OnStoragePlaceholderImage",
")",
":",
"name",
"=",
"placeholder_image",
".",
"path",
"else",
":",
"name",
"=",
"placeholder_image",
".",
"image_data",
".",
"name",
"placeholder_image_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"VERSATILEIMAGEFIELD_PLACEHOLDER_DIRNAME",
",",
"name",
")",
"if",
"not",
"self",
".",
"storage",
".",
"exists",
"(",
"placeholder_image_name",
")",
":",
"self",
".",
"storage",
".",
"save",
"(",
"placeholder_image_name",
",",
"placeholder_image",
".",
"image_data",
")",
"self",
".",
"placeholder_image_name",
"=",
"placeholder_image_name"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageField.pre_save
|
Return field's value just before saving.
|
versatileimagefield/fields.py
|
def pre_save(self, model_instance, add):
"""Return field's value just before saving."""
file = super(VersatileImageField, self).pre_save(model_instance, add)
self.update_ppoi_field(model_instance)
return file
|
def pre_save(self, model_instance, add):
"""Return field's value just before saving."""
file = super(VersatileImageField, self).pre_save(model_instance, add)
self.update_ppoi_field(model_instance)
return file
|
[
"Return",
"field",
"s",
"value",
"just",
"before",
"saving",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/fields.py#L81-L85
|
[
"def",
"pre_save",
"(",
"self",
",",
"model_instance",
",",
"add",
")",
":",
"file",
"=",
"super",
"(",
"VersatileImageField",
",",
"self",
")",
".",
"pre_save",
"(",
"model_instance",
",",
"add",
")",
"self",
".",
"update_ppoi_field",
"(",
"model_instance",
")",
"return",
"file"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageField.update_ppoi_field
|
Update field's ppoi field, if defined.
This method is hooked up this field's pre_save method to update
the ppoi immediately before the model instance (`instance`)
it is associated with is saved.
This field's ppoi can be forced to update with force=True,
which is how VersatileImageField.pre_save calls this method.
|
versatileimagefield/fields.py
|
def update_ppoi_field(self, instance, *args, **kwargs):
"""
Update field's ppoi field, if defined.
This method is hooked up this field's pre_save method to update
the ppoi immediately before the model instance (`instance`)
it is associated with is saved.
This field's ppoi can be forced to update with force=True,
which is how VersatileImageField.pre_save calls this method.
"""
# Nothing to update if the field doesn't have have a ppoi
# dimension field.
if not self.ppoi_field:
return
# getattr will call the VersatileImageFileDescriptor's __get__ method,
# which coerces the assigned value into an instance of
# self.attr_class(VersatileImageFieldFile in this case).
file = getattr(instance, self.attname)
# file should be an instance of VersatileImageFieldFile or should be
# None.
ppoi = None
if file and not isinstance(file, tuple):
if hasattr(file, 'ppoi'):
ppoi = file.ppoi
# Update the ppoi field.
if self.ppoi_field:
setattr(instance, self.ppoi_field, ppoi)
|
def update_ppoi_field(self, instance, *args, **kwargs):
"""
Update field's ppoi field, if defined.
This method is hooked up this field's pre_save method to update
the ppoi immediately before the model instance (`instance`)
it is associated with is saved.
This field's ppoi can be forced to update with force=True,
which is how VersatileImageField.pre_save calls this method.
"""
# Nothing to update if the field doesn't have have a ppoi
# dimension field.
if not self.ppoi_field:
return
# getattr will call the VersatileImageFileDescriptor's __get__ method,
# which coerces the assigned value into an instance of
# self.attr_class(VersatileImageFieldFile in this case).
file = getattr(instance, self.attname)
# file should be an instance of VersatileImageFieldFile or should be
# None.
ppoi = None
if file and not isinstance(file, tuple):
if hasattr(file, 'ppoi'):
ppoi = file.ppoi
# Update the ppoi field.
if self.ppoi_field:
setattr(instance, self.ppoi_field, ppoi)
|
[
"Update",
"field",
"s",
"ppoi",
"field",
"if",
"defined",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/fields.py#L87-L117
|
[
"def",
"update_ppoi_field",
"(",
"self",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Nothing to update if the field doesn't have have a ppoi",
"# dimension field.",
"if",
"not",
"self",
".",
"ppoi_field",
":",
"return",
"# getattr will call the VersatileImageFileDescriptor's __get__ method,",
"# which coerces the assigned value into an instance of",
"# self.attr_class(VersatileImageFieldFile in this case).",
"file",
"=",
"getattr",
"(",
"instance",
",",
"self",
".",
"attname",
")",
"# file should be an instance of VersatileImageFieldFile or should be",
"# None.",
"ppoi",
"=",
"None",
"if",
"file",
"and",
"not",
"isinstance",
"(",
"file",
",",
"tuple",
")",
":",
"if",
"hasattr",
"(",
"file",
",",
"'ppoi'",
")",
":",
"ppoi",
"=",
"file",
".",
"ppoi",
"# Update the ppoi field.",
"if",
"self",
".",
"ppoi_field",
":",
"setattr",
"(",
"instance",
",",
"self",
".",
"ppoi_field",
",",
"ppoi",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageField.save_form_data
|
Handle data sent from MultiValueField forms that set ppoi values.
`instance`: The model instance that is being altered via a form
`data`: The data sent from the form to this field which can be either:
* `None`: This is unset data from an optional field
* A two-position tuple: (image_form_data, ppoi_data)
* `image_form-data` options:
* `None` the file for this field is unchanged
* `False` unassign the file form the field
* `ppoi_data` data structure:
* `%(x_coordinate)sx%(y_coordinate)s': The ppoi data to
assign to the unchanged file
|
versatileimagefield/fields.py
|
def save_form_data(self, instance, data):
"""
Handle data sent from MultiValueField forms that set ppoi values.
`instance`: The model instance that is being altered via a form
`data`: The data sent from the form to this field which can be either:
* `None`: This is unset data from an optional field
* A two-position tuple: (image_form_data, ppoi_data)
* `image_form-data` options:
* `None` the file for this field is unchanged
* `False` unassign the file form the field
* `ppoi_data` data structure:
* `%(x_coordinate)sx%(y_coordinate)s': The ppoi data to
assign to the unchanged file
"""
to_assign = data
if data and isinstance(data, tuple):
# This value is coming from a MultiValueField
if data[0] is None:
# This means the file hasn't changed but we need to
# update the ppoi
current_field = getattr(instance, self.name)
if data[1]:
current_field.ppoi = data[1]
to_assign = current_field
elif data[0] is False:
# This means the 'Clear' checkbox was checked so we
# need to empty the field
to_assign = ''
else:
# This means there is a new upload so we need to unpack
# the tuple and assign the first position to the field
# attribute
to_assign = data[0]
super(VersatileImageField, self).save_form_data(instance, to_assign)
|
def save_form_data(self, instance, data):
"""
Handle data sent from MultiValueField forms that set ppoi values.
`instance`: The model instance that is being altered via a form
`data`: The data sent from the form to this field which can be either:
* `None`: This is unset data from an optional field
* A two-position tuple: (image_form_data, ppoi_data)
* `image_form-data` options:
* `None` the file for this field is unchanged
* `False` unassign the file form the field
* `ppoi_data` data structure:
* `%(x_coordinate)sx%(y_coordinate)s': The ppoi data to
assign to the unchanged file
"""
to_assign = data
if data and isinstance(data, tuple):
# This value is coming from a MultiValueField
if data[0] is None:
# This means the file hasn't changed but we need to
# update the ppoi
current_field = getattr(instance, self.name)
if data[1]:
current_field.ppoi = data[1]
to_assign = current_field
elif data[0] is False:
# This means the 'Clear' checkbox was checked so we
# need to empty the field
to_assign = ''
else:
# This means there is a new upload so we need to unpack
# the tuple and assign the first position to the field
# attribute
to_assign = data[0]
super(VersatileImageField, self).save_form_data(instance, to_assign)
|
[
"Handle",
"data",
"sent",
"from",
"MultiValueField",
"forms",
"that",
"set",
"ppoi",
"values",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/fields.py#L119-L154
|
[
"def",
"save_form_data",
"(",
"self",
",",
"instance",
",",
"data",
")",
":",
"to_assign",
"=",
"data",
"if",
"data",
"and",
"isinstance",
"(",
"data",
",",
"tuple",
")",
":",
"# This value is coming from a MultiValueField",
"if",
"data",
"[",
"0",
"]",
"is",
"None",
":",
"# This means the file hasn't changed but we need to",
"# update the ppoi",
"current_field",
"=",
"getattr",
"(",
"instance",
",",
"self",
".",
"name",
")",
"if",
"data",
"[",
"1",
"]",
":",
"current_field",
".",
"ppoi",
"=",
"data",
"[",
"1",
"]",
"to_assign",
"=",
"current_field",
"elif",
"data",
"[",
"0",
"]",
"is",
"False",
":",
"# This means the 'Clear' checkbox was checked so we",
"# need to empty the field",
"to_assign",
"=",
"''",
"else",
":",
"# This means there is a new upload so we need to unpack",
"# the tuple and assign the first position to the field",
"# attribute",
"to_assign",
"=",
"data",
"[",
"0",
"]",
"super",
"(",
"VersatileImageField",
",",
"self",
")",
".",
"save_form_data",
"(",
"instance",
",",
"to_assign",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageField.formfield
|
Return a formfield.
|
versatileimagefield/fields.py
|
def formfield(self, **kwargs):
"""Return a formfield."""
# This is a fairly standard way to set up some defaults
# while letting the caller override them.
defaults = {}
if self.ppoi_field:
defaults['form_class'] = SizedImageCenterpointClickDjangoAdminField
if kwargs.get('widget') is AdminFileWidget:
# Ensuring default admin widget is skipped (in favor of using
# SizedImageCenterpointClickDjangoAdminField's default widget as
# the default widget choice for use in the admin).
# This is for two reasons:
# 1. To prevent 'typical' admin users (those who want to use
# the PPOI 'click' widget by default) from having to
# specify a formfield_overrides for each ModelAdmin class
# used by each model that has a VersatileImageField.
# 2. If a VersatileImageField does not have a ppoi_field specified
# it will 'fall back' to a ClearableFileInput anyways.
# If admin users do, in fact, want to force use of the
# AdminFileWidget they can simply subclass AdminFileWidget and
# specify it in their ModelAdmin.formfield_overrides (though,
# if that's the case, why are they using VersatileImageField in
# the first place?)
del kwargs['widget']
defaults.update(kwargs)
return super(VersatileImageField, self).formfield(**defaults)
|
def formfield(self, **kwargs):
"""Return a formfield."""
# This is a fairly standard way to set up some defaults
# while letting the caller override them.
defaults = {}
if self.ppoi_field:
defaults['form_class'] = SizedImageCenterpointClickDjangoAdminField
if kwargs.get('widget') is AdminFileWidget:
# Ensuring default admin widget is skipped (in favor of using
# SizedImageCenterpointClickDjangoAdminField's default widget as
# the default widget choice for use in the admin).
# This is for two reasons:
# 1. To prevent 'typical' admin users (those who want to use
# the PPOI 'click' widget by default) from having to
# specify a formfield_overrides for each ModelAdmin class
# used by each model that has a VersatileImageField.
# 2. If a VersatileImageField does not have a ppoi_field specified
# it will 'fall back' to a ClearableFileInput anyways.
# If admin users do, in fact, want to force use of the
# AdminFileWidget they can simply subclass AdminFileWidget and
# specify it in their ModelAdmin.formfield_overrides (though,
# if that's the case, why are they using VersatileImageField in
# the first place?)
del kwargs['widget']
defaults.update(kwargs)
return super(VersatileImageField, self).formfield(**defaults)
|
[
"Return",
"a",
"formfield",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/fields.py#L156-L181
|
[
"def",
"formfield",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# This is a fairly standard way to set up some defaults",
"# while letting the caller override them.",
"defaults",
"=",
"{",
"}",
"if",
"self",
".",
"ppoi_field",
":",
"defaults",
"[",
"'form_class'",
"]",
"=",
"SizedImageCenterpointClickDjangoAdminField",
"if",
"kwargs",
".",
"get",
"(",
"'widget'",
")",
"is",
"AdminFileWidget",
":",
"# Ensuring default admin widget is skipped (in favor of using",
"# SizedImageCenterpointClickDjangoAdminField's default widget as",
"# the default widget choice for use in the admin).",
"# This is for two reasons:",
"# 1. To prevent 'typical' admin users (those who want to use",
"# the PPOI 'click' widget by default) from having to",
"# specify a formfield_overrides for each ModelAdmin class",
"# used by each model that has a VersatileImageField.",
"# 2. If a VersatileImageField does not have a ppoi_field specified",
"# it will 'fall back' to a ClearableFileInput anyways.",
"# If admin users do, in fact, want to force use of the",
"# AdminFileWidget they can simply subclass AdminFileWidget and",
"# specify it in their ModelAdmin.formfield_overrides (though,",
"# if that's the case, why are they using VersatileImageField in",
"# the first place?)",
"del",
"kwargs",
"[",
"'widget'",
"]",
"defaults",
".",
"update",
"(",
"kwargs",
")",
"return",
"super",
"(",
"VersatileImageField",
",",
"self",
")",
".",
"formfield",
"(",
"*",
"*",
"defaults",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
PPOIField.value_to_string
|
Prepare field for serialization.
|
versatileimagefield/fields.py
|
def value_to_string(self, obj):
"""Prepare field for serialization."""
if DJANGO_VERSION > (1, 9):
value = self.value_from_object(obj)
else:
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
|
def value_to_string(self, obj):
"""Prepare field for serialization."""
if DJANGO_VERSION > (1, 9):
value = self.value_from_object(obj)
else:
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
|
[
"Prepare",
"field",
"for",
"serialization",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/fields.py#L223-L229
|
[
"def",
"value_to_string",
"(",
"self",
",",
"obj",
")",
":",
"if",
"DJANGO_VERSION",
">",
"(",
"1",
",",
"9",
")",
":",
"value",
"=",
"self",
".",
"value_from_object",
"(",
"obj",
")",
"else",
":",
"value",
"=",
"self",
".",
"_get_val_from_obj",
"(",
"obj",
")",
"return",
"self",
".",
"get_prep_value",
"(",
"value",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
cli_progress_bar
|
Prints out a Yum-style progress bar (via sys.stdout.write).
`start`: The 'current' value of the progress bar.
`end`: The '100%' value of the progress bar.
`bar_length`: The size of the overall progress bar.
Example output with start=20, end=100, bar_length=50:
[###########----------------------------------------] 20/100 (100%)
Intended to be used in a loop. Example:
end = 100
for i in range(end):
cli_progress_bar(i, end)
Based on an implementation found here:
http://stackoverflow.com/a/13685020/1149774
|
versatileimagefield/image_warmer.py
|
def cli_progress_bar(start, end, bar_length=50):
"""
Prints out a Yum-style progress bar (via sys.stdout.write).
`start`: The 'current' value of the progress bar.
`end`: The '100%' value of the progress bar.
`bar_length`: The size of the overall progress bar.
Example output with start=20, end=100, bar_length=50:
[###########----------------------------------------] 20/100 (100%)
Intended to be used in a loop. Example:
end = 100
for i in range(end):
cli_progress_bar(i, end)
Based on an implementation found here:
http://stackoverflow.com/a/13685020/1149774
"""
percent = float(start) / end
hashes = '#' * int(round(percent * bar_length))
spaces = '-' * (bar_length - len(hashes))
stdout.write(
"\r[{0}] {1}/{2} ({3}%)".format(
hashes + spaces,
start,
end,
int(round(percent * 100))
)
)
stdout.flush()
|
def cli_progress_bar(start, end, bar_length=50):
"""
Prints out a Yum-style progress bar (via sys.stdout.write).
`start`: The 'current' value of the progress bar.
`end`: The '100%' value of the progress bar.
`bar_length`: The size of the overall progress bar.
Example output with start=20, end=100, bar_length=50:
[###########----------------------------------------] 20/100 (100%)
Intended to be used in a loop. Example:
end = 100
for i in range(end):
cli_progress_bar(i, end)
Based on an implementation found here:
http://stackoverflow.com/a/13685020/1149774
"""
percent = float(start) / end
hashes = '#' * int(round(percent * bar_length))
spaces = '-' * (bar_length - len(hashes))
stdout.write(
"\r[{0}] {1}/{2} ({3}%)".format(
hashes + spaces,
start,
end,
int(round(percent * 100))
)
)
stdout.flush()
|
[
"Prints",
"out",
"a",
"Yum",
"-",
"style",
"progress",
"bar",
"(",
"via",
"sys",
".",
"stdout",
".",
"write",
")",
".",
"start",
":",
"The",
"current",
"value",
"of",
"the",
"progress",
"bar",
".",
"end",
":",
"The",
"100%",
"value",
"of",
"the",
"progress",
"bar",
".",
"bar_length",
":",
"The",
"size",
"of",
"the",
"overall",
"progress",
"bar",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/image_warmer.py#L20-L49
|
[
"def",
"cli_progress_bar",
"(",
"start",
",",
"end",
",",
"bar_length",
"=",
"50",
")",
":",
"percent",
"=",
"float",
"(",
"start",
")",
"/",
"end",
"hashes",
"=",
"'#'",
"*",
"int",
"(",
"round",
"(",
"percent",
"*",
"bar_length",
")",
")",
"spaces",
"=",
"'-'",
"*",
"(",
"bar_length",
"-",
"len",
"(",
"hashes",
")",
")",
"stdout",
".",
"write",
"(",
"\"\\r[{0}] {1}/{2} ({3}%)\"",
".",
"format",
"(",
"hashes",
"+",
"spaces",
",",
"start",
",",
"end",
",",
"int",
"(",
"round",
"(",
"percent",
"*",
"100",
")",
")",
")",
")",
"stdout",
".",
"flush",
"(",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageFieldWarmer._prewarm_versatileimagefield
|
Returns a 2-tuple:
0: bool signifying whether the image was successfully pre-warmed
1: The url of the successfully created image OR the path on storage of
the image that was not able to be successfully created.
Arguments:
`size_key_list`: A list of VersatileImageField size keys. Examples:
* 'crop__800x450'
* 'thumbnail__800x800'
`versatileimagefieldfile`: A VersatileImageFieldFile instance
|
versatileimagefield/image_warmer.py
|
def _prewarm_versatileimagefield(size_key, versatileimagefieldfile):
"""
Returns a 2-tuple:
0: bool signifying whether the image was successfully pre-warmed
1: The url of the successfully created image OR the path on storage of
the image that was not able to be successfully created.
Arguments:
`size_key_list`: A list of VersatileImageField size keys. Examples:
* 'crop__800x450'
* 'thumbnail__800x800'
`versatileimagefieldfile`: A VersatileImageFieldFile instance
"""
versatileimagefieldfile.create_on_demand = True
try:
url = get_url_from_image_key(versatileimagefieldfile, size_key)
except Exception:
success = False
url_or_filepath = versatileimagefieldfile.name
logger.exception('Thumbnail generation failed',
extra={'path': url_or_filepath})
else:
success = True
url_or_filepath = url
return (success, url_or_filepath)
|
def _prewarm_versatileimagefield(size_key, versatileimagefieldfile):
"""
Returns a 2-tuple:
0: bool signifying whether the image was successfully pre-warmed
1: The url of the successfully created image OR the path on storage of
the image that was not able to be successfully created.
Arguments:
`size_key_list`: A list of VersatileImageField size keys. Examples:
* 'crop__800x450'
* 'thumbnail__800x800'
`versatileimagefieldfile`: A VersatileImageFieldFile instance
"""
versatileimagefieldfile.create_on_demand = True
try:
url = get_url_from_image_key(versatileimagefieldfile, size_key)
except Exception:
success = False
url_or_filepath = versatileimagefieldfile.name
logger.exception('Thumbnail generation failed',
extra={'path': url_or_filepath})
else:
success = True
url_or_filepath = url
return (success, url_or_filepath)
|
[
"Returns",
"a",
"2",
"-",
"tuple",
":",
"0",
":",
"bool",
"signifying",
"whether",
"the",
"image",
"was",
"successfully",
"pre",
"-",
"warmed",
"1",
":",
"The",
"url",
"of",
"the",
"successfully",
"created",
"image",
"OR",
"the",
"path",
"on",
"storage",
"of",
"the",
"image",
"that",
"was",
"not",
"able",
"to",
"be",
"successfully",
"created",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/image_warmer.py#L102-L126
|
[
"def",
"_prewarm_versatileimagefield",
"(",
"size_key",
",",
"versatileimagefieldfile",
")",
":",
"versatileimagefieldfile",
".",
"create_on_demand",
"=",
"True",
"try",
":",
"url",
"=",
"get_url_from_image_key",
"(",
"versatileimagefieldfile",
",",
"size_key",
")",
"except",
"Exception",
":",
"success",
"=",
"False",
"url_or_filepath",
"=",
"versatileimagefieldfile",
".",
"name",
"logger",
".",
"exception",
"(",
"'Thumbnail generation failed'",
",",
"extra",
"=",
"{",
"'path'",
":",
"url_or_filepath",
"}",
")",
"else",
":",
"success",
"=",
"True",
"url_or_filepath",
"=",
"url",
"return",
"(",
"success",
",",
"url_or_filepath",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageFieldWarmer.warm
|
Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
VersatileImageField field being processed by `self` of
files that could not be successfully seeded.
|
versatileimagefield/image_warmer.py
|
def warm(self):
"""
Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
VersatileImageField field being processed by `self` of
files that could not be successfully seeded.
"""
num_images_pre_warmed = 0
failed_to_create_image_path_list = []
total = self.queryset.count() * len(self.size_key_list)
for a, instance in enumerate(self.queryset, start=1):
for b, size_key in enumerate(self.size_key_list, start=1):
success, url_or_filepath = self._prewarm_versatileimagefield(
size_key,
reduce(getattr, self.image_attr.split("."), instance)
)
if success is True:
num_images_pre_warmed += 1
if self.verbose:
cli_progress_bar(num_images_pre_warmed, total)
else:
failed_to_create_image_path_list.append(url_or_filepath)
if a * b == total:
stdout.write('\n')
stdout.flush()
return (num_images_pre_warmed, failed_to_create_image_path_list)
|
def warm(self):
"""
Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
VersatileImageField field being processed by `self` of
files that could not be successfully seeded.
"""
num_images_pre_warmed = 0
failed_to_create_image_path_list = []
total = self.queryset.count() * len(self.size_key_list)
for a, instance in enumerate(self.queryset, start=1):
for b, size_key in enumerate(self.size_key_list, start=1):
success, url_or_filepath = self._prewarm_versatileimagefield(
size_key,
reduce(getattr, self.image_attr.split("."), instance)
)
if success is True:
num_images_pre_warmed += 1
if self.verbose:
cli_progress_bar(num_images_pre_warmed, total)
else:
failed_to_create_image_path_list.append(url_or_filepath)
if a * b == total:
stdout.write('\n')
stdout.flush()
return (num_images_pre_warmed, failed_to_create_image_path_list)
|
[
"Returns",
"a",
"2",
"-",
"tuple",
":",
"[",
"0",
"]",
":",
"Number",
"of",
"images",
"successfully",
"pre",
"-",
"warmed",
"[",
"1",
"]",
":",
"A",
"list",
"of",
"paths",
"on",
"the",
"storage",
"class",
"associated",
"with",
"the",
"VersatileImageField",
"field",
"being",
"processed",
"by",
"self",
"of",
"files",
"that",
"could",
"not",
"be",
"successfully",
"seeded",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/image_warmer.py#L128-L156
|
[
"def",
"warm",
"(",
"self",
")",
":",
"num_images_pre_warmed",
"=",
"0",
"failed_to_create_image_path_list",
"=",
"[",
"]",
"total",
"=",
"self",
".",
"queryset",
".",
"count",
"(",
")",
"*",
"len",
"(",
"self",
".",
"size_key_list",
")",
"for",
"a",
",",
"instance",
"in",
"enumerate",
"(",
"self",
".",
"queryset",
",",
"start",
"=",
"1",
")",
":",
"for",
"b",
",",
"size_key",
"in",
"enumerate",
"(",
"self",
".",
"size_key_list",
",",
"start",
"=",
"1",
")",
":",
"success",
",",
"url_or_filepath",
"=",
"self",
".",
"_prewarm_versatileimagefield",
"(",
"size_key",
",",
"reduce",
"(",
"getattr",
",",
"self",
".",
"image_attr",
".",
"split",
"(",
"\".\"",
")",
",",
"instance",
")",
")",
"if",
"success",
"is",
"True",
":",
"num_images_pre_warmed",
"+=",
"1",
"if",
"self",
".",
"verbose",
":",
"cli_progress_bar",
"(",
"num_images_pre_warmed",
",",
"total",
")",
"else",
":",
"failed_to_create_image_path_list",
".",
"append",
"(",
"url_or_filepath",
")",
"if",
"a",
"*",
"b",
"==",
"total",
":",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"stdout",
".",
"flush",
"(",
")",
"return",
"(",
"num_images_pre_warmed",
",",
"failed_to_create_image_path_list",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
autodiscover
|
Discover versatileimagefield.py modules.
Iterate over django.apps.get_app_configs() and discover
versatileimagefield.py modules.
|
versatileimagefield/registry.py
|
def autodiscover():
"""
Discover versatileimagefield.py modules.
Iterate over django.apps.get_app_configs() and discover
versatileimagefield.py modules.
"""
from importlib import import_module
from django.apps import apps
from django.utils.module_loading import module_has_submodule
for app_config in apps.get_app_configs():
# Attempt to import the app's module.
try:
before_import_sizedimage_registry = copy.copy(
versatileimagefield_registry._sizedimage_registry
)
before_import_filter_registry = copy.copy(
versatileimagefield_registry._filter_registry
)
import_module('%s.versatileimagefield' % app_config.name)
except Exception:
# Reset the versatileimagefield_registry to the state before the
# last import as this import will have to reoccur on the next
# request and this could raise NotRegistered and AlreadyRegistered
# exceptions (see django ticket #8245).
versatileimagefield_registry._sizedimage_registry = \
before_import_sizedimage_registry
versatileimagefield_registry._filter_registry = \
before_import_filter_registry
# Decide whether to bubble up this error. If the app just
# doesn't have the module in question, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(app_config.module, 'versatileimagefield'):
raise
|
def autodiscover():
"""
Discover versatileimagefield.py modules.
Iterate over django.apps.get_app_configs() and discover
versatileimagefield.py modules.
"""
from importlib import import_module
from django.apps import apps
from django.utils.module_loading import module_has_submodule
for app_config in apps.get_app_configs():
# Attempt to import the app's module.
try:
before_import_sizedimage_registry = copy.copy(
versatileimagefield_registry._sizedimage_registry
)
before_import_filter_registry = copy.copy(
versatileimagefield_registry._filter_registry
)
import_module('%s.versatileimagefield' % app_config.name)
except Exception:
# Reset the versatileimagefield_registry to the state before the
# last import as this import will have to reoccur on the next
# request and this could raise NotRegistered and AlreadyRegistered
# exceptions (see django ticket #8245).
versatileimagefield_registry._sizedimage_registry = \
before_import_sizedimage_registry
versatileimagefield_registry._filter_registry = \
before_import_filter_registry
# Decide whether to bubble up this error. If the app just
# doesn't have the module in question, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(app_config.module, 'versatileimagefield'):
raise
|
[
"Discover",
"versatileimagefield",
".",
"py",
"modules",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/registry.py#L203-L239
|
[
"def",
"autodiscover",
"(",
")",
":",
"from",
"importlib",
"import",
"import_module",
"from",
"django",
".",
"apps",
"import",
"apps",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"module_has_submodule",
"for",
"app_config",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"# Attempt to import the app's module.",
"try",
":",
"before_import_sizedimage_registry",
"=",
"copy",
".",
"copy",
"(",
"versatileimagefield_registry",
".",
"_sizedimage_registry",
")",
"before_import_filter_registry",
"=",
"copy",
".",
"copy",
"(",
"versatileimagefield_registry",
".",
"_filter_registry",
")",
"import_module",
"(",
"'%s.versatileimagefield'",
"%",
"app_config",
".",
"name",
")",
"except",
"Exception",
":",
"# Reset the versatileimagefield_registry to the state before the",
"# last import as this import will have to reoccur on the next",
"# request and this could raise NotRegistered and AlreadyRegistered",
"# exceptions (see django ticket #8245).",
"versatileimagefield_registry",
".",
"_sizedimage_registry",
"=",
"before_import_sizedimage_registry",
"versatileimagefield_registry",
".",
"_filter_registry",
"=",
"before_import_filter_registry",
"# Decide whether to bubble up this error. If the app just",
"# doesn't have the module in question, we can ignore the error",
"# attempting to import it, otherwise we want it to bubble up.",
"if",
"module_has_submodule",
"(",
"app_config",
".",
"module",
",",
"'versatileimagefield'",
")",
":",
"raise"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageFieldRegistry.register_sizer
|
Register a new SizedImage subclass (`sizedimage_cls`).
To be used via the attribute (`attr_name`).
|
versatileimagefield/registry.py
|
def register_sizer(self, attr_name, sizedimage_cls):
"""
Register a new SizedImage subclass (`sizedimage_cls`).
To be used via the attribute (`attr_name`).
"""
if attr_name.startswith(
'_'
) or attr_name in self.unallowed_sizer_names:
raise UnallowedSizerName(
"`%s` is an unallowed Sizer name. Sizer names cannot begin "
"with an underscore or be named any of the "
"following: %s." % (
attr_name,
', '.join([
name
for name in self.unallowed_sizer_names
])
)
)
if not issubclass(sizedimage_cls, SizedImage):
raise InvalidSizedImageSubclass(
'Only subclasses of versatileimagefield.datastructures.'
'SizedImage may be registered with register_sizer'
)
if attr_name in self._sizedimage_registry:
raise AlreadyRegistered(
'A SizedImage class is already registered to the `%s` '
'attribute. If you would like to override this attribute, '
'use the unregister method' % attr_name
)
else:
self._sizedimage_registry[attr_name] = sizedimage_cls
|
def register_sizer(self, attr_name, sizedimage_cls):
"""
Register a new SizedImage subclass (`sizedimage_cls`).
To be used via the attribute (`attr_name`).
"""
if attr_name.startswith(
'_'
) or attr_name in self.unallowed_sizer_names:
raise UnallowedSizerName(
"`%s` is an unallowed Sizer name. Sizer names cannot begin "
"with an underscore or be named any of the "
"following: %s." % (
attr_name,
', '.join([
name
for name in self.unallowed_sizer_names
])
)
)
if not issubclass(sizedimage_cls, SizedImage):
raise InvalidSizedImageSubclass(
'Only subclasses of versatileimagefield.datastructures.'
'SizedImage may be registered with register_sizer'
)
if attr_name in self._sizedimage_registry:
raise AlreadyRegistered(
'A SizedImage class is already registered to the `%s` '
'attribute. If you would like to override this attribute, '
'use the unregister method' % attr_name
)
else:
self._sizedimage_registry[attr_name] = sizedimage_cls
|
[
"Register",
"a",
"new",
"SizedImage",
"subclass",
"(",
"sizedimage_cls",
")",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/registry.py#L110-L143
|
[
"def",
"register_sizer",
"(",
"self",
",",
"attr_name",
",",
"sizedimage_cls",
")",
":",
"if",
"attr_name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"attr_name",
"in",
"self",
".",
"unallowed_sizer_names",
":",
"raise",
"UnallowedSizerName",
"(",
"\"`%s` is an unallowed Sizer name. Sizer names cannot begin \"",
"\"with an underscore or be named any of the \"",
"\"following: %s.\"",
"%",
"(",
"attr_name",
",",
"', '",
".",
"join",
"(",
"[",
"name",
"for",
"name",
"in",
"self",
".",
"unallowed_sizer_names",
"]",
")",
")",
")",
"if",
"not",
"issubclass",
"(",
"sizedimage_cls",
",",
"SizedImage",
")",
":",
"raise",
"InvalidSizedImageSubclass",
"(",
"'Only subclasses of versatileimagefield.datastructures.'",
"'SizedImage may be registered with register_sizer'",
")",
"if",
"attr_name",
"in",
"self",
".",
"_sizedimage_registry",
":",
"raise",
"AlreadyRegistered",
"(",
"'A SizedImage class is already registered to the `%s` '",
"'attribute. If you would like to override this attribute, '",
"'use the unregister method'",
"%",
"attr_name",
")",
"else",
":",
"self",
".",
"_sizedimage_registry",
"[",
"attr_name",
"]",
"=",
"sizedimage_cls"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageFieldRegistry.unregister_sizer
|
Unregister the SizedImage subclass currently assigned to `attr_name`.
If a SizedImage subclass isn't already registered to `attr_name`
NotRegistered will raise.
|
versatileimagefield/registry.py
|
def unregister_sizer(self, attr_name):
"""
Unregister the SizedImage subclass currently assigned to `attr_name`.
If a SizedImage subclass isn't already registered to `attr_name`
NotRegistered will raise.
"""
if attr_name not in self._sizedimage_registry:
raise NotRegistered(
'No SizedImage subclass is registered to %s' % attr_name
)
else:
del self._sizedimage_registry[attr_name]
|
def unregister_sizer(self, attr_name):
"""
Unregister the SizedImage subclass currently assigned to `attr_name`.
If a SizedImage subclass isn't already registered to `attr_name`
NotRegistered will raise.
"""
if attr_name not in self._sizedimage_registry:
raise NotRegistered(
'No SizedImage subclass is registered to %s' % attr_name
)
else:
del self._sizedimage_registry[attr_name]
|
[
"Unregister",
"the",
"SizedImage",
"subclass",
"currently",
"assigned",
"to",
"attr_name",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/registry.py#L145-L157
|
[
"def",
"unregister_sizer",
"(",
"self",
",",
"attr_name",
")",
":",
"if",
"attr_name",
"not",
"in",
"self",
".",
"_sizedimage_registry",
":",
"raise",
"NotRegistered",
"(",
"'No SizedImage subclass is registered to %s'",
"%",
"attr_name",
")",
"else",
":",
"del",
"self",
".",
"_sizedimage_registry",
"[",
"attr_name",
"]"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageFieldRegistry.register_filter
|
Register a new FilteredImage subclass (`filterimage_cls`).
To be used via the attribute (filters.`attr_name`)
|
versatileimagefield/registry.py
|
def register_filter(self, attr_name, filterimage_cls):
"""
Register a new FilteredImage subclass (`filterimage_cls`).
To be used via the attribute (filters.`attr_name`)
"""
if attr_name.startswith('_'):
raise UnallowedFilterName(
'`%s` is an unallowed Filter name. Filter names cannot begin '
'with an underscore.' % attr_name
)
if not issubclass(filterimage_cls, FilteredImage):
raise InvalidFilteredImageSubclass(
'Only subclasses of FilteredImage may be registered as '
'filters with VersatileImageFieldRegistry'
)
if attr_name in self._filter_registry:
raise AlreadyRegistered(
'A ProcessedImageMixIn class is already registered to the `%s`'
' attribute. If you would like to override this attribute, '
'use the unregister method' % attr_name
)
else:
self._filter_registry[attr_name] = filterimage_cls
|
def register_filter(self, attr_name, filterimage_cls):
"""
Register a new FilteredImage subclass (`filterimage_cls`).
To be used via the attribute (filters.`attr_name`)
"""
if attr_name.startswith('_'):
raise UnallowedFilterName(
'`%s` is an unallowed Filter name. Filter names cannot begin '
'with an underscore.' % attr_name
)
if not issubclass(filterimage_cls, FilteredImage):
raise InvalidFilteredImageSubclass(
'Only subclasses of FilteredImage may be registered as '
'filters with VersatileImageFieldRegistry'
)
if attr_name in self._filter_registry:
raise AlreadyRegistered(
'A ProcessedImageMixIn class is already registered to the `%s`'
' attribute. If you would like to override this attribute, '
'use the unregister method' % attr_name
)
else:
self._filter_registry[attr_name] = filterimage_cls
|
[
"Register",
"a",
"new",
"FilteredImage",
"subclass",
"(",
"filterimage_cls",
")",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/registry.py#L159-L183
|
[
"def",
"register_filter",
"(",
"self",
",",
"attr_name",
",",
"filterimage_cls",
")",
":",
"if",
"attr_name",
".",
"startswith",
"(",
"'_'",
")",
":",
"raise",
"UnallowedFilterName",
"(",
"'`%s` is an unallowed Filter name. Filter names cannot begin '",
"'with an underscore.'",
"%",
"attr_name",
")",
"if",
"not",
"issubclass",
"(",
"filterimage_cls",
",",
"FilteredImage",
")",
":",
"raise",
"InvalidFilteredImageSubclass",
"(",
"'Only subclasses of FilteredImage may be registered as '",
"'filters with VersatileImageFieldRegistry'",
")",
"if",
"attr_name",
"in",
"self",
".",
"_filter_registry",
":",
"raise",
"AlreadyRegistered",
"(",
"'A ProcessedImageMixIn class is already registered to the `%s`'",
"' attribute. If you would like to override this attribute, '",
"'use the unregister method'",
"%",
"attr_name",
")",
"else",
":",
"self",
".",
"_filter_registry",
"[",
"attr_name",
"]",
"=",
"filterimage_cls"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageFieldRegistry.unregister_filter
|
Unregister the FilteredImage subclass currently assigned to attr_name.
If a FilteredImage subclass isn't already registered to filters.
`attr_name` NotRegistered will raise.
|
versatileimagefield/registry.py
|
def unregister_filter(self, attr_name):
"""
Unregister the FilteredImage subclass currently assigned to attr_name.
If a FilteredImage subclass isn't already registered to filters.
`attr_name` NotRegistered will raise.
"""
if attr_name not in self._filter_registry:
raise NotRegistered(
'No FilteredImage subclass is registered to %s' % attr_name
)
else:
del self._filter_registry[attr_name]
|
def unregister_filter(self, attr_name):
"""
Unregister the FilteredImage subclass currently assigned to attr_name.
If a FilteredImage subclass isn't already registered to filters.
`attr_name` NotRegistered will raise.
"""
if attr_name not in self._filter_registry:
raise NotRegistered(
'No FilteredImage subclass is registered to %s' % attr_name
)
else:
del self._filter_registry[attr_name]
|
[
"Unregister",
"the",
"FilteredImage",
"subclass",
"currently",
"assigned",
"to",
"attr_name",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/registry.py#L185-L197
|
[
"def",
"unregister_filter",
"(",
"self",
",",
"attr_name",
")",
":",
"if",
"attr_name",
"not",
"in",
"self",
".",
"_filter_registry",
":",
"raise",
"NotRegistered",
"(",
"'No FilteredImage subclass is registered to %s'",
"%",
"attr_name",
")",
"else",
":",
"del",
"self",
".",
"_filter_registry",
"[",
"attr_name",
"]"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageMixIn.url
|
Return the appropriate URL.
URL is constructed based on these field conditions:
* If empty (not `self.name`) and a placeholder is defined, the
URL to the placeholder is returned.
* Otherwise, defaults to vanilla ImageFieldFile behavior.
|
versatileimagefield/mixins.py
|
def url(self):
"""
Return the appropriate URL.
URL is constructed based on these field conditions:
* If empty (not `self.name`) and a placeholder is defined, the
URL to the placeholder is returned.
* Otherwise, defaults to vanilla ImageFieldFile behavior.
"""
if not self.name and self.field.placeholder_image_name:
return self.storage.url(self.field.placeholder_image_name)
return super(VersatileImageMixIn, self).url
|
def url(self):
"""
Return the appropriate URL.
URL is constructed based on these field conditions:
* If empty (not `self.name`) and a placeholder is defined, the
URL to the placeholder is returned.
* Otherwise, defaults to vanilla ImageFieldFile behavior.
"""
if not self.name and self.field.placeholder_image_name:
return self.storage.url(self.field.placeholder_image_name)
return super(VersatileImageMixIn, self).url
|
[
"Return",
"the",
"appropriate",
"URL",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/mixins.py#L63-L75
|
[
"def",
"url",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"name",
"and",
"self",
".",
"field",
".",
"placeholder_image_name",
":",
"return",
"self",
".",
"storage",
".",
"url",
"(",
"self",
".",
"field",
".",
"placeholder_image_name",
")",
"return",
"super",
"(",
"VersatileImageMixIn",
",",
"self",
")",
".",
"url"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageMixIn.ppoi
|
Primary Point of Interest (ppoi) setter.
|
versatileimagefield/mixins.py
|
def ppoi(self, value):
"""Primary Point of Interest (ppoi) setter."""
ppoi = validate_ppoi(
value,
return_converted_tuple=True
)
if ppoi is not False:
self._ppoi_value = ppoi
self.build_filters_and_sizers(ppoi, self.create_on_demand)
|
def ppoi(self, value):
"""Primary Point of Interest (ppoi) setter."""
ppoi = validate_ppoi(
value,
return_converted_tuple=True
)
if ppoi is not False:
self._ppoi_value = ppoi
self.build_filters_and_sizers(ppoi, self.create_on_demand)
|
[
"Primary",
"Point",
"of",
"Interest",
"(",
"ppoi",
")",
"setter",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/mixins.py#L98-L106
|
[
"def",
"ppoi",
"(",
"self",
",",
"value",
")",
":",
"ppoi",
"=",
"validate_ppoi",
"(",
"value",
",",
"return_converted_tuple",
"=",
"True",
")",
"if",
"ppoi",
"is",
"not",
"False",
":",
"self",
".",
"_ppoi_value",
"=",
"ppoi",
"self",
".",
"build_filters_and_sizers",
"(",
"ppoi",
",",
"self",
".",
"create_on_demand",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageMixIn.build_filters_and_sizers
|
Build the filters and sizers for a field.
|
versatileimagefield/mixins.py
|
def build_filters_and_sizers(self, ppoi_value, create_on_demand):
"""Build the filters and sizers for a field."""
name = self.name
if not name and self.field.placeholder_image_name:
name = self.field.placeholder_image_name
self.filters = FilterLibrary(
name,
self.storage,
versatileimagefield_registry,
ppoi_value,
create_on_demand
)
for (
attr_name,
sizedimage_cls
) in iteritems(versatileimagefield_registry._sizedimage_registry):
setattr(
self,
attr_name,
sizedimage_cls(
path_to_image=name,
storage=self.storage,
create_on_demand=create_on_demand,
ppoi=ppoi_value
)
)
|
def build_filters_and_sizers(self, ppoi_value, create_on_demand):
"""Build the filters and sizers for a field."""
name = self.name
if not name and self.field.placeholder_image_name:
name = self.field.placeholder_image_name
self.filters = FilterLibrary(
name,
self.storage,
versatileimagefield_registry,
ppoi_value,
create_on_demand
)
for (
attr_name,
sizedimage_cls
) in iteritems(versatileimagefield_registry._sizedimage_registry):
setattr(
self,
attr_name,
sizedimage_cls(
path_to_image=name,
storage=self.storage,
create_on_demand=create_on_demand,
ppoi=ppoi_value
)
)
|
[
"Build",
"the",
"filters",
"and",
"sizers",
"for",
"a",
"field",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/mixins.py#L108-L133
|
[
"def",
"build_filters_and_sizers",
"(",
"self",
",",
"ppoi_value",
",",
"create_on_demand",
")",
":",
"name",
"=",
"self",
".",
"name",
"if",
"not",
"name",
"and",
"self",
".",
"field",
".",
"placeholder_image_name",
":",
"name",
"=",
"self",
".",
"field",
".",
"placeholder_image_name",
"self",
".",
"filters",
"=",
"FilterLibrary",
"(",
"name",
",",
"self",
".",
"storage",
",",
"versatileimagefield_registry",
",",
"ppoi_value",
",",
"create_on_demand",
")",
"for",
"(",
"attr_name",
",",
"sizedimage_cls",
")",
"in",
"iteritems",
"(",
"versatileimagefield_registry",
".",
"_sizedimage_registry",
")",
":",
"setattr",
"(",
"self",
",",
"attr_name",
",",
"sizedimage_cls",
"(",
"path_to_image",
"=",
"name",
",",
"storage",
"=",
"self",
".",
"storage",
",",
"create_on_demand",
"=",
"create_on_demand",
",",
"ppoi",
"=",
"ppoi_value",
")",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageMixIn.get_filtered_root_folder
|
Return the location where filtered images are stored.
|
versatileimagefield/mixins.py
|
def get_filtered_root_folder(self):
"""Return the location where filtered images are stored."""
folder, filename = os.path.split(self.name)
return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '')
|
def get_filtered_root_folder(self):
"""Return the location where filtered images are stored."""
folder, filename = os.path.split(self.name)
return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '')
|
[
"Return",
"the",
"location",
"where",
"filtered",
"images",
"are",
"stored",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/mixins.py#L135-L138
|
[
"def",
"get_filtered_root_folder",
"(",
"self",
")",
":",
"folder",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"VERSATILEIMAGEFIELD_FILTERED_DIRNAME",
",",
"''",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageMixIn.get_sized_root_folder
|
Return the location where sized images are stored.
|
versatileimagefield/mixins.py
|
def get_sized_root_folder(self):
"""Return the location where sized images are stored."""
folder, filename = os.path.split(self.name)
return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '')
|
def get_sized_root_folder(self):
"""Return the location where sized images are stored."""
folder, filename = os.path.split(self.name)
return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '')
|
[
"Return",
"the",
"location",
"where",
"sized",
"images",
"are",
"stored",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/mixins.py#L140-L143
|
[
"def",
"get_sized_root_folder",
"(",
"self",
")",
":",
"folder",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"VERSATILEIMAGEFIELD_SIZED_DIRNAME",
",",
"folder",
",",
"''",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageMixIn.get_filtered_sized_root_folder
|
Return the location where filtered + sized images are stored.
|
versatileimagefield/mixins.py
|
def get_filtered_sized_root_folder(self):
"""Return the location where filtered + sized images are stored."""
sized_root_folder = self.get_sized_root_folder()
return os.path.join(
sized_root_folder,
VERSATILEIMAGEFIELD_FILTERED_DIRNAME
)
|
def get_filtered_sized_root_folder(self):
"""Return the location where filtered + sized images are stored."""
sized_root_folder = self.get_sized_root_folder()
return os.path.join(
sized_root_folder,
VERSATILEIMAGEFIELD_FILTERED_DIRNAME
)
|
[
"Return",
"the",
"location",
"where",
"filtered",
"+",
"sized",
"images",
"are",
"stored",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/mixins.py#L145-L151
|
[
"def",
"get_filtered_sized_root_folder",
"(",
"self",
")",
":",
"sized_root_folder",
"=",
"self",
".",
"get_sized_root_folder",
"(",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"sized_root_folder",
",",
"VERSATILEIMAGEFIELD_FILTERED_DIRNAME",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
VersatileImageMixIn.delete_matching_files_from_storage
|
Delete files in `root_folder` which match `regex` before file ext.
Example values:
* root_folder = 'foo/'
* self.name = 'bar.jpg'
* regex = re.compile('-baz')
Result:
* foo/bar-baz.jpg <- Deleted
* foo/bar-biz.jpg <- Not deleted
|
versatileimagefield/mixins.py
|
def delete_matching_files_from_storage(self, root_folder, regex):
"""
Delete files in `root_folder` which match `regex` before file ext.
Example values:
* root_folder = 'foo/'
* self.name = 'bar.jpg'
* regex = re.compile('-baz')
Result:
* foo/bar-baz.jpg <- Deleted
* foo/bar-biz.jpg <- Not deleted
"""
if not self.name: # pragma: no cover
return
try:
directory_list, file_list = self.storage.listdir(root_folder)
except OSError: # pragma: no cover
pass
else:
folder, filename = os.path.split(self.name)
basename, ext = os.path.splitext(filename)
for f in file_list:
if not f.startswith(basename) or not f.endswith(ext): # pragma: no cover
continue
tag = f[len(basename):-len(ext)]
assert f == basename + tag + ext
if regex.match(tag) is not None:
file_location = os.path.join(root_folder, f)
self.storage.delete(file_location)
cache.delete(
self.storage.url(file_location)
)
print(
"Deleted {file} (created from: {original})".format(
file=os.path.join(root_folder, f),
original=self.name
)
)
|
def delete_matching_files_from_storage(self, root_folder, regex):
"""
Delete files in `root_folder` which match `regex` before file ext.
Example values:
* root_folder = 'foo/'
* self.name = 'bar.jpg'
* regex = re.compile('-baz')
Result:
* foo/bar-baz.jpg <- Deleted
* foo/bar-biz.jpg <- Not deleted
"""
if not self.name: # pragma: no cover
return
try:
directory_list, file_list = self.storage.listdir(root_folder)
except OSError: # pragma: no cover
pass
else:
folder, filename = os.path.split(self.name)
basename, ext = os.path.splitext(filename)
for f in file_list:
if not f.startswith(basename) or not f.endswith(ext): # pragma: no cover
continue
tag = f[len(basename):-len(ext)]
assert f == basename + tag + ext
if regex.match(tag) is not None:
file_location = os.path.join(root_folder, f)
self.storage.delete(file_location)
cache.delete(
self.storage.url(file_location)
)
print(
"Deleted {file} (created from: {original})".format(
file=os.path.join(root_folder, f),
original=self.name
)
)
|
[
"Delete",
"files",
"in",
"root_folder",
"which",
"match",
"regex",
"before",
"file",
"ext",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/mixins.py#L153-L191
|
[
"def",
"delete_matching_files_from_storage",
"(",
"self",
",",
"root_folder",
",",
"regex",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"# pragma: no cover",
"return",
"try",
":",
"directory_list",
",",
"file_list",
"=",
"self",
".",
"storage",
".",
"listdir",
"(",
"root_folder",
")",
"except",
"OSError",
":",
"# pragma: no cover",
"pass",
"else",
":",
"folder",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"basename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"for",
"f",
"in",
"file_list",
":",
"if",
"not",
"f",
".",
"startswith",
"(",
"basename",
")",
"or",
"not",
"f",
".",
"endswith",
"(",
"ext",
")",
":",
"# pragma: no cover",
"continue",
"tag",
"=",
"f",
"[",
"len",
"(",
"basename",
")",
":",
"-",
"len",
"(",
"ext",
")",
"]",
"assert",
"f",
"==",
"basename",
"+",
"tag",
"+",
"ext",
"if",
"regex",
".",
"match",
"(",
"tag",
")",
"is",
"not",
"None",
":",
"file_location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_folder",
",",
"f",
")",
"self",
".",
"storage",
".",
"delete",
"(",
"file_location",
")",
"cache",
".",
"delete",
"(",
"self",
".",
"storage",
".",
"url",
"(",
"file_location",
")",
")",
"print",
"(",
"\"Deleted {file} (created from: {original})\"",
".",
"format",
"(",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_folder",
",",
"f",
")",
",",
"original",
"=",
"self",
".",
"name",
")",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
validate_ppoi_tuple
|
Validates that a tuple (`value`)...
...has a len of exactly 2
...both values are floats/ints that are greater-than-or-equal-to 0
AND less-than-or-equal-to 1
|
versatileimagefield/validators.py
|
def validate_ppoi_tuple(value):
"""
Validates that a tuple (`value`)...
...has a len of exactly 2
...both values are floats/ints that are greater-than-or-equal-to 0
AND less-than-or-equal-to 1
"""
valid = True
while valid is True:
if len(value) == 2 and isinstance(value, tuple):
for x in value:
if x >= 0 and x <= 1:
pass
else:
valid = False
break
else:
valid = False
return valid
|
def validate_ppoi_tuple(value):
"""
Validates that a tuple (`value`)...
...has a len of exactly 2
...both values are floats/ints that are greater-than-or-equal-to 0
AND less-than-or-equal-to 1
"""
valid = True
while valid is True:
if len(value) == 2 and isinstance(value, tuple):
for x in value:
if x >= 0 and x <= 1:
pass
else:
valid = False
break
else:
valid = False
return valid
|
[
"Validates",
"that",
"a",
"tuple",
"(",
"value",
")",
"...",
"...",
"has",
"a",
"len",
"of",
"exactly",
"2",
"...",
"both",
"values",
"are",
"floats",
"/",
"ints",
"that",
"are",
"greater",
"-",
"than",
"-",
"or",
"-",
"equal",
"-",
"to",
"0",
"AND",
"less",
"-",
"than",
"-",
"or",
"-",
"equal",
"-",
"to",
"1"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/validators.py#L14-L32
|
[
"def",
"validate_ppoi_tuple",
"(",
"value",
")",
":",
"valid",
"=",
"True",
"while",
"valid",
"is",
"True",
":",
"if",
"len",
"(",
"value",
")",
"==",
"2",
"and",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"for",
"x",
"in",
"value",
":",
"if",
"x",
">=",
"0",
"and",
"x",
"<=",
"1",
":",
"pass",
"else",
":",
"valid",
"=",
"False",
"break",
"else",
":",
"valid",
"=",
"False",
"return",
"valid"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
validate_ppoi
|
Converts, validates and optionally returns a string with formatting:
'%(x_axis)dx%(y_axis)d' into a two position tuple.
If a tuple is passed to `value` it is also validated.
Both x_axis and y_axis must be floats or ints greater
than 0 and less than 1.
|
versatileimagefield/validators.py
|
def validate_ppoi(value, return_converted_tuple=False):
"""
Converts, validates and optionally returns a string with formatting:
'%(x_axis)dx%(y_axis)d' into a two position tuple.
If a tuple is passed to `value` it is also validated.
Both x_axis and y_axis must be floats or ints greater
than 0 and less than 1.
"""
valid_ppoi = True
to_return = None
if isinstance(value, tuple):
valid_ppoi = validate_ppoi_tuple(value)
if valid_ppoi:
to_return = value
else:
tup = tuple()
try:
string_split = [
float(segment.strip())
for segment in value.split('x')
if float(segment.strip()) >= 0 and float(segment.strip()) <= 1
]
except Exception:
valid_ppoi = False
else:
tup = tuple(string_split)
valid_ppoi = validate_ppoi_tuple(tup)
if valid_ppoi:
to_return = tup
if not valid_ppoi:
raise ValidationError(
message=INVALID_CENTERPOINT_ERROR_MESSAGE % str(value),
code='invalid_ppoi'
)
else:
if to_return and return_converted_tuple is True:
return to_return
|
def validate_ppoi(value, return_converted_tuple=False):
"""
Converts, validates and optionally returns a string with formatting:
'%(x_axis)dx%(y_axis)d' into a two position tuple.
If a tuple is passed to `value` it is also validated.
Both x_axis and y_axis must be floats or ints greater
than 0 and less than 1.
"""
valid_ppoi = True
to_return = None
if isinstance(value, tuple):
valid_ppoi = validate_ppoi_tuple(value)
if valid_ppoi:
to_return = value
else:
tup = tuple()
try:
string_split = [
float(segment.strip())
for segment in value.split('x')
if float(segment.strip()) >= 0 and float(segment.strip()) <= 1
]
except Exception:
valid_ppoi = False
else:
tup = tuple(string_split)
valid_ppoi = validate_ppoi_tuple(tup)
if valid_ppoi:
to_return = tup
if not valid_ppoi:
raise ValidationError(
message=INVALID_CENTERPOINT_ERROR_MESSAGE % str(value),
code='invalid_ppoi'
)
else:
if to_return and return_converted_tuple is True:
return to_return
|
[
"Converts",
"validates",
"and",
"optionally",
"returns",
"a",
"string",
"with",
"formatting",
":",
"%",
"(",
"x_axis",
")",
"dx%",
"(",
"y_axis",
")",
"d",
"into",
"a",
"two",
"position",
"tuple",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/validators.py#L35-L76
|
[
"def",
"validate_ppoi",
"(",
"value",
",",
"return_converted_tuple",
"=",
"False",
")",
":",
"valid_ppoi",
"=",
"True",
"to_return",
"=",
"None",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"valid_ppoi",
"=",
"validate_ppoi_tuple",
"(",
"value",
")",
"if",
"valid_ppoi",
":",
"to_return",
"=",
"value",
"else",
":",
"tup",
"=",
"tuple",
"(",
")",
"try",
":",
"string_split",
"=",
"[",
"float",
"(",
"segment",
".",
"strip",
"(",
")",
")",
"for",
"segment",
"in",
"value",
".",
"split",
"(",
"'x'",
")",
"if",
"float",
"(",
"segment",
".",
"strip",
"(",
")",
")",
">=",
"0",
"and",
"float",
"(",
"segment",
".",
"strip",
"(",
")",
")",
"<=",
"1",
"]",
"except",
"Exception",
":",
"valid_ppoi",
"=",
"False",
"else",
":",
"tup",
"=",
"tuple",
"(",
"string_split",
")",
"valid_ppoi",
"=",
"validate_ppoi_tuple",
"(",
"tup",
")",
"if",
"valid_ppoi",
":",
"to_return",
"=",
"tup",
"if",
"not",
"valid_ppoi",
":",
"raise",
"ValidationError",
"(",
"message",
"=",
"INVALID_CENTERPOINT_ERROR_MESSAGE",
"%",
"str",
"(",
"value",
")",
",",
"code",
"=",
"'invalid_ppoi'",
")",
"else",
":",
"if",
"to_return",
"and",
"return_converted_tuple",
"is",
"True",
":",
"return",
"to_return"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ProcessedImage.preprocess
|
Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`image` will be passed to it.
Arguments:
* `image`: a PIL Image instance
* `image_format`: str, a valid PIL format (i.e. 'JPEG' or 'GIF')
Subclasses should return a 2-tuple:
* [0]: A PIL Image instance.
* [1]: A dictionary of additional keyword arguments to be used
when the instance is saved. If no additional keyword
arguments, return an empty dict ({}).
|
versatileimagefield/datastructures/base.py
|
def preprocess(self, image, image_format):
"""
Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`image` will be passed to it.
Arguments:
* `image`: a PIL Image instance
* `image_format`: str, a valid PIL format (i.e. 'JPEG' or 'GIF')
Subclasses should return a 2-tuple:
* [0]: A PIL Image instance.
* [1]: A dictionary of additional keyword arguments to be used
when the instance is saved. If no additional keyword
arguments, return an empty dict ({}).
"""
save_kwargs = {'format': image_format}
# Ensuring image is properly rotated
if hasattr(image, '_getexif'):
exif_datadict = image._getexif() # returns None if no EXIF data
if exif_datadict is not None:
exif = dict(exif_datadict.items())
orientation = exif.get(EXIF_ORIENTATION_KEY, None)
if orientation == 3:
image = image.transpose(Image.ROTATE_180)
elif orientation == 6:
image = image.transpose(Image.ROTATE_270)
elif orientation == 8:
image = image.transpose(Image.ROTATE_90)
# Ensure any embedded ICC profile is preserved
save_kwargs['icc_profile'] = image.info.get('icc_profile')
if hasattr(self, 'preprocess_%s' % image_format):
image, addl_save_kwargs = getattr(
self,
'preprocess_%s' % image_format
)(image=image)
save_kwargs.update(addl_save_kwargs)
return image, save_kwargs
|
def preprocess(self, image, image_format):
"""
Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`image` will be passed to it.
Arguments:
* `image`: a PIL Image instance
* `image_format`: str, a valid PIL format (i.e. 'JPEG' or 'GIF')
Subclasses should return a 2-tuple:
* [0]: A PIL Image instance.
* [1]: A dictionary of additional keyword arguments to be used
when the instance is saved. If no additional keyword
arguments, return an empty dict ({}).
"""
save_kwargs = {'format': image_format}
# Ensuring image is properly rotated
if hasattr(image, '_getexif'):
exif_datadict = image._getexif() # returns None if no EXIF data
if exif_datadict is not None:
exif = dict(exif_datadict.items())
orientation = exif.get(EXIF_ORIENTATION_KEY, None)
if orientation == 3:
image = image.transpose(Image.ROTATE_180)
elif orientation == 6:
image = image.transpose(Image.ROTATE_270)
elif orientation == 8:
image = image.transpose(Image.ROTATE_90)
# Ensure any embedded ICC profile is preserved
save_kwargs['icc_profile'] = image.info.get('icc_profile')
if hasattr(self, 'preprocess_%s' % image_format):
image, addl_save_kwargs = getattr(
self,
'preprocess_%s' % image_format
)(image=image)
save_kwargs.update(addl_save_kwargs)
return image, save_kwargs
|
[
"Preprocess",
"an",
"image",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/base.py#L60-L104
|
[
"def",
"preprocess",
"(",
"self",
",",
"image",
",",
"image_format",
")",
":",
"save_kwargs",
"=",
"{",
"'format'",
":",
"image_format",
"}",
"# Ensuring image is properly rotated",
"if",
"hasattr",
"(",
"image",
",",
"'_getexif'",
")",
":",
"exif_datadict",
"=",
"image",
".",
"_getexif",
"(",
")",
"# returns None if no EXIF data",
"if",
"exif_datadict",
"is",
"not",
"None",
":",
"exif",
"=",
"dict",
"(",
"exif_datadict",
".",
"items",
"(",
")",
")",
"orientation",
"=",
"exif",
".",
"get",
"(",
"EXIF_ORIENTATION_KEY",
",",
"None",
")",
"if",
"orientation",
"==",
"3",
":",
"image",
"=",
"image",
".",
"transpose",
"(",
"Image",
".",
"ROTATE_180",
")",
"elif",
"orientation",
"==",
"6",
":",
"image",
"=",
"image",
".",
"transpose",
"(",
"Image",
".",
"ROTATE_270",
")",
"elif",
"orientation",
"==",
"8",
":",
"image",
"=",
"image",
".",
"transpose",
"(",
"Image",
".",
"ROTATE_90",
")",
"# Ensure any embedded ICC profile is preserved",
"save_kwargs",
"[",
"'icc_profile'",
"]",
"=",
"image",
".",
"info",
".",
"get",
"(",
"'icc_profile'",
")",
"if",
"hasattr",
"(",
"self",
",",
"'preprocess_%s'",
"%",
"image_format",
")",
":",
"image",
",",
"addl_save_kwargs",
"=",
"getattr",
"(",
"self",
",",
"'preprocess_%s'",
"%",
"image_format",
")",
"(",
"image",
"=",
"image",
")",
"save_kwargs",
".",
"update",
"(",
"addl_save_kwargs",
")",
"return",
"image",
",",
"save_kwargs"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ProcessedImage.preprocess_GIF
|
Receive a PIL Image instance of a GIF and return 2-tuple.
Args:
* [0]: Original Image instance (passed to `image`)
* [1]: Dict with a transparency key (to GIF transparency layer)
|
versatileimagefield/datastructures/base.py
|
def preprocess_GIF(self, image, **kwargs):
"""
Receive a PIL Image instance of a GIF and return 2-tuple.
Args:
* [0]: Original Image instance (passed to `image`)
* [1]: Dict with a transparency key (to GIF transparency layer)
"""
if 'transparency' in image.info:
save_kwargs = {'transparency': image.info['transparency']}
else:
save_kwargs = {}
return (image, save_kwargs)
|
def preprocess_GIF(self, image, **kwargs):
"""
Receive a PIL Image instance of a GIF and return 2-tuple.
Args:
* [0]: Original Image instance (passed to `image`)
* [1]: Dict with a transparency key (to GIF transparency layer)
"""
if 'transparency' in image.info:
save_kwargs = {'transparency': image.info['transparency']}
else:
save_kwargs = {}
return (image, save_kwargs)
|
[
"Receive",
"a",
"PIL",
"Image",
"instance",
"of",
"a",
"GIF",
"and",
"return",
"2",
"-",
"tuple",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/base.py#L106-L118
|
[
"def",
"preprocess_GIF",
"(",
"self",
",",
"image",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'transparency'",
"in",
"image",
".",
"info",
":",
"save_kwargs",
"=",
"{",
"'transparency'",
":",
"image",
".",
"info",
"[",
"'transparency'",
"]",
"}",
"else",
":",
"save_kwargs",
"=",
"{",
"}",
"return",
"(",
"image",
",",
"save_kwargs",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ProcessedImage.preprocess_JPEG
|
Receive a PIL Image instance of a JPEG and returns 2-tuple.
Args:
* [0]: Image instance, converted to RGB
* [1]: Dict with a quality key (mapped to the value of `QUAL` as
defined by the `VERSATILEIMAGEFIELD_JPEG_RESIZE_QUALITY`
setting)
|
versatileimagefield/datastructures/base.py
|
def preprocess_JPEG(self, image, **kwargs):
"""
Receive a PIL Image instance of a JPEG and returns 2-tuple.
Args:
* [0]: Image instance, converted to RGB
* [1]: Dict with a quality key (mapped to the value of `QUAL` as
defined by the `VERSATILEIMAGEFIELD_JPEG_RESIZE_QUALITY`
setting)
"""
save_kwargs = {
'progressive': VERSATILEIMAGEFIELD_PROGRESSIVE_JPEG,
'quality': QUAL
}
if image.mode != 'RGB':
image = image.convert('RGB')
return (image, save_kwargs)
|
def preprocess_JPEG(self, image, **kwargs):
"""
Receive a PIL Image instance of a JPEG and returns 2-tuple.
Args:
* [0]: Image instance, converted to RGB
* [1]: Dict with a quality key (mapped to the value of `QUAL` as
defined by the `VERSATILEIMAGEFIELD_JPEG_RESIZE_QUALITY`
setting)
"""
save_kwargs = {
'progressive': VERSATILEIMAGEFIELD_PROGRESSIVE_JPEG,
'quality': QUAL
}
if image.mode != 'RGB':
image = image.convert('RGB')
return (image, save_kwargs)
|
[
"Receive",
"a",
"PIL",
"Image",
"instance",
"of",
"a",
"JPEG",
"and",
"returns",
"2",
"-",
"tuple",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/base.py#L120-L136
|
[
"def",
"preprocess_JPEG",
"(",
"self",
",",
"image",
",",
"*",
"*",
"kwargs",
")",
":",
"save_kwargs",
"=",
"{",
"'progressive'",
":",
"VERSATILEIMAGEFIELD_PROGRESSIVE_JPEG",
",",
"'quality'",
":",
"QUAL",
"}",
"if",
"image",
".",
"mode",
"!=",
"'RGB'",
":",
"image",
"=",
"image",
".",
"convert",
"(",
"'RGB'",
")",
"return",
"(",
"image",
",",
"save_kwargs",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ProcessedImage.retrieve_image
|
Return a PIL Image instance stored at `path_to_image`.
|
versatileimagefield/datastructures/base.py
|
def retrieve_image(self, path_to_image):
"""Return a PIL Image instance stored at `path_to_image`."""
image = self.storage.open(path_to_image, 'rb')
file_ext = path_to_image.rsplit('.')[-1]
image_format, mime_type = get_image_metadata_from_file_ext(file_ext)
return (
Image.open(image),
file_ext,
image_format,
mime_type
)
|
def retrieve_image(self, path_to_image):
"""Return a PIL Image instance stored at `path_to_image`."""
image = self.storage.open(path_to_image, 'rb')
file_ext = path_to_image.rsplit('.')[-1]
image_format, mime_type = get_image_metadata_from_file_ext(file_ext)
return (
Image.open(image),
file_ext,
image_format,
mime_type
)
|
[
"Return",
"a",
"PIL",
"Image",
"instance",
"stored",
"at",
"path_to_image",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/base.py#L138-L149
|
[
"def",
"retrieve_image",
"(",
"self",
",",
"path_to_image",
")",
":",
"image",
"=",
"self",
".",
"storage",
".",
"open",
"(",
"path_to_image",
",",
"'rb'",
")",
"file_ext",
"=",
"path_to_image",
".",
"rsplit",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"image_format",
",",
"mime_type",
"=",
"get_image_metadata_from_file_ext",
"(",
"file_ext",
")",
"return",
"(",
"Image",
".",
"open",
"(",
"image",
")",
",",
"file_ext",
",",
"image_format",
",",
"mime_type",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ProcessedImage.save_image
|
Save an image to self.storage at `save_path`.
Arguments:
`imagefile`: Raw image data, typically a BytesIO instance.
`save_path`: The path within self.storage where the image should
be saved.
`file_ext`: The file extension of the image-to-be-saved.
`mime_type`: A valid image mime type (as found in
versatileimagefield.utils)
|
versatileimagefield/datastructures/base.py
|
def save_image(self, imagefile, save_path, file_ext, mime_type):
"""
Save an image to self.storage at `save_path`.
Arguments:
`imagefile`: Raw image data, typically a BytesIO instance.
`save_path`: The path within self.storage where the image should
be saved.
`file_ext`: The file extension of the image-to-be-saved.
`mime_type`: A valid image mime type (as found in
versatileimagefield.utils)
"""
file_to_save = InMemoryUploadedFile(
imagefile,
None,
'foo.%s' % file_ext,
mime_type,
imagefile.tell(),
None
)
file_to_save.seek(0)
self.storage.save(save_path, file_to_save)
|
def save_image(self, imagefile, save_path, file_ext, mime_type):
"""
Save an image to self.storage at `save_path`.
Arguments:
`imagefile`: Raw image data, typically a BytesIO instance.
`save_path`: The path within self.storage where the image should
be saved.
`file_ext`: The file extension of the image-to-be-saved.
`mime_type`: A valid image mime type (as found in
versatileimagefield.utils)
"""
file_to_save = InMemoryUploadedFile(
imagefile,
None,
'foo.%s' % file_ext,
mime_type,
imagefile.tell(),
None
)
file_to_save.seek(0)
self.storage.save(save_path, file_to_save)
|
[
"Save",
"an",
"image",
"to",
"self",
".",
"storage",
"at",
"save_path",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/base.py#L151-L172
|
[
"def",
"save_image",
"(",
"self",
",",
"imagefile",
",",
"save_path",
",",
"file_ext",
",",
"mime_type",
")",
":",
"file_to_save",
"=",
"InMemoryUploadedFile",
"(",
"imagefile",
",",
"None",
",",
"'foo.%s'",
"%",
"file_ext",
",",
"mime_type",
",",
"imagefile",
".",
"tell",
"(",
")",
",",
"None",
")",
"file_to_save",
".",
"seek",
"(",
"0",
")",
"self",
".",
"storage",
".",
"save",
"(",
"save_path",
",",
"file_to_save",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
SizedImage.ppoi_as_str
|
Return PPOI value as a string.
|
versatileimagefield/datastructures/sizedimage.py
|
def ppoi_as_str(self):
"""Return PPOI value as a string."""
return "%s__%s" % (
str(self.ppoi[0]).replace('.', '-'),
str(self.ppoi[1]).replace('.', '-')
)
|
def ppoi_as_str(self):
"""Return PPOI value as a string."""
return "%s__%s" % (
str(self.ppoi[0]).replace('.', '-'),
str(self.ppoi[1]).replace('.', '-')
)
|
[
"Return",
"PPOI",
"value",
"as",
"a",
"string",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/sizedimage.py#L64-L69
|
[
"def",
"ppoi_as_str",
"(",
"self",
")",
":",
"return",
"\"%s__%s\"",
"%",
"(",
"str",
"(",
"self",
".",
"ppoi",
"[",
"0",
"]",
")",
".",
"replace",
"(",
"'.'",
",",
"'-'",
")",
",",
"str",
"(",
"self",
".",
"ppoi",
"[",
"1",
"]",
")",
".",
"replace",
"(",
"'.'",
",",
"'-'",
")",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
SizedImage.create_resized_image
|
Create a resized image.
`path_to_image`: The path to the image with the media directory to
resize. If `None`, the
VERSATILEIMAGEFIELD_PLACEHOLDER_IMAGE will be used.
`save_path_on_storage`: Where on self.storage to save the resized image
`width`: Width of resized image (int)
`height`: Desired height of resized image (int)
`filename_key`: A string that will be used in the sized image filename
to signify what operation was done to it.
Examples: 'crop' or 'scale'
|
versatileimagefield/datastructures/sizedimage.py
|
def create_resized_image(self, path_to_image, save_path_on_storage,
width, height):
"""
Create a resized image.
`path_to_image`: The path to the image with the media directory to
resize. If `None`, the
VERSATILEIMAGEFIELD_PLACEHOLDER_IMAGE will be used.
`save_path_on_storage`: Where on self.storage to save the resized image
`width`: Width of resized image (int)
`height`: Desired height of resized image (int)
`filename_key`: A string that will be used in the sized image filename
to signify what operation was done to it.
Examples: 'crop' or 'scale'
"""
image, file_ext, image_format, mime_type = self.retrieve_image(
path_to_image
)
image, save_kwargs = self.preprocess(image, image_format)
imagefile = self.process_image(
image=image,
image_format=image_format,
save_kwargs=save_kwargs,
width=width,
height=height
)
self.save_image(imagefile, save_path_on_storage, file_ext, mime_type)
|
def create_resized_image(self, path_to_image, save_path_on_storage,
width, height):
"""
Create a resized image.
`path_to_image`: The path to the image with the media directory to
resize. If `None`, the
VERSATILEIMAGEFIELD_PLACEHOLDER_IMAGE will be used.
`save_path_on_storage`: Where on self.storage to save the resized image
`width`: Width of resized image (int)
`height`: Desired height of resized image (int)
`filename_key`: A string that will be used in the sized image filename
to signify what operation was done to it.
Examples: 'crop' or 'scale'
"""
image, file_ext, image_format, mime_type = self.retrieve_image(
path_to_image
)
image, save_kwargs = self.preprocess(image, image_format)
imagefile = self.process_image(
image=image,
image_format=image_format,
save_kwargs=save_kwargs,
width=width,
height=height
)
self.save_image(imagefile, save_path_on_storage, file_ext, mime_type)
|
[
"Create",
"a",
"resized",
"image",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/sizedimage.py#L185-L213
|
[
"def",
"create_resized_image",
"(",
"self",
",",
"path_to_image",
",",
"save_path_on_storage",
",",
"width",
",",
"height",
")",
":",
"image",
",",
"file_ext",
",",
"image_format",
",",
"mime_type",
"=",
"self",
".",
"retrieve_image",
"(",
"path_to_image",
")",
"image",
",",
"save_kwargs",
"=",
"self",
".",
"preprocess",
"(",
"image",
",",
"image_format",
")",
"imagefile",
"=",
"self",
".",
"process_image",
"(",
"image",
"=",
"image",
",",
"image_format",
"=",
"image_format",
",",
"save_kwargs",
"=",
"save_kwargs",
",",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
"self",
".",
"save_image",
"(",
"imagefile",
",",
"save_path_on_storage",
",",
"file_ext",
",",
"mime_type",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ClearableFileInputWithImagePreview.render
|
Render the widget as an HTML string.
Overridden here to support Django < 1.11.
|
versatileimagefield/widgets.py
|
def render(self, name, value, attrs=None, renderer=None):
"""
Render the widget as an HTML string.
Overridden here to support Django < 1.11.
"""
if self.has_template_widget_rendering:
return super(ClearableFileInputWithImagePreview, self).render(
name, value, attrs=attrs, renderer=renderer
)
else:
context = self.get_context(name, value, attrs)
return render_to_string(self.template_name, context)
|
def render(self, name, value, attrs=None, renderer=None):
"""
Render the widget as an HTML string.
Overridden here to support Django < 1.11.
"""
if self.has_template_widget_rendering:
return super(ClearableFileInputWithImagePreview, self).render(
name, value, attrs=attrs, renderer=renderer
)
else:
context = self.get_context(name, value, attrs)
return render_to_string(self.template_name, context)
|
[
"Render",
"the",
"widget",
"as",
"an",
"HTML",
"string",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/widgets.py#L41-L53
|
[
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"renderer",
"=",
"None",
")",
":",
"if",
"self",
".",
"has_template_widget_rendering",
":",
"return",
"super",
"(",
"ClearableFileInputWithImagePreview",
",",
"self",
")",
".",
"render",
"(",
"name",
",",
"value",
",",
"attrs",
"=",
"attrs",
",",
"renderer",
"=",
"renderer",
")",
"else",
":",
"context",
"=",
"self",
".",
"get_context",
"(",
"name",
",",
"value",
",",
"attrs",
")",
"return",
"render_to_string",
"(",
"self",
".",
"template_name",
",",
"context",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ClearableFileInputWithImagePreview.get_context
|
Get the context to render this widget with.
|
versatileimagefield/widgets.py
|
def get_context(self, name, value, attrs):
"""Get the context to render this widget with."""
if self.has_template_widget_rendering:
context = super(ClearableFileInputWithImagePreview, self).get_context(name, value, attrs)
else:
# Build the context manually.
context = {}
context['widget'] = {
'name': name,
'is_hidden': self.is_hidden,
'required': self.is_required,
'value': self._format_value(value),
'attrs': self.build_attrs(self.attrs, attrs),
'template_name': self.template_name,
'type': self.input_type,
}
# It seems Django 1.11's ClearableFileInput doesn't add everything to the 'widget' key, so we can't use it
# in MultiWidget. Add it manually here.
checkbox_name = self.clear_checkbox_name(name)
checkbox_id = self.clear_checkbox_id(checkbox_name)
context['widget'].update({
'checkbox_name': checkbox_name,
'checkbox_id': checkbox_id,
'is_initial': self.is_initial(value),
'input_text': self.input_text,
'initial_text': self.initial_text,
'clear_checkbox_label': self.clear_checkbox_label,
})
if value and hasattr(value, "url"):
context['widget'].update({
'hidden_field_id': self.get_hidden_field_id(name),
'point_stage_id': self.get_point_stage_id(name),
'ppoi_id': self.get_ppoi_id(name),
'sized_url': self.get_sized_url(value),
'image_preview_id': self.image_preview_id(name),
})
return context
|
def get_context(self, name, value, attrs):
"""Get the context to render this widget with."""
if self.has_template_widget_rendering:
context = super(ClearableFileInputWithImagePreview, self).get_context(name, value, attrs)
else:
# Build the context manually.
context = {}
context['widget'] = {
'name': name,
'is_hidden': self.is_hidden,
'required': self.is_required,
'value': self._format_value(value),
'attrs': self.build_attrs(self.attrs, attrs),
'template_name': self.template_name,
'type': self.input_type,
}
# It seems Django 1.11's ClearableFileInput doesn't add everything to the 'widget' key, so we can't use it
# in MultiWidget. Add it manually here.
checkbox_name = self.clear_checkbox_name(name)
checkbox_id = self.clear_checkbox_id(checkbox_name)
context['widget'].update({
'checkbox_name': checkbox_name,
'checkbox_id': checkbox_id,
'is_initial': self.is_initial(value),
'input_text': self.input_text,
'initial_text': self.initial_text,
'clear_checkbox_label': self.clear_checkbox_label,
})
if value and hasattr(value, "url"):
context['widget'].update({
'hidden_field_id': self.get_hidden_field_id(name),
'point_stage_id': self.get_point_stage_id(name),
'ppoi_id': self.get_ppoi_id(name),
'sized_url': self.get_sized_url(value),
'image_preview_id': self.image_preview_id(name),
})
return context
|
[
"Get",
"the",
"context",
"to",
"render",
"this",
"widget",
"with",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/widgets.py#L66-L106
|
[
"def",
"get_context",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
")",
":",
"if",
"self",
".",
"has_template_widget_rendering",
":",
"context",
"=",
"super",
"(",
"ClearableFileInputWithImagePreview",
",",
"self",
")",
".",
"get_context",
"(",
"name",
",",
"value",
",",
"attrs",
")",
"else",
":",
"# Build the context manually.",
"context",
"=",
"{",
"}",
"context",
"[",
"'widget'",
"]",
"=",
"{",
"'name'",
":",
"name",
",",
"'is_hidden'",
":",
"self",
".",
"is_hidden",
",",
"'required'",
":",
"self",
".",
"is_required",
",",
"'value'",
":",
"self",
".",
"_format_value",
"(",
"value",
")",
",",
"'attrs'",
":",
"self",
".",
"build_attrs",
"(",
"self",
".",
"attrs",
",",
"attrs",
")",
",",
"'template_name'",
":",
"self",
".",
"template_name",
",",
"'type'",
":",
"self",
".",
"input_type",
",",
"}",
"# It seems Django 1.11's ClearableFileInput doesn't add everything to the 'widget' key, so we can't use it",
"# in MultiWidget. Add it manually here.",
"checkbox_name",
"=",
"self",
".",
"clear_checkbox_name",
"(",
"name",
")",
"checkbox_id",
"=",
"self",
".",
"clear_checkbox_id",
"(",
"checkbox_name",
")",
"context",
"[",
"'widget'",
"]",
".",
"update",
"(",
"{",
"'checkbox_name'",
":",
"checkbox_name",
",",
"'checkbox_id'",
":",
"checkbox_id",
",",
"'is_initial'",
":",
"self",
".",
"is_initial",
"(",
"value",
")",
",",
"'input_text'",
":",
"self",
".",
"input_text",
",",
"'initial_text'",
":",
"self",
".",
"initial_text",
",",
"'clear_checkbox_label'",
":",
"self",
".",
"clear_checkbox_label",
",",
"}",
")",
"if",
"value",
"and",
"hasattr",
"(",
"value",
",",
"\"url\"",
")",
":",
"context",
"[",
"'widget'",
"]",
".",
"update",
"(",
"{",
"'hidden_field_id'",
":",
"self",
".",
"get_hidden_field_id",
"(",
"name",
")",
",",
"'point_stage_id'",
":",
"self",
".",
"get_point_stage_id",
"(",
"name",
")",
",",
"'ppoi_id'",
":",
"self",
".",
"get_ppoi_id",
"(",
"name",
")",
",",
"'sized_url'",
":",
"self",
".",
"get_sized_url",
"(",
"value",
")",
",",
"'image_preview_id'",
":",
"self",
".",
"image_preview_id",
"(",
"name",
")",
",",
"}",
")",
"return",
"context"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
ClearableFileInputWithImagePreview.build_attrs
|
Build an attribute dictionary.
|
versatileimagefield/widgets.py
|
def build_attrs(self, base_attrs, extra_attrs=None):
"""Build an attribute dictionary."""
attrs = base_attrs.copy()
if extra_attrs is not None:
attrs.update(extra_attrs)
return attrs
|
def build_attrs(self, base_attrs, extra_attrs=None):
"""Build an attribute dictionary."""
attrs = base_attrs.copy()
if extra_attrs is not None:
attrs.update(extra_attrs)
return attrs
|
[
"Build",
"an",
"attribute",
"dictionary",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/widgets.py#L108-L113
|
[
"def",
"build_attrs",
"(",
"self",
",",
"base_attrs",
",",
"extra_attrs",
"=",
"None",
")",
":",
"attrs",
"=",
"base_attrs",
".",
"copy",
"(",
")",
"if",
"extra_attrs",
"is",
"not",
"None",
":",
"attrs",
".",
"update",
"(",
"extra_attrs",
")",
"return",
"attrs"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
get_resized_filename
|
Return the 'resized filename' (according to `width`, `height` and
`filename_key`) in the following format:
`filename`-`filename_key`-`width`x`height`.ext
|
versatileimagefield/utils.py
|
def get_resized_filename(filename, width, height, filename_key):
"""
Return the 'resized filename' (according to `width`, `height` and
`filename_key`) in the following format:
`filename`-`filename_key`-`width`x`height`.ext
"""
try:
image_name, ext = filename.rsplit('.', 1)
except ValueError:
image_name = filename
ext = 'jpg'
resized_template = "%(filename_key)s-%(width)dx%(height)d"
if ext.lower() in ['jpg', 'jpeg']:
resized_template = resized_template + "-%(quality)d"
resized_key = resized_template % ({
'filename_key': filename_key,
'width': width,
'height': height,
'quality': QUAL
})
return "%(image_name)s-%(image_key)s.%(ext)s" % ({
'image_name': image_name,
'image_key': post_process_image_key(resized_key),
'ext': ext
})
|
def get_resized_filename(filename, width, height, filename_key):
"""
Return the 'resized filename' (according to `width`, `height` and
`filename_key`) in the following format:
`filename`-`filename_key`-`width`x`height`.ext
"""
try:
image_name, ext = filename.rsplit('.', 1)
except ValueError:
image_name = filename
ext = 'jpg'
resized_template = "%(filename_key)s-%(width)dx%(height)d"
if ext.lower() in ['jpg', 'jpeg']:
resized_template = resized_template + "-%(quality)d"
resized_key = resized_template % ({
'filename_key': filename_key,
'width': width,
'height': height,
'quality': QUAL
})
return "%(image_name)s-%(image_key)s.%(ext)s" % ({
'image_name': image_name,
'image_key': post_process_image_key(resized_key),
'ext': ext
})
|
[
"Return",
"the",
"resized",
"filename",
"(",
"according",
"to",
"width",
"height",
"and",
"filename_key",
")",
"in",
"the",
"following",
"format",
":",
"filename",
"-",
"filename_key",
"-",
"width",
"x",
"height",
".",
"ext"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L77-L104
|
[
"def",
"get_resized_filename",
"(",
"filename",
",",
"width",
",",
"height",
",",
"filename_key",
")",
":",
"try",
":",
"image_name",
",",
"ext",
"=",
"filename",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":",
"image_name",
"=",
"filename",
"ext",
"=",
"'jpg'",
"resized_template",
"=",
"\"%(filename_key)s-%(width)dx%(height)d\"",
"if",
"ext",
".",
"lower",
"(",
")",
"in",
"[",
"'jpg'",
",",
"'jpeg'",
"]",
":",
"resized_template",
"=",
"resized_template",
"+",
"\"-%(quality)d\"",
"resized_key",
"=",
"resized_template",
"%",
"(",
"{",
"'filename_key'",
":",
"filename_key",
",",
"'width'",
":",
"width",
",",
"'height'",
":",
"height",
",",
"'quality'",
":",
"QUAL",
"}",
")",
"return",
"\"%(image_name)s-%(image_key)s.%(ext)s\"",
"%",
"(",
"{",
"'image_name'",
":",
"image_name",
",",
"'image_key'",
":",
"post_process_image_key",
"(",
"resized_key",
")",
",",
"'ext'",
":",
"ext",
"}",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
get_resized_path
|
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
|
versatileimagefield/utils.py
|
def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
"""
containing_folder, filename = os.path.split(path_to_image)
resized_filename = get_resized_filename(
filename,
width,
height,
filename_key
)
joined_path = os.path.join(*[
VERSATILEIMAGEFIELD_SIZED_DIRNAME,
containing_folder,
resized_filename
]).replace(' ', '') # Removing spaces so this path is memcached friendly
return joined_path
|
def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
"""
containing_folder, filename = os.path.split(path_to_image)
resized_filename = get_resized_filename(
filename,
width,
height,
filename_key
)
joined_path = os.path.join(*[
VERSATILEIMAGEFIELD_SIZED_DIRNAME,
containing_folder,
resized_filename
]).replace(' ', '') # Removing spaces so this path is memcached friendly
return joined_path
|
[
"Return",
"a",
"path_to_image",
"location",
"on",
"storage",
"as",
"dictated",
"by",
"width",
"height",
"and",
"filename_key"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L107-L128
|
[
"def",
"get_resized_path",
"(",
"path_to_image",
",",
"width",
",",
"height",
",",
"filename_key",
",",
"storage",
")",
":",
"containing_folder",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path_to_image",
")",
"resized_filename",
"=",
"get_resized_filename",
"(",
"filename",
",",
"width",
",",
"height",
",",
"filename_key",
")",
"joined_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"[",
"VERSATILEIMAGEFIELD_SIZED_DIRNAME",
",",
"containing_folder",
",",
"resized_filename",
"]",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"# Removing spaces so this path is memcached friendly",
"return",
"joined_path"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
get_filtered_filename
|
Return the 'filtered filename' (according to `filename_key`)
in the following format:
`filename`__`filename_key`__.ext
|
versatileimagefield/utils.py
|
def get_filtered_filename(filename, filename_key):
"""
Return the 'filtered filename' (according to `filename_key`)
in the following format:
`filename`__`filename_key`__.ext
"""
try:
image_name, ext = filename.rsplit('.', 1)
except ValueError:
image_name = filename
ext = 'jpg'
return "%(image_name)s__%(filename_key)s__.%(ext)s" % ({
'image_name': image_name,
'filename_key': filename_key,
'ext': ext
})
|
def get_filtered_filename(filename, filename_key):
"""
Return the 'filtered filename' (according to `filename_key`)
in the following format:
`filename`__`filename_key`__.ext
"""
try:
image_name, ext = filename.rsplit('.', 1)
except ValueError:
image_name = filename
ext = 'jpg'
return "%(image_name)s__%(filename_key)s__.%(ext)s" % ({
'image_name': image_name,
'filename_key': filename_key,
'ext': ext
})
|
[
"Return",
"the",
"filtered",
"filename",
"(",
"according",
"to",
"filename_key",
")",
"in",
"the",
"following",
"format",
":",
"filename",
"__",
"filename_key",
"__",
".",
"ext"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L131-L146
|
[
"def",
"get_filtered_filename",
"(",
"filename",
",",
"filename_key",
")",
":",
"try",
":",
"image_name",
",",
"ext",
"=",
"filename",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":",
"image_name",
"=",
"filename",
"ext",
"=",
"'jpg'",
"return",
"\"%(image_name)s__%(filename_key)s__.%(ext)s\"",
"%",
"(",
"{",
"'image_name'",
":",
"image_name",
",",
"'filename_key'",
":",
"filename_key",
",",
"'ext'",
":",
"ext",
"}",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
get_filtered_path
|
Return the 'filtered path'
|
versatileimagefield/utils.py
|
def get_filtered_path(path_to_image, filename_key, storage):
"""
Return the 'filtered path'
"""
containing_folder, filename = os.path.split(path_to_image)
filtered_filename = get_filtered_filename(filename, filename_key)
path_to_return = os.path.join(*[
containing_folder,
VERSATILEIMAGEFIELD_FILTERED_DIRNAME,
filtered_filename
])
# Removing spaces so this path is memcached key friendly
path_to_return = path_to_return.replace(' ', '')
return path_to_return
|
def get_filtered_path(path_to_image, filename_key, storage):
"""
Return the 'filtered path'
"""
containing_folder, filename = os.path.split(path_to_image)
filtered_filename = get_filtered_filename(filename, filename_key)
path_to_return = os.path.join(*[
containing_folder,
VERSATILEIMAGEFIELD_FILTERED_DIRNAME,
filtered_filename
])
# Removing spaces so this path is memcached key friendly
path_to_return = path_to_return.replace(' ', '')
return path_to_return
|
[
"Return",
"the",
"filtered",
"path"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L149-L163
|
[
"def",
"get_filtered_path",
"(",
"path_to_image",
",",
"filename_key",
",",
"storage",
")",
":",
"containing_folder",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path_to_image",
")",
"filtered_filename",
"=",
"get_filtered_filename",
"(",
"filename",
",",
"filename_key",
")",
"path_to_return",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"[",
"containing_folder",
",",
"VERSATILEIMAGEFIELD_FILTERED_DIRNAME",
",",
"filtered_filename",
"]",
")",
"# Removing spaces so this path is memcached key friendly",
"path_to_return",
"=",
"path_to_return",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"path_to_return"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
validate_versatileimagefield_sizekey_list
|
Validate a list of size keys.
`sizes`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('medium', 'crop__400x400'),
('small', 'thumbnail__100x100')
]
|
versatileimagefield/utils.py
|
def validate_versatileimagefield_sizekey_list(sizes):
"""
Validate a list of size keys.
`sizes`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('medium', 'crop__400x400'),
('small', 'thumbnail__100x100')
]
"""
try:
for key, size_key in sizes:
size_key_split = size_key.split('__')
if size_key_split[-1] != 'url' and (
'x' not in size_key_split[-1]
):
raise InvalidSizeKey(
"{0} is an invalid size. All sizes must be either "
"'url' or made up of at least two segments separated "
"by double underscores. Examples: 'crop__400x400', "
"filters__invert__url".format(size_key)
)
except ValueError:
raise InvalidSizeKeySet(
'{} is an invalid size key set. Size key sets must be an '
'iterable of 2-tuples'.format(str(sizes))
)
return list(set(sizes))
|
def validate_versatileimagefield_sizekey_list(sizes):
"""
Validate a list of size keys.
`sizes`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('medium', 'crop__400x400'),
('small', 'thumbnail__100x100')
]
"""
try:
for key, size_key in sizes:
size_key_split = size_key.split('__')
if size_key_split[-1] != 'url' and (
'x' not in size_key_split[-1]
):
raise InvalidSizeKey(
"{0} is an invalid size. All sizes must be either "
"'url' or made up of at least two segments separated "
"by double underscores. Examples: 'crop__400x400', "
"filters__invert__url".format(size_key)
)
except ValueError:
raise InvalidSizeKeySet(
'{} is an invalid size key set. Size key sets must be an '
'iterable of 2-tuples'.format(str(sizes))
)
return list(set(sizes))
|
[
"Validate",
"a",
"list",
"of",
"size",
"keys",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L176-L204
|
[
"def",
"validate_versatileimagefield_sizekey_list",
"(",
"sizes",
")",
":",
"try",
":",
"for",
"key",
",",
"size_key",
"in",
"sizes",
":",
"size_key_split",
"=",
"size_key",
".",
"split",
"(",
"'__'",
")",
"if",
"size_key_split",
"[",
"-",
"1",
"]",
"!=",
"'url'",
"and",
"(",
"'x'",
"not",
"in",
"size_key_split",
"[",
"-",
"1",
"]",
")",
":",
"raise",
"InvalidSizeKey",
"(",
"\"{0} is an invalid size. All sizes must be either \"",
"\"'url' or made up of at least two segments separated \"",
"\"by double underscores. Examples: 'crop__400x400', \"",
"\"filters__invert__url\"",
".",
"format",
"(",
"size_key",
")",
")",
"except",
"ValueError",
":",
"raise",
"InvalidSizeKeySet",
"(",
"'{} is an invalid size key set. Size key sets must be an '",
"'iterable of 2-tuples'",
".",
"format",
"(",
"str",
"(",
"sizes",
")",
")",
")",
"return",
"list",
"(",
"set",
"(",
"sizes",
")",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
get_url_from_image_key
|
Build a URL from `image_key`.
|
versatileimagefield/utils.py
|
def get_url_from_image_key(image_instance, image_key):
"""Build a URL from `image_key`."""
img_key_split = image_key.split('__')
if 'x' in img_key_split[-1]:
size_key = img_key_split.pop(-1)
else:
size_key = None
img_url = reduce(getattr, img_key_split, image_instance)
if size_key:
img_url = img_url[size_key].url
return img_url
|
def get_url_from_image_key(image_instance, image_key):
"""Build a URL from `image_key`."""
img_key_split = image_key.split('__')
if 'x' in img_key_split[-1]:
size_key = img_key_split.pop(-1)
else:
size_key = None
img_url = reduce(getattr, img_key_split, image_instance)
if size_key:
img_url = img_url[size_key].url
return img_url
|
[
"Build",
"a",
"URL",
"from",
"image_key",
"."
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L207-L217
|
[
"def",
"get_url_from_image_key",
"(",
"image_instance",
",",
"image_key",
")",
":",
"img_key_split",
"=",
"image_key",
".",
"split",
"(",
"'__'",
")",
"if",
"'x'",
"in",
"img_key_split",
"[",
"-",
"1",
"]",
":",
"size_key",
"=",
"img_key_split",
".",
"pop",
"(",
"-",
"1",
")",
"else",
":",
"size_key",
"=",
"None",
"img_url",
"=",
"reduce",
"(",
"getattr",
",",
"img_key_split",
",",
"image_instance",
")",
"if",
"size_key",
":",
"img_url",
"=",
"img_url",
"[",
"size_key",
"]",
".",
"url",
"return",
"img_url"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
build_versatileimagefield_url_set
|
Return a dictionary of urls corresponding to size_set
- `image_instance`: A VersatileImageFieldFile
- `size_set`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('medium', 'crop__400x400'),
('small', 'thumbnail__100x100')
]
The above would lead to the following response:
{
'large': 'http://some.url/image.jpg',
'medium': 'http://some.url/__sized__/image-crop-400x400.jpg',
'small': 'http://some.url/__sized__/image-thumbnail-100x100.jpg',
}
- `request`:
|
versatileimagefield/utils.py
|
def build_versatileimagefield_url_set(image_instance, size_set, request=None):
"""
Return a dictionary of urls corresponding to size_set
- `image_instance`: A VersatileImageFieldFile
- `size_set`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('medium', 'crop__400x400'),
('small', 'thumbnail__100x100')
]
The above would lead to the following response:
{
'large': 'http://some.url/image.jpg',
'medium': 'http://some.url/__sized__/image-crop-400x400.jpg',
'small': 'http://some.url/__sized__/image-thumbnail-100x100.jpg',
}
- `request`:
"""
size_set = validate_versatileimagefield_sizekey_list(size_set)
to_return = {}
if image_instance or image_instance.field.placeholder_image:
for key, image_key in size_set:
img_url = get_url_from_image_key(image_instance, image_key)
if request is not None:
img_url = request.build_absolute_uri(img_url)
to_return[key] = img_url
return to_return
|
def build_versatileimagefield_url_set(image_instance, size_set, request=None):
"""
Return a dictionary of urls corresponding to size_set
- `image_instance`: A VersatileImageFieldFile
- `size_set`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('medium', 'crop__400x400'),
('small', 'thumbnail__100x100')
]
The above would lead to the following response:
{
'large': 'http://some.url/image.jpg',
'medium': 'http://some.url/__sized__/image-crop-400x400.jpg',
'small': 'http://some.url/__sized__/image-thumbnail-100x100.jpg',
}
- `request`:
"""
size_set = validate_versatileimagefield_sizekey_list(size_set)
to_return = {}
if image_instance or image_instance.field.placeholder_image:
for key, image_key in size_set:
img_url = get_url_from_image_key(image_instance, image_key)
if request is not None:
img_url = request.build_absolute_uri(img_url)
to_return[key] = img_url
return to_return
|
[
"Return",
"a",
"dictionary",
"of",
"urls",
"corresponding",
"to",
"size_set",
"-",
"image_instance",
":",
"A",
"VersatileImageFieldFile",
"-",
"size_set",
":",
"An",
"iterable",
"of",
"2",
"-",
"tuples",
"both",
"strings",
".",
"Example",
":",
"[",
"(",
"large",
"url",
")",
"(",
"medium",
"crop__400x400",
")",
"(",
"small",
"thumbnail__100x100",
")",
"]"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L220-L247
|
[
"def",
"build_versatileimagefield_url_set",
"(",
"image_instance",
",",
"size_set",
",",
"request",
"=",
"None",
")",
":",
"size_set",
"=",
"validate_versatileimagefield_sizekey_list",
"(",
"size_set",
")",
"to_return",
"=",
"{",
"}",
"if",
"image_instance",
"or",
"image_instance",
".",
"field",
".",
"placeholder_image",
":",
"for",
"key",
",",
"image_key",
"in",
"size_set",
":",
"img_url",
"=",
"get_url_from_image_key",
"(",
"image_instance",
",",
"image_key",
")",
"if",
"request",
"is",
"not",
"None",
":",
"img_url",
"=",
"request",
".",
"build_absolute_uri",
"(",
"img_url",
")",
"to_return",
"[",
"key",
"]",
"=",
"img_url",
"return",
"to_return"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
get_rendition_key_set
|
Retrieve a validated and prepped Rendition Key Set from
settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS
|
versatileimagefield/utils.py
|
def get_rendition_key_set(key):
"""
Retrieve a validated and prepped Rendition Key Set from
settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS
"""
try:
rendition_key_set = IMAGE_SETS[key]
except KeyError:
raise ImproperlyConfigured(
"No Rendition Key Set exists at "
"settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS['{}']".format(key)
)
else:
return validate_versatileimagefield_sizekey_list(rendition_key_set)
|
def get_rendition_key_set(key):
"""
Retrieve a validated and prepped Rendition Key Set from
settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS
"""
try:
rendition_key_set = IMAGE_SETS[key]
except KeyError:
raise ImproperlyConfigured(
"No Rendition Key Set exists at "
"settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS['{}']".format(key)
)
else:
return validate_versatileimagefield_sizekey_list(rendition_key_set)
|
[
"Retrieve",
"a",
"validated",
"and",
"prepped",
"Rendition",
"Key",
"Set",
"from",
"settings",
".",
"VERSATILEIMAGEFIELD_RENDITION_KEY_SETS"
] |
respondcreate/django-versatileimagefield
|
python
|
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L250-L263
|
[
"def",
"get_rendition_key_set",
"(",
"key",
")",
":",
"try",
":",
"rendition_key_set",
"=",
"IMAGE_SETS",
"[",
"key",
"]",
"except",
"KeyError",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"No Rendition Key Set exists at \"",
"\"settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS['{}']\"",
".",
"format",
"(",
"key",
")",
")",
"else",
":",
"return",
"validate_versatileimagefield_sizekey_list",
"(",
"rendition_key_set",
")"
] |
d41e279c39cccffafbe876c67596184704ae8877
|
test
|
format_instruction
|
Takes a raw `Instruction` and translates it into a human readable text
representation. As of writing, the text representation for WASM is not yet
standardized, so we just emit some generic format.
|
wasm/formatter.py
|
def format_instruction(insn):
"""
Takes a raw `Instruction` and translates it into a human readable text
representation. As of writing, the text representation for WASM is not yet
standardized, so we just emit some generic format.
"""
text = insn.op.mnemonic
if not insn.imm:
return text
return text + ' ' + ', '.join([
getattr(insn.op.imm_struct, x.name).to_string(
getattr(insn.imm, x.name)
)
for x in insn.op.imm_struct._meta.fields
])
|
def format_instruction(insn):
"""
Takes a raw `Instruction` and translates it into a human readable text
representation. As of writing, the text representation for WASM is not yet
standardized, so we just emit some generic format.
"""
text = insn.op.mnemonic
if not insn.imm:
return text
return text + ' ' + ', '.join([
getattr(insn.op.imm_struct, x.name).to_string(
getattr(insn.imm, x.name)
)
for x in insn.op.imm_struct._meta.fields
])
|
[
"Takes",
"a",
"raw",
"Instruction",
"and",
"translates",
"it",
"into",
"a",
"human",
"readable",
"text",
"representation",
".",
"As",
"of",
"writing",
"the",
"text",
"representation",
"for",
"WASM",
"is",
"not",
"yet",
"standardized",
"so",
"we",
"just",
"emit",
"some",
"generic",
"format",
"."
] |
athre0z/wasm
|
python
|
https://github.com/athre0z/wasm/blob/bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755/wasm/formatter.py#L11-L27
|
[
"def",
"format_instruction",
"(",
"insn",
")",
":",
"text",
"=",
"insn",
".",
"op",
".",
"mnemonic",
"if",
"not",
"insn",
".",
"imm",
":",
"return",
"text",
"return",
"text",
"+",
"' '",
"+",
"', '",
".",
"join",
"(",
"[",
"getattr",
"(",
"insn",
".",
"op",
".",
"imm_struct",
",",
"x",
".",
"name",
")",
".",
"to_string",
"(",
"getattr",
"(",
"insn",
".",
"imm",
",",
"x",
".",
"name",
")",
")",
"for",
"x",
"in",
"insn",
".",
"op",
".",
"imm_struct",
".",
"_meta",
".",
"fields",
"]",
")"
] |
bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755
|
test
|
format_function
|
Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string
representation of the function line by line. The function type is required
for formatting function parameter and return value information.
|
wasm/formatter.py
|
def format_function(
func_body,
func_type=None,
indent=2,
format_locals=True,
):
"""
Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string
representation of the function line by line. The function type is required
for formatting function parameter and return value information.
"""
if func_type is None:
yield 'func'
else:
param_section = ' (param {})'.format(' '.join(
map(format_lang_type, func_type.param_types)
)) if func_type.param_types else ''
result_section = ' (result {})'.format(
format_lang_type(func_type.return_type)
) if func_type.return_type else ''
yield 'func' + param_section + result_section
if format_locals and func_body.locals:
yield '(locals {})'.format(' '.join(itertools.chain.from_iterable(
itertools.repeat(format_lang_type(x.type), x.count)
for x in func_body.locals
)))
level = 1
for cur_insn in decode_bytecode(func_body.code):
if cur_insn.op.flags & INSN_LEAVE_BLOCK:
level -= 1
yield ' ' * (level * indent) + format_instruction(cur_insn)
if cur_insn.op.flags & INSN_ENTER_BLOCK:
level += 1
|
def format_function(
func_body,
func_type=None,
indent=2,
format_locals=True,
):
"""
Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string
representation of the function line by line. The function type is required
for formatting function parameter and return value information.
"""
if func_type is None:
yield 'func'
else:
param_section = ' (param {})'.format(' '.join(
map(format_lang_type, func_type.param_types)
)) if func_type.param_types else ''
result_section = ' (result {})'.format(
format_lang_type(func_type.return_type)
) if func_type.return_type else ''
yield 'func' + param_section + result_section
if format_locals and func_body.locals:
yield '(locals {})'.format(' '.join(itertools.chain.from_iterable(
itertools.repeat(format_lang_type(x.type), x.count)
for x in func_body.locals
)))
level = 1
for cur_insn in decode_bytecode(func_body.code):
if cur_insn.op.flags & INSN_LEAVE_BLOCK:
level -= 1
yield ' ' * (level * indent) + format_instruction(cur_insn)
if cur_insn.op.flags & INSN_ENTER_BLOCK:
level += 1
|
[
"Takes",
"a",
"FunctionBody",
"and",
"optionally",
"a",
"FunctionType",
"yielding",
"the",
"string",
"representation",
"of",
"the",
"function",
"line",
"by",
"line",
".",
"The",
"function",
"type",
"is",
"required",
"for",
"formatting",
"function",
"parameter",
"and",
"return",
"value",
"information",
"."
] |
athre0z/wasm
|
python
|
https://github.com/athre0z/wasm/blob/bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755/wasm/formatter.py#L46-L80
|
[
"def",
"format_function",
"(",
"func_body",
",",
"func_type",
"=",
"None",
",",
"indent",
"=",
"2",
",",
"format_locals",
"=",
"True",
",",
")",
":",
"if",
"func_type",
"is",
"None",
":",
"yield",
"'func'",
"else",
":",
"param_section",
"=",
"' (param {})'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"map",
"(",
"format_lang_type",
",",
"func_type",
".",
"param_types",
")",
")",
")",
"if",
"func_type",
".",
"param_types",
"else",
"''",
"result_section",
"=",
"' (result {})'",
".",
"format",
"(",
"format_lang_type",
"(",
"func_type",
".",
"return_type",
")",
")",
"if",
"func_type",
".",
"return_type",
"else",
"''",
"yield",
"'func'",
"+",
"param_section",
"+",
"result_section",
"if",
"format_locals",
"and",
"func_body",
".",
"locals",
":",
"yield",
"'(locals {})'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"itertools",
".",
"repeat",
"(",
"format_lang_type",
"(",
"x",
".",
"type",
")",
",",
"x",
".",
"count",
")",
"for",
"x",
"in",
"func_body",
".",
"locals",
")",
")",
")",
"level",
"=",
"1",
"for",
"cur_insn",
"in",
"decode_bytecode",
"(",
"func_body",
".",
"code",
")",
":",
"if",
"cur_insn",
".",
"op",
".",
"flags",
"&",
"INSN_LEAVE_BLOCK",
":",
"level",
"-=",
"1",
"yield",
"' '",
"*",
"(",
"level",
"*",
"indent",
")",
"+",
"format_instruction",
"(",
"cur_insn",
")",
"if",
"cur_insn",
".",
"op",
".",
"flags",
"&",
"INSN_ENTER_BLOCK",
":",
"level",
"+=",
"1"
] |
bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755
|
test
|
decode_bytecode
|
Decodes raw bytecode, yielding `Instruction`s.
|
wasm/decode.py
|
def decode_bytecode(bytecode):
"""Decodes raw bytecode, yielding `Instruction`s."""
bytecode_wnd = memoryview(bytecode)
while bytecode_wnd:
opcode_id = byte2int(bytecode_wnd[0])
opcode = OPCODE_MAP[opcode_id]
if opcode.imm_struct is not None:
offs, imm, _ = opcode.imm_struct.from_raw(None, bytecode_wnd[1:])
else:
imm = None
offs = 0
insn_len = 1 + offs
yield Instruction(opcode, imm, insn_len)
bytecode_wnd = bytecode_wnd[insn_len:]
|
def decode_bytecode(bytecode):
"""Decodes raw bytecode, yielding `Instruction`s."""
bytecode_wnd = memoryview(bytecode)
while bytecode_wnd:
opcode_id = byte2int(bytecode_wnd[0])
opcode = OPCODE_MAP[opcode_id]
if opcode.imm_struct is not None:
offs, imm, _ = opcode.imm_struct.from_raw(None, bytecode_wnd[1:])
else:
imm = None
offs = 0
insn_len = 1 + offs
yield Instruction(opcode, imm, insn_len)
bytecode_wnd = bytecode_wnd[insn_len:]
|
[
"Decodes",
"raw",
"bytecode",
"yielding",
"Instruction",
"s",
"."
] |
athre0z/wasm
|
python
|
https://github.com/athre0z/wasm/blob/bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755/wasm/decode.py#L14-L29
|
[
"def",
"decode_bytecode",
"(",
"bytecode",
")",
":",
"bytecode_wnd",
"=",
"memoryview",
"(",
"bytecode",
")",
"while",
"bytecode_wnd",
":",
"opcode_id",
"=",
"byte2int",
"(",
"bytecode_wnd",
"[",
"0",
"]",
")",
"opcode",
"=",
"OPCODE_MAP",
"[",
"opcode_id",
"]",
"if",
"opcode",
".",
"imm_struct",
"is",
"not",
"None",
":",
"offs",
",",
"imm",
",",
"_",
"=",
"opcode",
".",
"imm_struct",
".",
"from_raw",
"(",
"None",
",",
"bytecode_wnd",
"[",
"1",
":",
"]",
")",
"else",
":",
"imm",
"=",
"None",
"offs",
"=",
"0",
"insn_len",
"=",
"1",
"+",
"offs",
"yield",
"Instruction",
"(",
"opcode",
",",
"imm",
",",
"insn_len",
")",
"bytecode_wnd",
"=",
"bytecode_wnd",
"[",
"insn_len",
":",
"]"
] |
bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755
|
test
|
decode_module
|
Decodes raw WASM modules, yielding `ModuleFragment`s.
|
wasm/decode.py
|
def decode_module(module, decode_name_subsections=False):
"""Decodes raw WASM modules, yielding `ModuleFragment`s."""
module_wnd = memoryview(module)
# Read & yield module header.
hdr = ModuleHeader()
hdr_len, hdr_data, _ = hdr.from_raw(None, module_wnd)
yield ModuleFragment(hdr, hdr_data)
module_wnd = module_wnd[hdr_len:]
# Read & yield sections.
while module_wnd:
sec = Section()
sec_len, sec_data, _ = sec.from_raw(None, module_wnd)
# If requested, decode name subsections when encountered.
if (
decode_name_subsections and
sec_data.id == SEC_UNK and
sec_data.name == SEC_NAME
):
sec_wnd = sec_data.payload
while sec_wnd:
subsec = NameSubSection()
subsec_len, subsec_data, _ = subsec.from_raw(None, sec_wnd)
yield ModuleFragment(subsec, subsec_data)
sec_wnd = sec_wnd[subsec_len:]
else:
yield ModuleFragment(sec, sec_data)
module_wnd = module_wnd[sec_len:]
|
def decode_module(module, decode_name_subsections=False):
"""Decodes raw WASM modules, yielding `ModuleFragment`s."""
module_wnd = memoryview(module)
# Read & yield module header.
hdr = ModuleHeader()
hdr_len, hdr_data, _ = hdr.from_raw(None, module_wnd)
yield ModuleFragment(hdr, hdr_data)
module_wnd = module_wnd[hdr_len:]
# Read & yield sections.
while module_wnd:
sec = Section()
sec_len, sec_data, _ = sec.from_raw(None, module_wnd)
# If requested, decode name subsections when encountered.
if (
decode_name_subsections and
sec_data.id == SEC_UNK and
sec_data.name == SEC_NAME
):
sec_wnd = sec_data.payload
while sec_wnd:
subsec = NameSubSection()
subsec_len, subsec_data, _ = subsec.from_raw(None, sec_wnd)
yield ModuleFragment(subsec, subsec_data)
sec_wnd = sec_wnd[subsec_len:]
else:
yield ModuleFragment(sec, sec_data)
module_wnd = module_wnd[sec_len:]
|
[
"Decodes",
"raw",
"WASM",
"modules",
"yielding",
"ModuleFragment",
"s",
"."
] |
athre0z/wasm
|
python
|
https://github.com/athre0z/wasm/blob/bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755/wasm/decode.py#L32-L62
|
[
"def",
"decode_module",
"(",
"module",
",",
"decode_name_subsections",
"=",
"False",
")",
":",
"module_wnd",
"=",
"memoryview",
"(",
"module",
")",
"# Read & yield module header.",
"hdr",
"=",
"ModuleHeader",
"(",
")",
"hdr_len",
",",
"hdr_data",
",",
"_",
"=",
"hdr",
".",
"from_raw",
"(",
"None",
",",
"module_wnd",
")",
"yield",
"ModuleFragment",
"(",
"hdr",
",",
"hdr_data",
")",
"module_wnd",
"=",
"module_wnd",
"[",
"hdr_len",
":",
"]",
"# Read & yield sections.",
"while",
"module_wnd",
":",
"sec",
"=",
"Section",
"(",
")",
"sec_len",
",",
"sec_data",
",",
"_",
"=",
"sec",
".",
"from_raw",
"(",
"None",
",",
"module_wnd",
")",
"# If requested, decode name subsections when encountered.",
"if",
"(",
"decode_name_subsections",
"and",
"sec_data",
".",
"id",
"==",
"SEC_UNK",
"and",
"sec_data",
".",
"name",
"==",
"SEC_NAME",
")",
":",
"sec_wnd",
"=",
"sec_data",
".",
"payload",
"while",
"sec_wnd",
":",
"subsec",
"=",
"NameSubSection",
"(",
")",
"subsec_len",
",",
"subsec_data",
",",
"_",
"=",
"subsec",
".",
"from_raw",
"(",
"None",
",",
"sec_wnd",
")",
"yield",
"ModuleFragment",
"(",
"subsec",
",",
"subsec_data",
")",
"sec_wnd",
"=",
"sec_wnd",
"[",
"subsec_len",
":",
"]",
"else",
":",
"yield",
"ModuleFragment",
"(",
"sec",
",",
"sec_data",
")",
"module_wnd",
"=",
"module_wnd",
"[",
"sec_len",
":",
"]"
] |
bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755
|
test
|
deprecated_func
|
Deprecates a function, printing a warning on the first usage.
|
wasm/compat.py
|
def deprecated_func(func):
"""Deprecates a function, printing a warning on the first usage."""
# We use a mutable container here to work around Py2's lack of
# the `nonlocal` keyword.
first_usage = [True]
@functools.wraps(func)
def wrapper(*args, **kwargs):
if first_usage[0]:
warnings.warn(
"Call to deprecated function {}.".format(func.__name__),
DeprecationWarning,
)
first_usage[0] = False
return func(*args, **kwargs)
return wrapper
|
def deprecated_func(func):
"""Deprecates a function, printing a warning on the first usage."""
# We use a mutable container here to work around Py2's lack of
# the `nonlocal` keyword.
first_usage = [True]
@functools.wraps(func)
def wrapper(*args, **kwargs):
if first_usage[0]:
warnings.warn(
"Call to deprecated function {}.".format(func.__name__),
DeprecationWarning,
)
first_usage[0] = False
return func(*args, **kwargs)
return wrapper
|
[
"Deprecates",
"a",
"function",
"printing",
"a",
"warning",
"on",
"the",
"first",
"usage",
"."
] |
athre0z/wasm
|
python
|
https://github.com/athre0z/wasm/blob/bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755/wasm/compat.py#L50-L67
|
[
"def",
"deprecated_func",
"(",
"func",
")",
":",
"# We use a mutable container here to work around Py2's lack of",
"# the `nonlocal` keyword.",
"first_usage",
"=",
"[",
"True",
"]",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"first_usage",
"[",
"0",
"]",
":",
"warnings",
".",
"warn",
"(",
"\"Call to deprecated function {}.\"",
".",
"format",
"(",
"func",
".",
"__name__",
")",
",",
"DeprecationWarning",
",",
")",
"first_usage",
"[",
"0",
"]",
"=",
"False",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755
|
test
|
Manager.send_action
|
Send an :class:`~panoramisk.actions.Action` to the server:
:param action: an Action or dict with action name and parameters to
send
:type action: Action or dict or Command
:param as_list: If True, the action Future will retrieve all responses
:type as_list: boolean
:return: a Future that will receive the response
:rtype: asyncio.Future
:Example:
To retrieve answer in a coroutine::
manager = Manager()
resp = yield from manager.send_action({'Action': 'Status'})
With a callback::
manager = Manager()
future = manager.send_action({'Action': 'Status'})
future.add_done_callback(handle_status_response)
See https://wiki.asterisk.org/wiki/display/AST/AMI+Actions for
more information on actions
|
panoramisk/manager.py
|
def send_action(self, action, as_list=None, **kwargs):
"""Send an :class:`~panoramisk.actions.Action` to the server:
:param action: an Action or dict with action name and parameters to
send
:type action: Action or dict or Command
:param as_list: If True, the action Future will retrieve all responses
:type as_list: boolean
:return: a Future that will receive the response
:rtype: asyncio.Future
:Example:
To retrieve answer in a coroutine::
manager = Manager()
resp = yield from manager.send_action({'Action': 'Status'})
With a callback::
manager = Manager()
future = manager.send_action({'Action': 'Status'})
future.add_done_callback(handle_status_response)
See https://wiki.asterisk.org/wiki/display/AST/AMI+Actions for
more information on actions
"""
action.update(kwargs)
return self.protocol.send(action, as_list=as_list)
|
def send_action(self, action, as_list=None, **kwargs):
"""Send an :class:`~panoramisk.actions.Action` to the server:
:param action: an Action or dict with action name and parameters to
send
:type action: Action or dict or Command
:param as_list: If True, the action Future will retrieve all responses
:type as_list: boolean
:return: a Future that will receive the response
:rtype: asyncio.Future
:Example:
To retrieve answer in a coroutine::
manager = Manager()
resp = yield from manager.send_action({'Action': 'Status'})
With a callback::
manager = Manager()
future = manager.send_action({'Action': 'Status'})
future.add_done_callback(handle_status_response)
See https://wiki.asterisk.org/wiki/display/AST/AMI+Actions for
more information on actions
"""
action.update(kwargs)
return self.protocol.send(action, as_list=as_list)
|
[
"Send",
"an",
":",
"class",
":",
"~panoramisk",
".",
"actions",
".",
"Action",
"to",
"the",
"server",
":"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/manager.py#L110-L138
|
[
"def",
"send_action",
"(",
"self",
",",
"action",
",",
"as_list",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"action",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"protocol",
".",
"send",
"(",
"action",
",",
"as_list",
"=",
"as_list",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Manager.send_command
|
Send a :class:`~panoramisk.actions.Command` to the server::
manager = Manager()
resp = manager.send_command('http show status')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/display/AST/ManagerAction_Command
|
panoramisk/manager.py
|
def send_command(self, command, as_list=False):
"""Send a :class:`~panoramisk.actions.Command` to the server::
manager = Manager()
resp = manager.send_command('http show status')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/display/AST/ManagerAction_Command
"""
action = actions.Action({'Command': command, 'Action': 'Command'},
as_list=as_list)
return self.send_action(action)
|
def send_command(self, command, as_list=False):
"""Send a :class:`~panoramisk.actions.Command` to the server::
manager = Manager()
resp = manager.send_command('http show status')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/display/AST/ManagerAction_Command
"""
action = actions.Action({'Command': command, 'Action': 'Command'},
as_list=as_list)
return self.send_action(action)
|
[
"Send",
"a",
":",
"class",
":",
"~panoramisk",
".",
"actions",
".",
"Command",
"to",
"the",
"server",
"::"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/manager.py#L140-L151
|
[
"def",
"send_command",
"(",
"self",
",",
"command",
",",
"as_list",
"=",
"False",
")",
":",
"action",
"=",
"actions",
".",
"Action",
"(",
"{",
"'Command'",
":",
"command",
",",
"'Action'",
":",
"'Command'",
"}",
",",
"as_list",
"=",
"as_list",
")",
"return",
"self",
".",
"send_action",
"(",
"action",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Manager.send_agi_command
|
Send a :class:`~panoramisk.actions.Command` to the server:
:param channel: Channel name where to launch command.
Ex: 'SIP/000000-00000a53'
:type channel: String
:param command: command to launch. Ex: 'GET VARIABLE async_agi_server'
:type command: String
:param as_list: If True, the action Future will retrieve all responses
:type as_list: boolean
:return: a Future that will receive the response
:rtype: asyncio.Future
:Example:
::
manager = Manager()
resp = manager.send_agi_command('SIP/000000-00000a53',
'GET VARIABLE async_agi_server')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+ManagerAction_AGI
|
panoramisk/manager.py
|
def send_agi_command(self, channel, command, as_list=False):
"""Send a :class:`~panoramisk.actions.Command` to the server:
:param channel: Channel name where to launch command.
Ex: 'SIP/000000-00000a53'
:type channel: String
:param command: command to launch. Ex: 'GET VARIABLE async_agi_server'
:type command: String
:param as_list: If True, the action Future will retrieve all responses
:type as_list: boolean
:return: a Future that will receive the response
:rtype: asyncio.Future
:Example:
::
manager = Manager()
resp = manager.send_agi_command('SIP/000000-00000a53',
'GET VARIABLE async_agi_server')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+ManagerAction_AGI
"""
action = actions.Command({'Action': 'AGI',
'Channel': channel,
'Command': command},
as_list=as_list)
return self.send_action(action)
|
def send_agi_command(self, channel, command, as_list=False):
"""Send a :class:`~panoramisk.actions.Command` to the server:
:param channel: Channel name where to launch command.
Ex: 'SIP/000000-00000a53'
:type channel: String
:param command: command to launch. Ex: 'GET VARIABLE async_agi_server'
:type command: String
:param as_list: If True, the action Future will retrieve all responses
:type as_list: boolean
:return: a Future that will receive the response
:rtype: asyncio.Future
:Example:
::
manager = Manager()
resp = manager.send_agi_command('SIP/000000-00000a53',
'GET VARIABLE async_agi_server')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+ManagerAction_AGI
"""
action = actions.Command({'Action': 'AGI',
'Channel': channel,
'Command': command},
as_list=as_list)
return self.send_action(action)
|
[
"Send",
"a",
":",
"class",
":",
"~panoramisk",
".",
"actions",
".",
"Command",
"to",
"the",
"server",
":"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/manager.py#L153-L182
|
[
"def",
"send_agi_command",
"(",
"self",
",",
"channel",
",",
"command",
",",
"as_list",
"=",
"False",
")",
":",
"action",
"=",
"actions",
".",
"Command",
"(",
"{",
"'Action'",
":",
"'AGI'",
",",
"'Channel'",
":",
"channel",
",",
"'Command'",
":",
"command",
"}",
",",
"as_list",
"=",
"as_list",
")",
"return",
"self",
".",
"send_action",
"(",
"action",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Manager.connect
|
connect to the server
|
panoramisk/manager.py
|
def connect(self):
"""connect to the server"""
if self.loop is None: # pragma: no cover
self.loop = asyncio.get_event_loop()
t = asyncio.Task(
self.loop.create_connection(
self.config['protocol_factory'],
self.config['host'], self.config['port'],
ssl=self.config['ssl']),
loop=self.loop)
t.add_done_callback(self.connection_made)
return t
|
def connect(self):
"""connect to the server"""
if self.loop is None: # pragma: no cover
self.loop = asyncio.get_event_loop()
t = asyncio.Task(
self.loop.create_connection(
self.config['protocol_factory'],
self.config['host'], self.config['port'],
ssl=self.config['ssl']),
loop=self.loop)
t.add_done_callback(self.connection_made)
return t
|
[
"connect",
"to",
"the",
"server"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/manager.py#L184-L195
|
[
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"loop",
"is",
"None",
":",
"# pragma: no cover",
"self",
".",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"t",
"=",
"asyncio",
".",
"Task",
"(",
"self",
".",
"loop",
".",
"create_connection",
"(",
"self",
".",
"config",
"[",
"'protocol_factory'",
"]",
",",
"self",
".",
"config",
"[",
"'host'",
"]",
",",
"self",
".",
"config",
"[",
"'port'",
"]",
",",
"ssl",
"=",
"self",
".",
"config",
"[",
"'ssl'",
"]",
")",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"t",
".",
"add_done_callback",
"(",
"self",
".",
"connection_made",
")",
"return",
"t"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Manager.register_event
|
register an event. See :class:`~panoramisk.message.Message`:
.. code-block:: python
>>> def callback(manager, event):
... print(manager, event)
>>> manager = Manager()
>>> manager.register_event('Meetme*', callback)
<function callback at 0x...>
You can also use the manager as a decorator:
.. code-block:: python
>>> manager = Manager()
>>> @manager.register_event('Meetme*')
... def callback(manager, event):
... print(manager, event)
|
panoramisk/manager.py
|
def register_event(self, pattern, callback=None):
"""register an event. See :class:`~panoramisk.message.Message`:
.. code-block:: python
>>> def callback(manager, event):
... print(manager, event)
>>> manager = Manager()
>>> manager.register_event('Meetme*', callback)
<function callback at 0x...>
You can also use the manager as a decorator:
.. code-block:: python
>>> manager = Manager()
>>> @manager.register_event('Meetme*')
... def callback(manager, event):
... print(manager, event)
"""
def _register_event(callback):
if not self.callbacks[pattern]:
self.patterns.append((pattern,
re.compile(fnmatch.translate(pattern))))
self.callbacks[pattern].append(callback)
return callback
if callback is not None:
return _register_event(callback)
else:
return _register_event
|
def register_event(self, pattern, callback=None):
"""register an event. See :class:`~panoramisk.message.Message`:
.. code-block:: python
>>> def callback(manager, event):
... print(manager, event)
>>> manager = Manager()
>>> manager.register_event('Meetme*', callback)
<function callback at 0x...>
You can also use the manager as a decorator:
.. code-block:: python
>>> manager = Manager()
>>> @manager.register_event('Meetme*')
... def callback(manager, event):
... print(manager, event)
"""
def _register_event(callback):
if not self.callbacks[pattern]:
self.patterns.append((pattern,
re.compile(fnmatch.translate(pattern))))
self.callbacks[pattern].append(callback)
return callback
if callback is not None:
return _register_event(callback)
else:
return _register_event
|
[
"register",
"an",
"event",
".",
"See",
":",
"class",
":",
"~panoramisk",
".",
"message",
".",
"Message",
":"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/manager.py#L197-L226
|
[
"def",
"register_event",
"(",
"self",
",",
"pattern",
",",
"callback",
"=",
"None",
")",
":",
"def",
"_register_event",
"(",
"callback",
")",
":",
"if",
"not",
"self",
".",
"callbacks",
"[",
"pattern",
"]",
":",
"self",
".",
"patterns",
".",
"append",
"(",
"(",
"pattern",
",",
"re",
".",
"compile",
"(",
"fnmatch",
".",
"translate",
"(",
"pattern",
")",
")",
")",
")",
"self",
".",
"callbacks",
"[",
"pattern",
"]",
".",
"append",
"(",
"callback",
")",
"return",
"callback",
"if",
"callback",
"is",
"not",
"None",
":",
"return",
"_register_event",
"(",
"callback",
")",
"else",
":",
"return",
"_register_event"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Manager.close
|
Close the connection
|
panoramisk/manager.py
|
def close(self):
"""Close the connection"""
if self.pinger:
self.pinger.cancel()
self.pinger = None
if getattr(self, 'protocol', None):
self.protocol.close()
|
def close(self):
"""Close the connection"""
if self.pinger:
self.pinger.cancel()
self.pinger = None
if getattr(self, 'protocol', None):
self.protocol.close()
|
[
"Close",
"the",
"connection"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/manager.py#L242-L248
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"pinger",
":",
"self",
".",
"pinger",
".",
"cancel",
"(",
")",
"self",
".",
"pinger",
"=",
"None",
"if",
"getattr",
"(",
"self",
",",
"'protocol'",
",",
"None",
")",
":",
"self",
".",
"protocol",
".",
"close",
"(",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Request.send_command
|
Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(request):
print(['AGI variables:', request.headers])
yield from request.send_command('ANSWER')
yield from request.send_command('EXEC StartMusicOnHold')
yield from request.send_command('EXEC Wait 10')
|
panoramisk/fast_agi.py
|
def send_command(self, command):
"""Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(request):
print(['AGI variables:', request.headers])
yield from request.send_command('ANSWER')
yield from request.send_command('EXEC StartMusicOnHold')
yield from request.send_command('EXEC Wait 10')
"""
command += '\n'
self.writer.write(command.encode(self.encoding))
yield from self.writer.drain()
agi_result = yield from self._read_result()
# If Asterisk returns `100 Trying...`, wait for next the response.
while agi_result.get('status_code') == 100:
agi_result = yield from self._read_result()
# when we got AGIUsageError the following line contains some indication
if 'error' in agi_result and agi_result['error'] == 'AGIUsageError':
buff_usage_error = yield from self.reader.readline()
agi_result['msg'] += buff_usage_error.decode(self.encoding)
return agi_result
|
def send_command(self, command):
"""Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(request):
print(['AGI variables:', request.headers])
yield from request.send_command('ANSWER')
yield from request.send_command('EXEC StartMusicOnHold')
yield from request.send_command('EXEC Wait 10')
"""
command += '\n'
self.writer.write(command.encode(self.encoding))
yield from self.writer.drain()
agi_result = yield from self._read_result()
# If Asterisk returns `100 Trying...`, wait for next the response.
while agi_result.get('status_code') == 100:
agi_result = yield from self._read_result()
# when we got AGIUsageError the following line contains some indication
if 'error' in agi_result and agi_result['error'] == 'AGIUsageError':
buff_usage_error = yield from self.reader.readline()
agi_result['msg'] += buff_usage_error.decode(self.encoding)
return agi_result
|
[
"Send",
"a",
"command",
"for",
"FastAGI",
"request",
":"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/fast_agi.py#L18-L50
|
[
"def",
"send_command",
"(",
"self",
",",
"command",
")",
":",
"command",
"+=",
"'\\n'",
"self",
".",
"writer",
".",
"write",
"(",
"command",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
")",
"yield",
"from",
"self",
".",
"writer",
".",
"drain",
"(",
")",
"agi_result",
"=",
"yield",
"from",
"self",
".",
"_read_result",
"(",
")",
"# If Asterisk returns `100 Trying...`, wait for next the response.",
"while",
"agi_result",
".",
"get",
"(",
"'status_code'",
")",
"==",
"100",
":",
"agi_result",
"=",
"yield",
"from",
"self",
".",
"_read_result",
"(",
")",
"# when we got AGIUsageError the following line contains some indication",
"if",
"'error'",
"in",
"agi_result",
"and",
"agi_result",
"[",
"'error'",
"]",
"==",
"'AGIUsageError'",
":",
"buff_usage_error",
"=",
"yield",
"from",
"self",
".",
"reader",
".",
"readline",
"(",
")",
"agi_result",
"[",
"'msg'",
"]",
"+=",
"buff_usage_error",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"return",
"agi_result"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Request._read_result
|
Parse read a response from the AGI and parse it.
:return dict: The AGI response parsed into a dict.
|
panoramisk/fast_agi.py
|
def _read_result(self):
"""Parse read a response from the AGI and parse it.
:return dict: The AGI response parsed into a dict.
"""
response = yield from self.reader.readline()
return parse_agi_result(response.decode(self.encoding)[:-1])
|
def _read_result(self):
"""Parse read a response from the AGI and parse it.
:return dict: The AGI response parsed into a dict.
"""
response = yield from self.reader.readline()
return parse_agi_result(response.decode(self.encoding)[:-1])
|
[
"Parse",
"read",
"a",
"response",
"from",
"the",
"AGI",
"and",
"parse",
"it",
"."
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/fast_agi.py#L53-L59
|
[
"def",
"_read_result",
"(",
"self",
")",
":",
"response",
"=",
"yield",
"from",
"self",
".",
"reader",
".",
"readline",
"(",
")",
"return",
"parse_agi_result",
"(",
"response",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"[",
":",
"-",
"1",
"]",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Application.add_route
|
Add a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:param endpoint: command to launch. Ex: start
:type endpoint: callable
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
|
panoramisk/fast_agi.py
|
def add_route(self, path, endpoint):
"""Add a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:param endpoint: command to launch. Ex: start
:type endpoint: callable
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
"""
assert callable(endpoint), endpoint
if path in self._route:
raise ValueError('A route already exists.')
if not asyncio.iscoroutinefunction(endpoint):
endpoint = asyncio.coroutine(endpoint)
self._route[path] = endpoint
|
def add_route(self, path, endpoint):
"""Add a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:param endpoint: command to launch. Ex: start
:type endpoint: callable
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
"""
assert callable(endpoint), endpoint
if path in self._route:
raise ValueError('A route already exists.')
if not asyncio.iscoroutinefunction(endpoint):
endpoint = asyncio.coroutine(endpoint)
self._route[path] = endpoint
|
[
"Add",
"a",
"route",
"for",
"FastAGI",
"requests",
":"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/fast_agi.py#L80-L106
|
[
"def",
"add_route",
"(",
"self",
",",
"path",
",",
"endpoint",
")",
":",
"assert",
"callable",
"(",
"endpoint",
")",
",",
"endpoint",
"if",
"path",
"in",
"self",
".",
"_route",
":",
"raise",
"ValueError",
"(",
"'A route already exists.'",
")",
"if",
"not",
"asyncio",
".",
"iscoroutinefunction",
"(",
"endpoint",
")",
":",
"endpoint",
"=",
"asyncio",
".",
"coroutine",
"(",
"endpoint",
")",
"self",
".",
"_route",
"[",
"path",
"]",
"=",
"endpoint"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Application.del_route
|
Delete a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
fa_app.del_route('calls/start')
|
panoramisk/fast_agi.py
|
def del_route(self, path):
"""Delete a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
fa_app.del_route('calls/start')
"""
if path not in self._route:
raise ValueError('This route doesn\'t exist.')
del(self._route[path])
|
def del_route(self, path):
"""Delete a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
fa_app.del_route('calls/start')
"""
if path not in self._route:
raise ValueError('This route doesn\'t exist.')
del(self._route[path])
|
[
"Delete",
"a",
"route",
"for",
"FastAGI",
"requests",
":"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/fast_agi.py#L108-L130
|
[
"def",
"del_route",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"_route",
":",
"raise",
"ValueError",
"(",
"'This route doesn\\'t exist.'",
")",
"del",
"(",
"self",
".",
"_route",
"[",
"path",
"]",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Application.handler
|
AsyncIO coroutine handler to launch socket listening.
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
coro = asyncio.start_server(fa_app.handler, '0.0.0.0', 4574)
server = loop.run_until_complete(coro)
See https://docs.python.org/3/library/asyncio-stream.html
|
panoramisk/fast_agi.py
|
def handler(self, reader, writer):
"""AsyncIO coroutine handler to launch socket listening.
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
coro = asyncio.start_server(fa_app.handler, '0.0.0.0', 4574)
server = loop.run_until_complete(coro)
See https://docs.python.org/3/library/asyncio-stream.html
"""
buffer = b''
while b'\n\n' not in buffer:
buffer += yield from reader.read(self.buf_size)
lines = buffer[:-2].decode(self.default_encoding).split('\n')
headers = OrderedDict([
line.split(': ', 1) for line in lines if ': ' in line
])
agi_network_script = headers.get('agi_network_script')
log.info('Received FastAGI request from %r for "%s" route',
writer.get_extra_info('peername'), agi_network_script)
log.debug("Asterisk Headers: %r", headers)
if agi_network_script is not None:
route = self._route.get(agi_network_script)
if route is not None:
request = Request(app=self,
headers=headers,
reader=reader, writer=writer,
encoding=self.default_encoding)
try:
yield from route(request)
except BaseException:
log.exception(
'An exception has been raised for the request "%s"',
agi_network_script
)
else:
log.error('No route for the request "%s"', agi_network_script)
else:
log.error('No agi_network_script header for the request')
log.debug("Closing client socket")
writer.close()
|
def handler(self, reader, writer):
"""AsyncIO coroutine handler to launch socket listening.
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa_app = Application()
fa_app.add_route('calls/start', start)
coro = asyncio.start_server(fa_app.handler, '0.0.0.0', 4574)
server = loop.run_until_complete(coro)
See https://docs.python.org/3/library/asyncio-stream.html
"""
buffer = b''
while b'\n\n' not in buffer:
buffer += yield from reader.read(self.buf_size)
lines = buffer[:-2].decode(self.default_encoding).split('\n')
headers = OrderedDict([
line.split(': ', 1) for line in lines if ': ' in line
])
agi_network_script = headers.get('agi_network_script')
log.info('Received FastAGI request from %r for "%s" route',
writer.get_extra_info('peername'), agi_network_script)
log.debug("Asterisk Headers: %r", headers)
if agi_network_script is not None:
route = self._route.get(agi_network_script)
if route is not None:
request = Request(app=self,
headers=headers,
reader=reader, writer=writer,
encoding=self.default_encoding)
try:
yield from route(request)
except BaseException:
log.exception(
'An exception has been raised for the request "%s"',
agi_network_script
)
else:
log.error('No route for the request "%s"', agi_network_script)
else:
log.error('No agi_network_script header for the request')
log.debug("Closing client socket")
writer.close()
|
[
"AsyncIO",
"coroutine",
"handler",
"to",
"launch",
"socket",
"listening",
"."
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/fast_agi.py#L133-L184
|
[
"def",
"handler",
"(",
"self",
",",
"reader",
",",
"writer",
")",
":",
"buffer",
"=",
"b''",
"while",
"b'\\n\\n'",
"not",
"in",
"buffer",
":",
"buffer",
"+=",
"yield",
"from",
"reader",
".",
"read",
"(",
"self",
".",
"buf_size",
")",
"lines",
"=",
"buffer",
"[",
":",
"-",
"2",
"]",
".",
"decode",
"(",
"self",
".",
"default_encoding",
")",
".",
"split",
"(",
"'\\n'",
")",
"headers",
"=",
"OrderedDict",
"(",
"[",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")",
"for",
"line",
"in",
"lines",
"if",
"': '",
"in",
"line",
"]",
")",
"agi_network_script",
"=",
"headers",
".",
"get",
"(",
"'agi_network_script'",
")",
"log",
".",
"info",
"(",
"'Received FastAGI request from %r for \"%s\" route'",
",",
"writer",
".",
"get_extra_info",
"(",
"'peername'",
")",
",",
"agi_network_script",
")",
"log",
".",
"debug",
"(",
"\"Asterisk Headers: %r\"",
",",
"headers",
")",
"if",
"agi_network_script",
"is",
"not",
"None",
":",
"route",
"=",
"self",
".",
"_route",
".",
"get",
"(",
"agi_network_script",
")",
"if",
"route",
"is",
"not",
"None",
":",
"request",
"=",
"Request",
"(",
"app",
"=",
"self",
",",
"headers",
"=",
"headers",
",",
"reader",
"=",
"reader",
",",
"writer",
"=",
"writer",
",",
"encoding",
"=",
"self",
".",
"default_encoding",
")",
"try",
":",
"yield",
"from",
"route",
"(",
"request",
")",
"except",
"BaseException",
":",
"log",
".",
"exception",
"(",
"'An exception has been raised for the request \"%s\"'",
",",
"agi_network_script",
")",
"else",
":",
"log",
".",
"error",
"(",
"'No route for the request \"%s\"'",
",",
"agi_network_script",
")",
"else",
":",
"log",
".",
"error",
"(",
"'No agi_network_script header for the request'",
")",
"log",
".",
"debug",
"(",
"\"Closing client socket\"",
")",
"writer",
".",
"close",
"(",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
parse_agi_result
|
Parse AGI results using Regular expression.
AGI Result examples::
100 result=0 Trying...
200 result=0
200 result=-1
200 result=132456
200 result= (timeout)
510 Invalid or unknown command
520-Invalid command syntax. Proper usage follows:
int() argument must be a string, a bytes-like object or a number, not
'NoneType'
HANGUP
|
panoramisk/utils.py
|
def parse_agi_result(line):
"""Parse AGI results using Regular expression.
AGI Result examples::
100 result=0 Trying...
200 result=0
200 result=-1
200 result=132456
200 result= (timeout)
510 Invalid or unknown command
520-Invalid command syntax. Proper usage follows:
int() argument must be a string, a bytes-like object or a number, not
'NoneType'
HANGUP
"""
# print("--------------\n", line)
if line == 'HANGUP':
return {'error': 'AGIResultHangup',
'msg': 'User hungup during execution'}
kwargs = dict(code=0, response="", line=line)
m = re_code.search(line)
try:
kwargs.update(m.groupdict())
except AttributeError:
# None has no attribute groupdict
pass
return agi_code_check(**kwargs)
|
def parse_agi_result(line):
"""Parse AGI results using Regular expression.
AGI Result examples::
100 result=0 Trying...
200 result=0
200 result=-1
200 result=132456
200 result= (timeout)
510 Invalid or unknown command
520-Invalid command syntax. Proper usage follows:
int() argument must be a string, a bytes-like object or a number, not
'NoneType'
HANGUP
"""
# print("--------------\n", line)
if line == 'HANGUP':
return {'error': 'AGIResultHangup',
'msg': 'User hungup during execution'}
kwargs = dict(code=0, response="", line=line)
m = re_code.search(line)
try:
kwargs.update(m.groupdict())
except AttributeError:
# None has no attribute groupdict
pass
return agi_code_check(**kwargs)
|
[
"Parse",
"AGI",
"results",
"using",
"Regular",
"expression",
"."
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/utils.py#L18-L54
|
[
"def",
"parse_agi_result",
"(",
"line",
")",
":",
"# print(\"--------------\\n\", line)",
"if",
"line",
"==",
"'HANGUP'",
":",
"return",
"{",
"'error'",
":",
"'AGIResultHangup'",
",",
"'msg'",
":",
"'User hungup during execution'",
"}",
"kwargs",
"=",
"dict",
"(",
"code",
"=",
"0",
",",
"response",
"=",
"\"\"",
",",
"line",
"=",
"line",
")",
"m",
"=",
"re_code",
".",
"search",
"(",
"line",
")",
"try",
":",
"kwargs",
".",
"update",
"(",
"m",
".",
"groupdict",
"(",
")",
")",
"except",
"AttributeError",
":",
"# None has no attribute groupdict",
"pass",
"return",
"agi_code_check",
"(",
"*",
"*",
"kwargs",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
agi_code_check
|
Check the AGI code and return a dict to help on error handling.
|
panoramisk/utils.py
|
def agi_code_check(code=None, response=None, line=None):
"""
Check the AGI code and return a dict to help on error handling.
"""
code = int(code)
response = response or ""
result = {'status_code': code, 'result': ('', ''), 'msg': ''}
if code == 100:
result['msg'] = line
elif code == 200:
for key, value, data in re_kv.findall(response):
result[key] = (value, data)
# If user hangs up... we get 'hangup' in the data
if data == 'hangup':
return {
'error': 'AGIResultHangup',
'msg': 'User hungup during execution'}
elif key == 'result' and value == '-1':
return {
'error': 'AGIAppError',
'msg': 'Error executing application, or hangup'}
elif code == 510:
result['error'] = 'AGIInvalidCommand'
elif code == 520:
# AGI Usage error
result['error'] = 'AGIUsageError'
result['msg'] = line
else:
# Unhandled code or undefined response
result['error'] = 'AGIUnknownError'
result['msg'] = line
return result
|
def agi_code_check(code=None, response=None, line=None):
"""
Check the AGI code and return a dict to help on error handling.
"""
code = int(code)
response = response or ""
result = {'status_code': code, 'result': ('', ''), 'msg': ''}
if code == 100:
result['msg'] = line
elif code == 200:
for key, value, data in re_kv.findall(response):
result[key] = (value, data)
# If user hangs up... we get 'hangup' in the data
if data == 'hangup':
return {
'error': 'AGIResultHangup',
'msg': 'User hungup during execution'}
elif key == 'result' and value == '-1':
return {
'error': 'AGIAppError',
'msg': 'Error executing application, or hangup'}
elif code == 510:
result['error'] = 'AGIInvalidCommand'
elif code == 520:
# AGI Usage error
result['error'] = 'AGIUsageError'
result['msg'] = line
else:
# Unhandled code or undefined response
result['error'] = 'AGIUnknownError'
result['msg'] = line
return result
|
[
"Check",
"the",
"AGI",
"code",
"and",
"return",
"a",
"dict",
"to",
"help",
"on",
"error",
"handling",
"."
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/utils.py#L57-L88
|
[
"def",
"agi_code_check",
"(",
"code",
"=",
"None",
",",
"response",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"code",
"=",
"int",
"(",
"code",
")",
"response",
"=",
"response",
"or",
"\"\"",
"result",
"=",
"{",
"'status_code'",
":",
"code",
",",
"'result'",
":",
"(",
"''",
",",
"''",
")",
",",
"'msg'",
":",
"''",
"}",
"if",
"code",
"==",
"100",
":",
"result",
"[",
"'msg'",
"]",
"=",
"line",
"elif",
"code",
"==",
"200",
":",
"for",
"key",
",",
"value",
",",
"data",
"in",
"re_kv",
".",
"findall",
"(",
"response",
")",
":",
"result",
"[",
"key",
"]",
"=",
"(",
"value",
",",
"data",
")",
"# If user hangs up... we get 'hangup' in the data",
"if",
"data",
"==",
"'hangup'",
":",
"return",
"{",
"'error'",
":",
"'AGIResultHangup'",
",",
"'msg'",
":",
"'User hungup during execution'",
"}",
"elif",
"key",
"==",
"'result'",
"and",
"value",
"==",
"'-1'",
":",
"return",
"{",
"'error'",
":",
"'AGIAppError'",
",",
"'msg'",
":",
"'Error executing application, or hangup'",
"}",
"elif",
"code",
"==",
"510",
":",
"result",
"[",
"'error'",
"]",
"=",
"'AGIInvalidCommand'",
"elif",
"code",
"==",
"520",
":",
"# AGI Usage error",
"result",
"[",
"'error'",
"]",
"=",
"'AGIUsageError'",
"result",
"[",
"'msg'",
"]",
"=",
"line",
"else",
":",
"# Unhandled code or undefined response",
"result",
"[",
"'error'",
"]",
"=",
"'AGIUnknownError'",
"result",
"[",
"'msg'",
"]",
"=",
"line",
"return",
"result"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
IdGenerator.reset
|
Mostly used for unit testing. Allow to use a static uuid and reset
all counter
|
panoramisk/utils.py
|
def reset(cls, uid=None):
"""Mostly used for unit testing. Allow to use a static uuid and reset
all counter"""
for instance in cls.instances:
if uid:
instance.uid = uid
instance.generator = instance.get_generator()
|
def reset(cls, uid=None):
"""Mostly used for unit testing. Allow to use a static uuid and reset
all counter"""
for instance in cls.instances:
if uid:
instance.uid = uid
instance.generator = instance.get_generator()
|
[
"Mostly",
"used",
"for",
"unit",
"testing",
".",
"Allow",
"to",
"use",
"a",
"static",
"uuid",
"and",
"reset",
"all",
"counter"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/utils.py#L129-L135
|
[
"def",
"reset",
"(",
"cls",
",",
"uid",
"=",
"None",
")",
":",
"for",
"instance",
"in",
"cls",
".",
"instances",
":",
"if",
"uid",
":",
"instance",
".",
"uid",
"=",
"uid",
"instance",
".",
"generator",
"=",
"instance",
".",
"get_generator",
"(",
")"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
IdGenerator.get_instances
|
Mostly used for debugging
|
panoramisk/utils.py
|
def get_instances(self):
"""Mostly used for debugging"""
return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__,
i.prefix, self.uid)
for i in self.instances]
|
def get_instances(self):
"""Mostly used for debugging"""
return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__,
i.prefix, self.uid)
for i in self.instances]
|
[
"Mostly",
"used",
"for",
"debugging"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/utils.py#L137-L141
|
[
"def",
"get_instances",
"(",
"self",
")",
":",
"return",
"[",
"\"<%s prefix:%s (uid:%s)>\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"i",
".",
"prefix",
",",
"self",
".",
"uid",
")",
"for",
"i",
"in",
"self",
".",
"instances",
"]"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
test
|
Message.success
|
return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False
|
panoramisk/message.py
|
def success(self):
"""return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False
"""
if 'event' in self:
return True
if self.response in self.success_responses:
return True
return False
|
def success(self):
"""return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False
"""
if 'event' in self:
return True
if self.response in self.success_responses:
return True
return False
|
[
"return",
"True",
"if",
"a",
"response",
"status",
"is",
"Success",
"or",
"Follows",
":"
] |
gawel/panoramisk
|
python
|
https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/message.py#L61-L77
|
[
"def",
"success",
"(",
"self",
")",
":",
"if",
"'event'",
"in",
"self",
":",
"return",
"True",
"if",
"self",
".",
"response",
"in",
"self",
".",
"success_responses",
":",
"return",
"True",
"return",
"False"
] |
2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.