Get locations by GPS position - sqlite

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.

Related

Multiple Y axes on a single plot Octave

What I am trying to do is create something that looks like this,
which I have created by using the Octave pcolor and barh functions using 3 subplots with the subplot x axes scaled to look as if the figure were one plot. However, this approach is unsatisfactory as I cannot zoom or pan across it as I would be able to if it were actually one plot.
How can I plot one background figure using pcolor and then add multiple y axes at different points along the x axis to plot the horizontal histograms using barh?
For some background to this question, I am trying to create what is called a Market Profile chart, i.e. see example here or here.
I have also cross posted this question on the Octave mailing list here.
I have found a way to do what I want. Instead of using the barh function, one can use the fill function instead.
A minimal, reproducible example given below.
## create y and x axes for chart
y_max = max( high_round ) + max_tick_range * tick_size ;
y_min = min( low_round ) - max_tick_range * tick_size ;
y_ax = ( y_min : tick_size : y_max )' ;
end_x_ax_freespace = 5 ;
x_ax = ( 1 : 1 : numel( open ) + end_x_ax_freespace )' ;
colormap( 'viridis' ) ; pcolor( x_ax , y_ax , vp_z' ) ; shading interp ; axis tight ;
## plot the individual volume profiles
hold on ;
scale_factor = 0.18 ;
fill( vp( 1 , : ) .* scale_factor , y_ax' , [99;99;99]./255 ) ;
fill( vp( 2 , : ) .* scale_factor .+ 50 , y_ax' , [99;99;99]./255 ) ;
fill( vp( 3 , : ) .* scale_factor .+ 100 , y_ax' , [99;99;99]./255 ) ;
hold off;
More details on a blog post of mine.

Using Complex Numbers in ODE Problem returns Inexact Error

I am trying to implement to Swing equation for a n-Machine system using Julia.
When i run the following code I get this Error Message:
LoadError: InexactError: Float64(0.0 + 1.0im)
in expression starting at /home/Documents/first_try.jl:61
Swing_Equation(::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}, ::Float64) at complex.jl:37
ODEFunction at diffeqfunction.jl:219 [inlined]
initialize!
The problem is occuring since I am using du[3] = (u[3] * u[2]) * im which can not be a Float64 type. The code is working fine when I remove the im - but then it is not the model I want to implement anymore.
What way is there to work around my problem?
using Plots
using DifferentialEquations
inspectdr()
# Constants
P_m0 = 0.3 # constant Mechanical Power
P_emax = 1
H = 1.01 # Inertia constant of the system
θ_0 = asin(P_m0 / P_emax) # angle of the system
ω_0 = 1.0 # initial angular velocity
M = 2 * H / ω_0
D = 0.9 # Damping constant
u02 = [θ_0;ω_0] # Initial Conditions
tspan = (0.0,100.0) # Time span to solve for
p = [M;P_m0;D]
i = 3
function Swing_Equation(du,u,t,p) # u[1] = angle θ
du[1] = u[2] # u[2] = angular velocity ω
P_e = real(u[3] * conj(i))
du[2] = (1 / M) * ( P_m0 - P_e - D * u[2]) # du[2] = angular acceleration
du[3] = (u[3] * u[2]) * im
end
# solving the differential equations
prob2 = ODEProblem(Swing_Equation,u0,tspan,p)
print(prob2)
sol2 = solve(prob2)
# Visualizing the solutoins
plot(sol2; vars = 1, label = "Θ_kura", line = ("red"))
plot!(sol2; vars = 2, label = "ω_kura", line = ("blue"))
gui()
plot(sol2,vars = (1,2),label="Kurmamoto" ,line = ("purple"))
xlabel!("Θ")
ylabel!("ω")
gui()
The problem is most likely in your input.
prob2 = ODEProblem(Swing_Equation,u0,tspan,p)
I am guessing that in this part you are providing an array of Float64 for u0? Your Swing_Equation then receives u as an Array{Float64} type. I suspect that also means du is the same.
This causes the expression
du[3] = (u[3] * u[2]) * im
to fail because you are trying to assign a Complex{Float64} number to du[3] which is of type Float64. Julia will then try to perform a
convert(Float64, (u[3] * u[2]) * im)
Which will cause the inexact error, because you cannot convert a complex number to a floating point number.
The Solution is to make sure du and u are complex numbers so you avoid this conversion. A quick and dirty way to solve that would be to write:
prob2 = ODEProblem(Swing_Equation, collect(Complex{Float64}, u0),tspan,p)
This will collect all elements in u0 and create a new array where every element is a Complex{Float64}. However this assumes a 1D array. I don't know your case. I don't work with ODE solvers myself.
General Advice to avoid this kind of problem
Add some more type assertions to in your code to make sure you get the kind of inputs you expect. This will help catch these kinds of problem and make you more easily see what is going on.
function Swing_Equation(du::AbstractArray{T}, u::AbstractArray{T}, t,p) where T<:Complex # u[1] = angle θ
du[1] = u[2] :: Complex{Float64}
P_e = real(u[3] * conj(i))
du[2] = (1 / M) * ( P_m0 - P_e - D * u[2]) # du[2] = angular acceleration
du[3] = (u[3] * u[2]) * im
end
Keep in mind Julia is a bit more demanding when it comes to matching up types than other dynamic languages. That is what gives it the performance.
Why is Julia different from Python in this case?
Julia does not upgrade types like Python to whatever fits. Arrays are typed. They cannot contain anything like in Python and other dynamic languages. If you e.g. made an array where each element is an integer, then you cannot assign float values to each element without doing an explicit conversion to floating point first. Otherwise Julia has to warn you that you are getting an inexact error by throwing an exception.
In Python this is not a problem because every element in an array can be a different type. If you want every element in a Julia array to be a different number type then you must create the array as a Array{Number} type but these are very inefficient.
Hope that helps!

Query Haversine with JDO

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)

Classic ASP : what's wrong with my code to convert quantity from dozen to piece (eg. 10.3 dozen = 123 pieces)

What i want is to retrieve quantity in database from piece and covert it to dozen. Then input as dozen and convert back to pieces and save to database again.
when I input data eg. 10.3, it should convert to 123 piece for me ((10 * 12) + 3). My code work well without my "If clause" but only when data was "single" type. It made error when I input integer number, so I added "If.." statement to check it first which is now the output was correct for Integer but incorrect when I input single number.
I have this code..
Function DzToPcs(val)
'If CLng(val) = val then <-- not work
'if Fix(val) <> val then <-- work but the output was not correct when input single type number.
if Int(vInt) = vInt then <-- work but the output was not correct when input single type number.
DztoPcs = val * 12
else
strInt = Cstr(val)
a = Split(strInt,".")
dz = a(0)
pcs = a(1)
getdz = Cint(dz)
getpcs = Cint(pcs)
DztoPcs = (getdz * 12) + getpcs
end if
I'm not sure what's wrong with your if statements (my VBScript is a little rusty), but you could try this alternative:
Function DzToPcs(val)
strInt = Cstr(val)
a = Split(strInt,".")
dz = a(0)
if UBound(a) > 0 then
pcs = a(1)
getdz = Cint(dz)
getpcs = Cint(pcs)
DztoPcs = (getdz * 12) + getpcs
else
DztoPcs = dz * 12
end if
end function

Where does recordPlot() store par() and layout() for first plot?

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)
*/

Resources