Calculating distance in vapor4
The answer to your immediate question is to just return newUsers
, changing the return type of your route as shown, but I would also decode using something like:
struct LocData: Decodable {
let userLocation: Pers.UserLocation
let pers: [Pers]
}
func temp(_ req:Request) throws -> [Pers] {
let locData = try req.content.decode(LocData.self)
let userlocation = locData.userLocation
let mylocation = CLLocation(latitude: userlocation.latitude, longitude: userlocation.longitude)
return locData.pers.filter{ user in
let location = CLLocation(latitude: user.latitude, longitude: user.longitude)
return location.distance(from: mylocation) < 100
}
}
Your JSON needs to look something like:
{ "userLocation" : { ... },
"pers" : [ ... ]
}
Your subsequent problem is you are trying to decode the request data two different ways. The first one works but the second one fails. You were only supplying JSON data for the first decode in your example image, so there was no array for the second decode.
The more fundamental issue is that you should really be doing this operation client-side, given that you must have all the source data you need in order to send it to the server. It doesn't make sense to transfer a potentially large dataset to do a simple, self-contained calculation only to return (a subset of) the same dataset as a response. See How to find my distance to a known location in JavaScript for an example implementation of the required calculation.
Returning reasonable data in vapor4
The short answer is that you can use the subset query to get all the users from a subset, e.g.
return Pers.query(on: req.db).filter(\.$user.$id ~~ newUsers.compactMap { $0.id }).all()
However there are a number of serious issues with your code. For starters if you're planning on deploying to Linux you cannot use CoreLocation. Second you're doing the location filter on the server instead of the database, so if you have a lot of users that query is going to be slow as you need to get every user from the database. A PostGIS query would be much more efficient.
Finally what are you trying to achieve with user defaults? They should not be used in server-side Swift. The way you have it is that the coordinates will be taken from whoever accessed the take
endpoint last, even if it's not the same person accessing the all
endpoint.
Measure total count and avg distance between points - python
You can try:
# distance to reference point
dist = np.square(df[['x_ref','y_ref']] - df[['x','y']].values).sum(1) ** 0.5
(dist[dist.le(2)&dist.gt(0)] # filter the valid points
.groupby(df['Time']) # groupby Time
.agg(['mean', 'count']) # count and mean
.reindex(df.Time.unique(), fill_value=0)
)
Output:
mean count
Time
1 0.0 0
2 1.0 1
How to find my distance to a known location in JavaScript
If your code runs in a browser, you can use the HTML5 geolocation API:
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
})
Once you know the current position and the position of your "target", you can calculate the distance between them in the way documented in this question: Calculate distance between two latitude-longitude points? (Haversine formula).
So the complete script becomes:
function distance(lon1, lat1, lon2, lat2) {
var R = 6371; // Radius of the earth in km
var dLat = (lat2-lat1).toRad(); // Javascript functions in radians
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
console.log(
distance(pos.coords.longitude, pos.coords.latitude, 42.37, 71.03)
);
});
Apparently I am 6643 meters from the center of Boston, MA right now (that's the hard-coded second location).
See these links for more information:
- http://html5demos.com/geo
- http://diveintohtml5.info/geolocation.html
- Calculate distance between two latitude-longitude points? (Haversine formula)
- toRad() Javascript function throwing error
how can I improve my code to calculate distance between two locations in Swift?
I would like to suggest two things:
- Don't round the double, but format the result when converting to string for displaying
- Don't make the formatting change at 4, it does not seem very intuitive
If you can live with these suggestions, you could use NumberFormatter
to format to specific number of significant digits:
let nums = [0.12345, 1.56789, 2.49876, 5.99999, 9.49876, 11.55555, 19.54321, 123.6]
let formatter: NumberFormatter = {
let f = NumberFormatter()
f.maximumSignificantDigits = 2
return f
} ()
nums.forEach {
print(formatter.string(from: NSNumber(value: $0)) ?? "n/a")
}
// Prints:
// 0.12
// 1.6
// 2.5
// 6
// 9.5
// 12
// 20
// 120
Efficient way to compute pairwise euclidean distances between all vectors in a tensor in TensorFlow
I used the Euclidean Distance Matrix Trick from here
The numpy
adaption is the following:
feature_map = tf.reshape(feature_map,(b,-1,c))
G = np.einsum('bik, bjk->bij', feature_map, feature_map)
D = G.diagonal(axis1=1,axis2=2).reshape(b,-1,1)+ np.transpose(G.diagonal(axis1=1,axis2=2).reshape(b,-1,1),axes=(0,2,1)) - 2*G
norms = np.sqrt(D)
and the corresponding tensorflow
adaptation:
feature_map = tf.reshape(feature_map,(b,-1,c))
G = tf.einsum('bik, bjk->bij', feature_map, feature_map)
D = tf.reshape(tf.linalg.diag_part(G),(b,-1,1))+ tf.transpose(tf.reshape(tf.linalg.diag_part(G),(b,-1,1)),perm=(0,2,1)) - 2*G
norms = tf.sqrt(D)
Related Topics
Swift How to Make List Start at The Top with No Padding
Why Does a Function Have Long-Term Write Access to All of Its In-Out Parameters
Convert Input Data to Integer in Swift
Using Nsdate to Get Date for Easter
Add a File Generated by Run Script into The Test Target Compilation List in Xcode
Xcode 6.1 Swift Extensions - Sourcekit Service Crash
Swift: Guard Let and Where - The Priority
Parsing JSON from Url Ends Up with an Error - Swift 5
Invalid Update: Invalid Number of Rows in Section 1
Do Protocols Have an Effect on The Retain Count
Switch Statement Where Value Is Int But Case Can Contain Array
How Do Uniqueness Constraints as (Comma,Separated,Attributes) Work with Swift in Coredata
Swift 4: How to Asynchronously Use Urlsessiondatatask But Have The Requests Be in a Timed Queue
How to Access Results from a Realm in Swift
Swift - Setting Calayer Bounds or Frame Not Working
Pie Chart Entries Outside Slices Have Different Position Offsets