Distance Spatial Queries with Tastypie - tastypie

Not sure how to use distance_lte spatial filters with tasty-pie. I can use the contains spatial filter i am unable to figure out the format for the distance_lte filter.
Here is what I have tried:
http://www.domain.com/myapp/api/v1/location/?format=json&coord__distance_lte={"type": "Point", "coordinates": [153.09537, -27.52618]},D(m=5)
Which returns {"error": "Invalid resource lookup data provided (mismatched type)."}

From the tastypie sourcecode:
# If we are filtering on a GeometryApiField then we should try
# and convert this to a GEOSGeometry object. The conversion
# will fail if we don't have value JSON, so in that case we'll
# just return ``value`` as normal.
your D(m=3) is not valid JSON.
This is the Code that is translating the fields:
if isinstance(self.fields[field_name], GeometryApiField):
try:
value = GEOSGeometry(unquote(value))
except ValueError:
pass
return value
Since the following Code should work internally:
Location.objects.filter(location__distance_lte=(fromstr('POINT(153.09537 -27.52618)', srid=4326), D(m=5)))
I could imagine it would need to look a little like:
[{"type": "Point", "coordinates": [153.09537, -27.52618]},{"type": "D", "m" : 5}]
I am not yet getting this to run. Hope you have more luck with it!
EDIT:
Since I couldn't get this to run, I implemented it myself using
Django Tastypie Advanced Filtering: How to do complex lookups with Q objects
Not the ideal solution, but it works.

This is because Tastypie erroneously looks for valid filters using the querysets query.query_terms attributes
It won't contain 'distance', and as a result you get the error.
Except for contains, TastyPie is mostly non-functional with these GIS searches (at least without adding in your own special sauce.)
You could make distance work, for example, by overriding build_filters and adding 'distance' to the valid set of filters:
def build_filters(self, filters=None):
'''
Add in some filters so spatial queries will work.
'''
self._meta.queryset.query.query_terms.update(set(['distance','distance_lte']))
return super(MyResource, self).build_filters(filters)
After which the documentation starts to become correct in regard to how you pass in WKT and/or GeoJSON as get parameters.

Related

Flutter and google places API results

hope someone can help me with this.
I've managed to return search autocomplete results and for the most part everything is ok and results are almost restricted to the area but ocassionaly I get areas outside of the radius when non of the queried letters match the area.
However I want to apply restrictions to display results that are only in the specified area/radius. I've tried applying strictbounds parameter, but strictbounds combined with types : 'address' is just showing no results or single result. When I remove types the results automatically show only points of interest which I don't need. Only need addresses.
Anyone have any idea whats wrong in this?
Uri uri = Uri.https("maps.googleapis.com", "maps/api/place/autocomplete/json", {
"input": query,
"location": poznanLocation,
"language": "pl",
"radius": searchRadius,
"key": apiKey,
"bounds": "52.22,15.33|53.13,17.36",
"strictbounds": "true",
"types": "address",
"sessiontoken": _sessionToken,
});
Are you sure there are suitable results that should be returned?
Depending on the values of location and radius(*), there may be no suitable results left after adding both strictbounds and types=address.
If results are returned when removing strictbounds, are they strictly within the region defined by location and radius? If they are, please file a bug. Otherwise, that is precisely the intended behavior of strictbounds.
(*) The Place Autocomplete web service will ignore the bounds parameter, because it is not supported.

What data source ID to use for Google Fit REST heart rate query?

I'm trying to retrieve aggregate daily heart rate summary data using the Google Fit REST API, but I'm struggling because either I'm missing something or the documentation seems to be very incomplete. I've successfully managed to retrieve aggregate daily step count by following one of the few available examples:
Request URL
https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate
Request body
{
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": 1438705622000,
"endTimeMillis": 1439310422000
}
I can't find any example for reading heart rate, so I'm trying to modify this for heart rate. I found this list of data types where it has this data type: com.google.heart_rate.summary but there isn't any information on what the dataSourceId should be. I tried just omitting it but I get this error:
no default datasource found for: com.google.heart_rate.summary
Does anybody know what I need to use for dataSourceId, or have a link to any decent documentation on data sources?
For resting heart rate, I use this:
"derived:com.google.heart_rate.bpm:com.google.android.gms:resting_heart_rate<-merge_heart_rate_bpm"
For heart rate or BPM, I use this:
"derived:com.google.heart_rate.bpm:com.google.android.gms:merge_heart_rate_bpm"
For completeness, I have included the datasources that I am using below for various readings:
DATA_SOURCE = {
"steps": "derived:com.google.step_count.delta:com.google.android.gms:merge_step_deltas",
"dist": "derived:com.google.distance.delta:com.google.android.gms:from_steps<-merge_step_deltas",
"bpm": "derived:com.google.heart_rate.bpm:com.google.android.gms:merge_heart_rate_bpm",
"rhr": "derived:com.google.heart_rate.bpm:com.google.android.gms:resting_heart_rate<-merge_heart_rate_bpm",
"sleep" : "derived:com.google.sleep.segment:com.google.android.gms:sleep_from_activity<-raw:com.google.activity.segment:com.heytap.wearable.health:stream_sleep",
"cal" : "derived:com.google.calories.expended:com.google.android.gms:from_activities",
"move": "derived:com.google.active_minutes:com.google.android.gms:from_steps<-estimated_steps",
"points" : "derived:com.google.heart_minutes:com.google.android.gms:merge_heart_minutes",
"weight" : "derived:com.google.weight:com.google.android.gms:merge_weight"
}
Depending on the datasource, sometimes it will provide an array of points. You can then choose to take sum, mean, median, etc of all points in the array accordingly.
You can list the data sources available for a given data type, for example :
Method
GET
Request URL
https://www.googleapis.com/fitness/v1/users/me/dataSources?dataTypeName=com.google.heart_rate.summary
Depending on what you're trying to achieve, you'll probably find a source either for com.google.heart_rate.summary or com.google.heart_rate.bpm to meet your needs, including merged sources.

