I need help to do this query with JDO:
SELECT id, ( 3959 * acos( cos( radians(lat_t) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(lng_t) )
+ sin( radians(lat_t) ) * sin( radians( lat ) ) ) ) AS distance
FROM Stores HAVING distance < 25
ORDER BY distance
I'm trying to consult with proximity coordinates, and much internet searching, I found this algorithm Haversine. The source is Google.
This is what you need:
public static ArrayList<User> getUsers(double lat, double lng, double distance) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(¿?¿?¿?);
...
return users;
}
Thanks!
From: http://db.apache.org/jdo/jdoql_methods.html
When writing the "filter" for a JDOQL Query you can make use of some methods on the various Java
types. The range of methods included as standard in JDOQL is not as flexible as with the true Java
types, but the ones that are available are typically of much use.
You should lookup your values and apply whatever methods you desire on these values.
For the ordering part, the Query interface has a method called setOrdering, pass to it yourColumn ASC|DESC (i.e. ASC OR DESC)
Related
What is the simplest and correct way to round the time and dateTime in XPath?
For example, how to define a function local:round-time-to-minutes in such way that the following test-case:
let $t1 := xs:time( "12:58:37" )
let $t2 := local:round-time-to-minutes( $t1 )
return format-time( $t2, '[H01]:[m01]:[s01]' )
will return "12:59:00".
Don't sure what is better in case of "23:59:31" — to return "00:00:00" or to raise a dynamic error.
And similar function local:round-datetime-to-minutes to handle dateTime?
(it doesn't have such edge case as above)
Let these functions use "round half towards positive infinity" rule, where half is 30.0 seconds.
This is how the solution proposed by #michael.hor257k would look in XQuery:
declare variable $ONE_MIN := xs:dayTimeDuration("PT1M");
declare variable $MIDNIGHT := xs:time("00:00:00");
declare function local:round-time-to-minutes($time) {
$MIDNIGHT + round(($time - $MIDNIGHT) div $ONE_MIN) * $ONE_MIN
};
Another solution is to subtract the number of second from the given dateTime and add one minute (60 seconds) if the number of seconds is not less than 30.
To convert a number of seconds into duration we multiple it on 1S duration (actually, this operation can be eliminated by a compiler).
declare function local:round-time-to-minutes ( $time as xs:time ) {
let $s := seconds-from-time( $time )
return $time - xs:dayTimeDuration('PT1S') * ( $s - 60 * ($s idiv 30) )
};
declare function local:round-dateTime-to-minutes ( $dt as xs:dateTime ) {
let $s := seconds-from-dateTime( $dt )
return $dt - xs:dayTimeDuration('PT1S') * ( $s - 60 * ($s idiv 30) )
};
This solution is uniform for the cases of xs:time and xs:dateTime types.
I currently have a function that updates a value using the sin function, and a timeFactor double that keeps track of how much time has passed since the program started:
double timeFactor;
double delta;
while(running) {
delta = currentTime - lastTime;
timeFactor += delta;
var objectX = sin(timeFactor);
}
However, I need to convert this code to use the delta rather than the timeFactor.
I.e. For updating to sin(time+delta) I only want to use the current value of sin(time) and anything calculated from the value of delta.
I.e. calcualte sin(time+delta) == f(sin(time),delta)
How do I do this?
From math:
sin(A + B) == sin(A) * cos(B) + cos(A) * sin(B)
cos(A + B) == cos(A) * cos(B) - sin(A) * sin(B)
Store sin(A) and cos(A) in two variables.
Then for updating them use temporary copy of one of them, otherwise you will update the second using the new instead of the old value of the first.
Assuming:
persistent objectX stores current and is initialised with initial sin(timeFactor)
persistent objectXc stores current and is initialised with initial cos(timeFactor)
temporary objectXt stores a copy of objectX
("persistent" as in "keeps value across executions of update code",
in contrast to "temporary" as in "only keeps value during update code";
this is to avoid using the "global" attribute, which implies poor data design)
Update code:
objectXt = objectX;
objectX = objectX * cos(delta) + objectXc * sin(delta);
objectXc = objectXc* cos(delta) - objectXt * sin(delta);
Credits to John Coleman for spotting the problem in initial idea to use
1 == sin(A)*sin(A)+cos(A)*cos(A)
That would have been actually
sin(time+delta)== f(sin(time), delta)
But it fails for 50% of a full period.
So I hope this
sin(time+delta)==f(sin(time), cos(time), delta)
also helps.
I have a table called "pois", I want to run SQL query which will show all locations nearest to the phone GPS location in 500 m, I copied the MySQL code somewhere and used it for SQLLite and it does not work, maybe anyone can help me to translate the query to SQLLite query version?
The code is as follows :
Sub GPS_LocationChanged (Location1 As Location)
Loc1 = Location1.Latitude
Loc2 = Location1.Longitude
Dim Cursor As Cursor
Qry = "Select place_id,place_name,lat,lon,poi_catid, ( 6371 * acos( cos( radians( " & Loc1 & " ) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians( " & Loc2 & ") ) + sin( radians( " & Loc1 & " ) ) * sin( radians( lat ) ) ) ) as distance FROM pois HAVING distance < 0.5 ORDER BY distance"
Cursor = SQL1.ExecQuery(Qry)
For i = 0 To 15
Cursor.Position = i
ToastMessageShow(Cursor.GetString("place_name"),True)
Next
Cursor.Close
End Sub
Error message says :
android.database.sqlite.SQLiteException: no such function: acos (code
1):
SQLite doesn't provide mathematical functions you are using and, IFAIK, you can't add user defined functions in Android.
I would calculate a bounding rectangle, to limit database rows, and query database for entries within this rectangle. Then, for each row, calculate exact distance to filter out entries too far. This way I would also save lots of computation time.
There's nothing magical about doing the calculations in the database statement -- the computer is still going to have to examine each individual row. (There's database software which is designed to support efficient spatial queries, but SQLite is not one.) You may as well just select all the rows, and do the distance calculation in VB.
In the following recorded plot, I cannot find the instruction that constructs the layout and sets the par() settings before the first plot.new call()
library( PerformanceAnalytics )
data( managers )
# write the plot to the open device
suppressWarnings(charts.RollingRegression(managers[, 1:6], managers[, 8, drop=FALSE], Rf = .04/12, colorset = rich6equal, legend.loc="topleft"))
# record = investigate the primitive calls. notice no par() nor layout() before the first call to plot.new()
recorded = recordPlot()
lapply(recorded[[1]], "[[", 1 )
# as a result, the following creates one plot per page, not 3 on the same page:
lapply( recorded[[ 1 ]] , function( x ) { do.call( x[[ 1 ]] , as.list( x[[ 2 ]] ) ) } )
Perhaps this is encoded in recorded[[ 2 ]] which looks like some kind of encoded raw data? If so, how could I grab the insructions prior to the first plot.new() from the raw data?
Edit
Warning: dirty hack.
If you want to encode the initial state in the instruction list, here's how:
tryCatch( dev.off() , error = function( e ) {} )
plot.new()
par( new = TRUE )
originalLayoutFunction = graphics:::layout
graphicsEnvironment = as.environment( "package:graphics" )
newLayoutFunction = function( ... )
{
originalLayoutFunction( ... )
par( mfg = c( 1 , 1 ) )
}
unlockBinding( "layout" , env = graphicsEnvironment )
assign( "layout" , newLayoutFunction , envir = graphicsEnvironment )
lockBinding( "layout" , env = graphicsEnvironment )
tryCatch( YOUR_PLOT_CALL_HERE , finally =
{
unlockBinding( "layout" , env = graphicsEnvironment )
assign( "layout" , originalLayoutFunction , env = graphicsEnvironment )
lockBinding( "layout" , env = graphicsEnvironment )
} )
recordedPlot = recordPlot()
dev.off()
You're probably right about what's in recorded[[2]]. My suspicion is that it contains the SEXP which "nicely hides the internals" referenced in this comment from the R sources:
/****************************************************************
* GEcreateSnapshot
****************************************************************
*/
/* Create a recording of the current display,
* including enough information from each registered
* graphics system to be able to recreate the display
* The structure created is an SEXP which nicely hides the
* internals, because noone should be looking in there anyway
* The product of this call can be stored, but should only
* be used in a call to GEplaySnapshot.
*/
A bit further down in the same file ($SRC_HOME/src/main/engine.c) is another possibly illuminating passage.
Like the comment above (and like the recordPlot help file), it too comes with a strongish admonition not to try mucking around with the objects stored by recordPlot(). "Here be dragons", they all say, and it looks like you are starting to meet them that were warned about ;)
/****************************************************************
* GEplaySnapshot
****************************************************************
*/
/* Recreate a saved display using the information in a structure
* created by GEcreateSnapshot.
*
* The graphics engine assumes that it is getting a snapshot
* that was created in THE CURRENT R SESSION
* (Thus, it can assume that registered graphics systems are
* in the same order as they were when the snapshot was
* created -- in patricular, state information will be sent
* to the appropriate graphics system.)
* [With only two systems and base registered on each device at
* creation, that has to be true: and grid does not save any state.]
*
* It also assumes that the system that created the snapshot is
* still loaded (e.g. the grid namespace has not been unloaded).
*
* It is possible to save a snapshot to an R variable
* (and therefore save and reload it between sessions and
* even possibly into a different R version),
* BUT this is strongly discouraged
* (in the documentation for recordPlot() and replayPlot()
* and in the documentation for the Rgui interface on Windows)
*/
I cannot find any examples in CF of the Haversine formula (a formula for working out distances between two points on a sphere from their longitudes and latitudes).
Wikipeda has examples in other languages (http://en.wikipedia.org/wiki/Haversine_formula) but none in CF.
An interpretation in CF is below by another developer, internal, and not fully tested. I am interested to see how others have calculated this in CF. I would also be interested to get opinions on the example below to how it can be simplified.
var variables.intEarthRadius = 6371; // in km
var local.decRadius = arguments.radius / 1000; // convert radius given in metres to kilometres
var local.latMax = arguments.latitude + degree(local.decRadius / variables.intEarthRadius);
var local.latMin = arguments.latitude - degree(local.decRadius / variables.intEarthRadius);
var local.lngMax = arguments.longitude + degree(local.decRadius / variables.intEarthRadius / cos(radian(arguments.latitude)));
var local.lngMin = arguments.longitude - degree(local.decRadius / variables.intEarthRadius / cos(radian(arguments.latitude)));
private numeric function degree(required numeric radian) hint="I convert radians to degrees." {
return arguments.radian * 180 / pi();
}
private numeric function radian(required numeric degrees) hint="I convert degrees to radians." {
return arguments.degrees * pi() / 180;
}
Have you looked at this...
http://cflib.org/udf/getHaversineDistance
(New URL since CFLib.org switched to static site generator)