Add rows in smartsheets using python

How do I take a list of values, iterate through it to create the needed objects then pass that "list" of objects to the API to create multiple rows?
I have been successful in adding a new row with a value using the API example. In that example, two objects are created.
row_a = ss_client.models.Row()
row_b = ss_client.models.Row()
These two objects are passed in the add row function. (Forgive me if I use the wrong terms. Still new to this)
response = ss_client.Sheets.add_rows(
2331373580117892, # sheet_id
[row_a, row_b])
I have not been successful in passing an unknown amount of objects with something like this.
newRowsToCreate = []
for row in new_rows:
rowObject = ss.models.Row()
rowObject.cells.append({
'column_id': PM_columns['Row ID Master'],
'value': row
})
newRowsToCreate.append(rowObject)
# Add rows to sheet
response = ss.Sheets.add_rows(
OH_MkrSheetId, # sheet_id
newRowsToCreate)
This returns this error:
{"code": 1062, "errorCode": 1062, "message": "Invalid row location: You must
use at least 1 location specifier.",
Thank you for any help.
From the error message, it looks like you're missing the location specification for the new rows.
Each row object that you create needs to have a location value set. For example, if you want your new rows to be added to the bottom of your sheet, then you would add this attribute to your rowObject.
rowObject.toBottom=True
You can read about this location specific attribute and how it relates to the Python SDK here.
To be 100% precise here I had to set the attribute differently to make it work:
rowObject.to_bottom = True
I've found the name of the property below:
https://smartsheet-platform.github.io/smartsheet-python-sdk/smartsheet.models.html#module-smartsheet.models.row
To be 100% precise here I had to set the attribute differently to make it work:
Yep, the documentation isn't super clear about this other than in the examples, but the API uses camelCase in Javascript, but the same terms are always in snake_case in the Python API (which is, after all, the Pythonic way to do it!)

Get the number of features displayed on a map after a filter (with featuresIn)

First of all, I'm aware that querySourceFeatures could fix that. But unfortunately the new version is effective with all types but not with symbols, which I'm using. So I'm still coding under version 0.14.x.
That said, I filter my map with the setFilter function and I need to catch back the number of features displayed once the filter is done.
I thought about transform the whole world (-90,-180,90,180) map coordinates into pixels and then pass it into a featuresIn function.
With fiddle below, featuresIn returns nothing [EDIT : that was due to not setting interacive : true, now it's done but issue is still here]. Do you have any idea how to get the number of features displayed on my map?
EDIT : Please find my jsFiddle : https://jsfiddle.net/y7hoa0gy/7/
No features are being returned from featuresIn because you did not set "interactive": true on the "route" layer, as specified in the documentation (but no longer on our official docs page because we have changed this API).
/*Now I want to know how many features are still displayed after that filter
My thought was to get the bbox of the whole map (-180,-90,180,90) and make a featuresIn of that bbox.*/
More fundamentally, this approach will not work. featuresIn only returns features in the current viewport. It does not return all features.

How to escape some characters in postgresql

I have this data in one column in postgresql
{
"geometry":{
"status":"Point",
"coordinates":[
-122.421583,
37.795027
]
},
and i using his query
select * from students where data_json LIKE '%status%' ;
Above query return results but this one does not
select * from students where data_json LIKE '%status:%' ;
How can fix that
Of course the 2nd one doesn't find a match, there's no status: text in the value. I think you wanted:
select * from students where data_json LIKE '%"status":%'
... however, like most cases where you attempt text pattern matching on structured data this is in general a terrible idea that will bite you. Just a couple of problem examples:
{
"somekey": "the value is \"status\": true"
}
... where "status": appears as part of the text value and will match even though it shouldn't, and:
{
status : "blah"
}
where status has no quotes and a space between the quotes and colon. As far as JavaScript is concerned this is the same as "status": but it won't match.
If you're trying to find fields within json or extract fields from json, do it with a json parser. PL/V8 may be of interest, or the json libraries available for tools like pl/perl, pl/pythonu, etc. Future PostgreSQL versions will have functions to get a json key by path, test if a json value exists, etc, but 9.2 does not.
At this point you might be thinking "why don't I use regular expressions". Don't go there, you do not want to try to write a full JSON parser in regex. this blog entry is somewhat relevant.