Search Results

Search found 104 results on 5 pages for 'radians'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • How to combine a Distance and Keyword SQL query?

    - by Jason
    Hi Folks, I have a tables in my database called "points" and "category". A user will input info into both a location input and a keyword input text box. Then I want to find points in my table where the keyword matches either the "title" field in the points table, or the "category" but are within a certain distance from the user's location. I want to order the results by distance. Here are the 2 queries which btoh work independently: $mysql = "SELECT *, ( 3959 * acos( cos( radians('$search_lat') ) * cos( radians( lat ) ) * cos( radians( longi ) - radians('$search_lng') ) + sin( radians('$search_lat') ) * sin( radians( lat ) ) ) ) AS distance FROM points HAVING distance < '$radius'"; $mysql2 = "SELECT * FROM `points` LEFT JOIN category USING ( category_id ) WHERE (point_title LIKE '%$esc_catsearch%' OR category.title LIKE '%$esc_catsearch%')"; Here is what I tried: $sql_search = sprintf("SELECT *,point_id FROM points WHERE point_title LIKE '%%%s%%' UNION SELECT *, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( longi ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM points HAVING distance < '%s' ORDER BY distance LIMIT %d , %d", $esc_catsearch, mysql_real_escape_string($search_lat), mysql_real_escape_string($search_lng), mysql_real_escape_string($search_lat), mysql_real_escape_string($radius), $offset, $rowsPerPage); But it tells me there is no know column "distance". If I remove the "Order By" phrase then it works but I'm still not sure this is giving me the results I want. I also tried the query the other way around with the distance search first but that seems to ignore my keyword. Any thoughts would be much appreciated!

    Read the article

  • Is there any valid reason radians are used as the inputs to trig function in many modern languages?

    - by johnmortal
    Is there any pressing reason trig functions should use radian inputs in modern programming languages? As far as I know radians are typically ugly to deal with except in three cases: (1) You want to compute an arc length and you know the angle of the arc and (2) You need to do symbolic calculus with trig functions (3) certain infinite series expansion look prettier if the input is in radians. None of these scenarios seem like a worthy justification for every programming language I am familiar with using radian inputs for Sin, Cos, Tangent, etc... The third one sounds good because it might mean one gets faster computations using radians (very slightly faster- the cost of one additional floating point multiplication ) , but I am dubious even of that because most commonly the developer had to take an extra step to put the angle in radians in the first place. The other two are ridiculous justifications for all the added obscurity.

    Read the article

  • How do I draw the points in an ESRI Polyline, given the bounding box as lat/long and the "points" as

    - by Aaron
    I'm using OpenMap and I'm reading a ShapeFile using com.bbn.openmap.layer.shape.ShapeFile. The bounding box is read in as lat/long points, for example 39.583642,-104.895486. The bounding box is a lower-left point and an upper-right point which represents where the points are contained. The "points," which are named "radians" in OpenMap, are in a different format, which looks like this: [0.69086486, -1.8307719, 0.6908546, -1.8307716, 0.6908518, -1.8307717, 0.69085056, -1.8307722, 0.69084936, -1.8307728, 0.6908477, -1.8307738, 0.69084626, -1.8307749, 0.69084185, -1.8307792]. How do I convert the points like "0.69086486, -1.8307719" into x,y coordinates that are usable in normal graphics? I believe all that's needed here is some kind of conversion, because bringing the points into Excel and graphing them creates a line whose curve matches the curve of the road at the given location (lat/long). However, the axises need to be adjusted manually and I have no reference as how to adjust the axises, since the given bounding box appears to be in a different format than the given points. The ESRI Shapefile technical description doesn't seem to mention this (http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf).

    Read the article

  • Geolocation SQL query not finding exact location

    - by Iridium52
    I have been testing my geolocation query for some time now and I haven't found any issues with it until now. I am trying to search for all cities within a given radius, often times I'm searching for cities surrounding a city using that city's coords, but recently I tried searching around a city and found that the city itself was not returned. I have these cities as an excerpt in my database: city latitude longitude Saint-Mathieu 45.316708 -73.516253 Saint-Édouard 45.233374 -73.516254 Saint-Michel 45.233374 -73.566256 Saint-Rémi 45.266708 -73.616257 But when I run my query around the city of Saint-Rémi, with the following query... SELECT tblcity.city, tblcity.latitude, tblcity.longitude, truncate((degrees(acos( sin(radians(tblcity.latitude)) * sin(radians(45.266708)) + cos(radians(tblcity.latitude)) * cos(radians(45.266708)) * cos(radians(tblcity.longitude - -73.616257) ) ) ) * 69.09*1.6),1) as distance FROM tblcity HAVING distance < 10 ORDER BY distance desc I get these results: city latitude longitude distance Saint-Mathieu 45.316708 -73.516253 9.5 Saint-Édouard 45.233374 -73.516254 8.6 Saint-Michel 45.233374 -73.566256 5.3 The town of Saint-Rémi is missing from the search. So I tried a modified query hoping to get a better result: SELECT tblcity.city, tblcity.latitude, tblcity.longitude, truncate(( 6371 * acos( cos( radians( 45.266708 ) ) * cos( radians( tblcity.latitude ) ) * cos( radians( tblcity.longitude ) - radians( -73.616257 ) ) + sin( radians( 45.266708 ) ) * sin( radians( tblcity.latitude ) ) ) ),1) AS distance FROM tblcity HAVING distance < 10 ORDER BY distance desc But I get the same result... However, if I modify Saint-Rémi's coords slighly by changing the last digit of the lat or long by 1, both queries will return Saint-Rémi. Also, if I center the query on any of the other cities above, the searched city is returned in the results. Can anyone shed some light on what may be causing my queries above to not display the searched city of Saint-Rémi? I have added a sample of the table (with extra fields removed) below. I'm using MySQL 5.0.45, thanks in advance. CREATE TABLE `tblcity` ( `IDCity` int(1) NOT NULL auto_increment, `City` varchar(155) NOT NULL default '', `Latitude` decimal(9,6) NOT NULL default '0.000000', `Longitude` decimal(9,6) NOT NULL default '0.000000', PRIMARY KEY (`IDCity`) ) ENGINE=MyISAM AUTO_INCREMENT=52743 DEFAULT CHARSET=latin1 AUTO_INCREMENT=52743; INSERT INTO `tblcity` (`city`, `latitude`, `longitude`) VALUES ('Saint-Mathieu', 45.316708, -73.516253), ('Saint-Édouard', 45.233374, -73.516254), ('Saint-Michel', 45.233374, -73.566256), ('Saint-Rémi', 45.266708, -73.616257);

    Read the article

  • Simple XNA 2D demo: why is my F# version slower than C# version?

    - by Den
    When running this XNA application it should display a rotated rectangle that moves from top-left corner to bottom-right corner. It looks like my F# version is noticeably much slower. It seems that the Draw method skips a lot of frames. I am using VS 2012 RC, XNA 4.0, .NET 4.5, F# 3.0. I am trying to make it as functional as possible. What could be the reason for poor performance? C#: class Program { static void Main(string[] args) { using (var game = new FlockGame()) { game.Run(); } } } public class FlockGame : Game { private GraphicsDeviceManager graphics; private DrawingManager drawingManager; private Vector2 position = Vector2.Zero; public FlockGame() { graphics = new GraphicsDeviceManager(this); } protected override void Initialize() { drawingManager = new DrawingManager(graphics.GraphicsDevice); this.IsFixedTimeStep = false; } protected override void Update(GameTime gameTime) { position = new Vector2(position.X + 50.1f * (float)gameTime.ElapsedGameTime.TotalSeconds, position.Y + 50.1f * (float)gameTime.ElapsedGameTime.TotalSeconds); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { //this.GraphicsDevice.Clear(Color.Lavender) drawingManager.DrawRectangle(position, new Vector2(100.0f, 100.0f), 0.7845f, Color.Red); base.Draw(gameTime); } } public class DrawingManager { private GraphicsDevice GraphicsDevice; private Effect Effect; public DrawingManager(GraphicsDevice graphicsDevice) { GraphicsDevice = graphicsDevice; this.Effect = new BasicEffect(this.GraphicsDevice) { VertexColorEnabled = true, Projection = Matrix.CreateOrthographicOffCenter(0.0f, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height, 0.0f, 0.0f, 1.0f) }; } private VertexPositionColor[] GetRectangleVertices (Vector2 center, Vector2 size, float radians, Color color) { var halfSize = size/2.0f; var topLeft = -halfSize; var bottomRight = halfSize; var topRight = new Vector2(bottomRight.X, topLeft.Y); var bottomLeft = new Vector2(topLeft.X, bottomRight.Y); topLeft = Vector2.Transform(topLeft, Matrix.CreateRotationZ(radians)) + center; topRight = Vector2.Transform(topRight, Matrix.CreateRotationZ(radians)) + center; bottomRight = Vector2.Transform(bottomRight, Matrix.CreateRotationZ(radians)) + center; bottomLeft = Vector2.Transform(bottomLeft, Matrix.CreateRotationZ(radians)) + center; return new VertexPositionColor[] { new VertexPositionColor(new Vector3(topLeft, 0.0f), color), new VertexPositionColor(new Vector3(topRight, 0.0f), color), new VertexPositionColor(new Vector3(topRight, 0.0f), color), new VertexPositionColor(new Vector3(bottomRight, 0.0f), color), new VertexPositionColor(new Vector3(bottomRight, 0.0f), color), new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color), new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color), new VertexPositionColor(new Vector3(topLeft, 0.0f), color) }; } public void DrawRectangle(Vector2 center, Vector2 size, float radians, Color color) { var vertices = GetRectangleVertices(center, size, radians, color); foreach (var pass in this.Effect.CurrentTechnique.Passes) { pass.Apply(); this.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, vertices.Length/2); } } } F#: namespace Flocking module FlockingProgram = open System open Flocking [<STAThread>] [<EntryPoint>] let Main _ = use g = new FlockGame() g.Run() 0 //------------------------------------------------------------------------------ namespace Flocking open System open System.Diagnostics open Microsoft.Xna.Framework open Microsoft.Xna.Framework.Graphics open Microsoft.Xna.Framework.Input type public FlockGame() as this = inherit Game() let mutable graphics = new GraphicsDeviceManager(this) let mutable drawingManager = null let mutable position = Vector2.Zero override Game.LoadContent() = drawingManager <- new Rendering.DrawingManager(graphics.GraphicsDevice) this.IsFixedTimeStep <- false override Game.Update gameTime = position <- Vector2(position.X + 50.1f * float32 gameTime.ElapsedGameTime.TotalSeconds, position.Y + 50.1f * float32 gameTime.ElapsedGameTime.TotalSeconds) base.Update gameTime override Game.Draw gameTime = //this.GraphicsDevice.Clear(Color.Lavender) Rendering.DrawRectangle(drawingManager, position, Vector2(100.0f, 100.0f), 0.7845f, Color.Red) base.Draw gameTime //------------------------------------------------------------------------------ namespace Flocking open System open System.Collections.Generic open Microsoft.Xna.Framework open Microsoft.Xna.Framework.Graphics open Microsoft.Xna.Framework.Input module Rendering = [<AllowNullLiteral>] type DrawingManager (graphicsDevice : GraphicsDevice) = member this.GraphicsDevice = graphicsDevice member this.Effect = new BasicEffect(this.GraphicsDevice, VertexColorEnabled = true, Projection = Matrix.CreateOrthographicOffCenter(0.0f, float32 this.GraphicsDevice.Viewport.Width, float32 this.GraphicsDevice.Viewport.Height, 0.0f, 0.0f, 1.0f)) let private GetRectangleVertices (center:Vector2, size:Vector2, radians:float32, color:Color) = let halfSize = size / 2.0f let mutable topLeft = -halfSize let mutable bottomRight = halfSize let mutable topRight = new Vector2(bottomRight.X, topLeft.Y) let mutable bottomLeft = new Vector2(topLeft.X, bottomRight.Y) topLeft <- Vector2.Transform(topLeft, Matrix.CreateRotationZ(radians)) + center topRight <- Vector2.Transform(topRight, Matrix.CreateRotationZ(radians)) + center bottomRight <- Vector2.Transform(bottomRight, Matrix.CreateRotationZ(radians)) + center bottomLeft <- Vector2.Transform(bottomLeft, Matrix.CreateRotationZ(radians)) + center [| new VertexPositionColor(new Vector3(topLeft, 0.0f), color) new VertexPositionColor(new Vector3(topRight, 0.0f), color) new VertexPositionColor(new Vector3(topRight, 0.0f), color) new VertexPositionColor(new Vector3(bottomRight, 0.0f), color) new VertexPositionColor(new Vector3(bottomRight, 0.0f), color) new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color) new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color) new VertexPositionColor(new Vector3(topLeft, 0.0f), color) |] let DrawRectangle (drawingManager:DrawingManager, center:Vector2, size:Vector2, radians:float32, color:Color) = let vertices = GetRectangleVertices(center, size, radians, color) for pass in drawingManager.Effect.CurrentTechnique.Passes do pass.Apply() drawingManager.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, vertices.Length/2)

    Read the article

  • I need to write a program that reads angles in radians from an input disk and converts them in degre

    - by Amadou
    Write a program that reads angles in radians from an input disk le and converts them into degrees, minutes, and seconds. Output should be written into another le. A sample input le could be: # this is a comment # your program should be able to skip comment lines # and blank lines # input radian numbers could be seperated by blanks 0.0 1.0 # or by a newline 3.141593 6.0

    Read the article

  • Converting from samplerate/cutoff frequency to pi-radians/sample in a discrete time sampled IIR filter system.

    - by Fake Name
    I am working on doing some digital filter work using Python and Numpy/Scipy. I'm using scipy.signal.iirdesign to generate my filter coefficents, but it requires the filter passband coefficents in a format I am not familiar with wp, ws : float Passband and stopband edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: wp = 0.2, ws = 0.3 Highpass: wp = 0.3, ws = 0.2 (from here) I'm not familiar with digital filters (I'm coming from a hardware design background). In an analog context, I would determine the desired slope and the 3db down point, and calculate component values from that. In this context, how do I take a known sample rate, a desired corner frequency, and a desired rolloff, and calculate the wp, ws values from that? (This might be more appropriate for math.stackexchange. I'm not sure)

    Read the article

  • Function to get X, Y position of an object orbiting a point, given a distance and angle in radians?

    - by Jake Petroules
    I am trying to code a function for a camera that orbits a point. Assume a 3d coordinate plane where Z is up. Ignore Z. Let's say the camera's position starts at (0, 0, z). The object to orbit is at, say (50, 50, z). So we have a distance of ~70 units. Calling the function with {(50, 50, z), 70, x} where x is the position in orbit, in radians, should return where the position of the camera should be. I believe this involves cos and tan but my trig isn't that great... point3d getCameraPosition(point3d objectPosition, float distance, float rotationRadians) { // ??? }

    Read the article

  • Fastest distance lookup given latitude/longitude?

    - by Ryan Detzel
    I currently have just under a million locations in a mysql database all with longitude and latitude information. With this I use another lat/lng to find the distance of certain places in the database but it's not as fast as I want it to be especially with 100+ hits a second. Is there a faster formula or possibly a faster system other than mysql for this? The formula I'm using is this. select name, ( 3959 * acos( cos( radians(42.290763) ) * cos( radians( locations.lat ) ) * cos( radians( locations.lng ) - radians(-71.35368) ) + sin( radians(42.290763) ) * sin( radians( locations.lat ) ) ) ) AS distance from locations where active = 1 HAVING distance < 10 ORDER BY distance;

    Read the article

  • Optimising SQL distance query

    - by Alex
    I'm running an MySQL query that returns results based on location. However I have noticed recently that its really slowing down my PHP app. I used CodeIgniter and the profiler shows the query taking 4.2seconds. The geoname table has 500,000 rows. I have some indexes on the key columns, how else can speed up this query? Here is my SQL: SELECT `products`.`product_name`, `geoname`.`geonameid`, `geoname`.`latitude`, `geoname`.`longitude`, `products`.`product_id`, AVG(ratings.vote) as rating, count(comments.comment_id) as total_comments, (6371 * acos(cos(radians(38.7666667)) * cos(radians(geoname.latitude)) * cos(radians(geoname.longitude) - radians(-3.3833333)) + sin(radians(38.7666667)) * sin(radians(geoname.latitude)))) AS distance FROM (`foods`) JOIN `geoname` ON `geoname`.`geonameid` = `products`.`geoname_id` LEFT JOIN `ratings` ON `ratings`.`var_id` = `products`.`product_id` LEFT JOIN `comments` ON `comments`.`var_id` = `products `.`product_id` WHERE `products`.`product_id` != 82 GROUP BY `products`.`product_id` HAVING `distance` < 99 ORDER BY `distance` LIMIT 10

    Read the article

  • Directional Map Search

    - by Rooneyl
    Hello, I am trying so write a bit of code that will search for a given point on a map, but in a given arc of a compass bearing. e.g. 45 degress (north-east), 20 degrees either side. So far I have got a SQL command that will give me the results in a given radius, need some help on how to filter it to a direction. SELECT * FROM (SELECT `place1_id`, `place2_id`, ( 6371 * acos( cos( radians(search_latitude) ) * cos( radians( `location_lat` ) ) * cos( radians( `location_long` ) - radians(search_longitude) ) + sin( radians(search_latitude) ) * sin( radians( `location_lat` ) ) ) ) AS `distance` FROM `place` ORDER BY distance) AS `places` WHERE `places`.`distance` < search_radius AND `places`.`place2_id` = ? Will I be able to do this (if possible) all in SQL, or will it need a bit of PHP applying to it? Any and all help much appreciated!

    Read the article

  • Filter zipcodes by proximity in Django with the Spherical Law of Cosines

    - by spiffytech
    I'm trying to handle proximity search for a basic store locater in Django. Rather than haul PostGIS around with my app just so I can use GeoDjango's distance filter, I'd like to use the Spherical Law of Cosines distance formula in a model query. I'd like all of the calculations to be done in the database in one query, for efficiency. An example MySQL query from The Internet implementing the Spherical Law of Cosines like this: SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM stores HAVING distance < 25 ORDER BY distance LIMIT 0 , 20; The query needs to reference the Zipcode ForeignKey for each store's lat/lng values. How can I make all of this work in a Django model query?

    Read the article

  • Table alias -- Unkown column in field list

    - by Jason
    Hi all, I have a sql query which is executing a LEFT JOIN on 2 tables in which some of the columns are ambiguous. I can prefix the joined tables but when I try to prefix one of the columns from the table in the FROM clause, it tells me Unknown column. I even tried giving that table an alias like so ...From points AS p and using "p" to prefix the tables but that didn't work either. Can someone tell me what I'm doing wrong. Here is my query: SELECT point_title, point_url, address, city, state, zip_code, phone, `points`.`lat`, `points`.`longi`, featured, kmlno, image_url, category.title, category_id, point_id, lat, longi, reviews.star_points, reviews.review_id, count(reviews.point_id) as totals FROM (SELECT *, ( 3959 * acos( cos( radians('37.7717185') ) * cos( radians( lat ) ) * cos( radians( longi ) - radians('-122.4438929') ) + sin( radians('37.7717185') ) * sin( radians( lat ) ) ) ) AS distance FROM points HAVING distance < '25') as distResults LEFT JOIN category USING ( category_id ) LEFT JOIN reviews USING ( point_id ) WHERE (point_title LIKE '%Playgrounds%' OR category.title LIKE '%Playgrounds%') GROUP BY point_id ORDER BY totals DESC, distance LIMIT 0 , 10

    Read the article

  • Rotate a vector by given degrees (errors when value over 90)

    - by Ivan
    I created a function to rotate a vector by a given number of degrees. It seems to work fine when given values in the range -90 to +90. Beyond this, the amount of rotation decreases, i.e., I think objects are rotating the same amount for 80 and 100 degrees. I think this diagram might be a clue to my problem, but I don't quite understand what it's showing. Must I use a different trig function depending on the radians value? The programming examples I've been able to find look similar to mine (not varying the trig functions). Vector2D.prototype.rotate = function(angleDegrees) { var radians = angleDegrees * (Math.PI / 180); var ca = Math.cos(radians); var sa = Math.sin(radians); var rx = this.x*ca - this.y*sa; var ry = this.x*sa + this.y*ca; this.x = rx; this.y = ry; };

    Read the article

  • how to rotate the Circle in DrawRect?

    - by senthilmuthu
    HI, i want to draw a circle in DrawRect through context like pie chart(took from tutorial) thorugh UITouch? i have given the code as follows,how can i rotate ? any help please? define PI 3.14159265358979323846 define snapshot_start 360 define snapshot_finish 360 static inline float radians(double degrees) { return degrees * PI / 180; } - (void)drawRect:(CGRect)rect { // Drawing code CGRect parentViewBounds = self.bounds; CGFloat x = CGRectGetWidth(parentViewBounds)/2; CGFloat y = CGRectGetHeight(parentViewBounds)*0.55; // Get the graphics context and clear it CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextClearRect(ctx, rect); // define stroke color CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1.0); // define line width CGContextSetLineWidth(ctx, 4.0); // need some values to draw pie charts double snapshotCapacity =20; double rawCapacity = 100; double systemCapacity = 1; int offset = 5; double pie1_start = 315.0; double pie1_finish = snapshotCapacity *360.0/rawCapacity; double system_finish = systemCapacity*360.0/rawCapacity; CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor greenColor] CGColor])); CGContextMoveToPoint(ctx, x+2*offset, y); CGContextAddArc(ctx, x+2*offset, y, 100, radians(snapshot_start), radians(snapshot_start+snapshot_finish), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); // system capacity CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:15 green:165/255 blue:0 alpha:1 ] CGColor])); CGContextMoveToPoint(ctx, x+offset,y); CGContextAddArc(ctx, x+offset, y, 100, radians(snapshot_start+snapshot_finish+offset), radians(snapshot_start+snapshot_finish+system_finish), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); /* data capacity */ CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:99/255 green:184/255 blue:255/255 alpha:1 ] CGColor])); CGContextMoveToPoint(ctx, x, y); CGContextAddArc(ctx, x, y, 100, radians(snapshot_start+snapshot_finish+system_finish+offset), radians(snapshot_start), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); }

    Read the article

  • MySQL 1064 error, works in command line and phpMyAdmin; not in app

    - by hundleyj
    Here is my query: select * from (select *, 3956 * 2 * ASIN(SQRT(POWER(SIN(RADIANS(45.5200077 - lat)/ 2), 2) + COS(RADIANS(45.5200077)) * COS(RADIANS(lat)) * POWER(SIN(RADIANS(-122.6942014 - lng)/2),2))) AS distance from stops order by distance, route asc) as p group by route, dir order by distance asc limit 10 This works fine at the command line and in PHPMyAdmin. I'm using Dbslayer to connect to MySQL via my JavaScript backend, and the request is returning a 1064 error. Here is the encoded DBSlayer request string: http://localhost:9090/db?{%22SQL%22:%22select%20*%20from%20%28select%20*,%203956%20*%202%20*%20ASIN%28SQRT%28POWER%28SIN%28RADIANS%2845.5200077%20-%20lat%29/%202%29,%202%29%20+%20COS%28RADIANS%2845.5200077%29%29%20*%20COS%28RADIANS%28lat%29%29%20*%20POWER%28SIN%28RADIANS%28-122.6942014%20-%20lng%29/2%29,2%29%29%29%20AS%20distance%20from%20%60stops%60%20order%20by%20%60distance%60,%20%60route%60%20asc%29%20as%20p%20group%20by%20%60route%60,%20%60dir%60%20order%20by%20%60distance%60%20asc%20limit%2010%22} And the response: {"MYSQL_ERRNO" : 1064 , "MYSQL_ERROR" : "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(RADIANS(45.5200077)) * COS(RADIANS(lat)) * POWER(SIN(RADIANS(-122.6942014 - lng' at line 1" , "SERVER" : "trimet"} Thanks!

    Read the article

  • rotating a circle in UIView?

    - by senthilmuthu
    HI, i want to draw a circle in DrawRect through context like pie chart(took from tutorial) thorugh UITouch? i have given the code as follows,how can i rotate ? any help please? define PI 3.14159265358979323846 define snapshot_start 360 define snapshot_finish 360 static inline float radians(double degrees) { return degrees * PI / 180; } - (void)drawRect:(CGRect)rect { // Drawing code CGRect parentViewBounds = self.bounds; CGFloat x = CGRectGetWidth(parentViewBounds)/2; CGFloat y = CGRectGetHeight(parentViewBounds)*0.55; // Get the graphics context and clear it CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextClearRect(ctx, rect); // define stroke color CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1.0); // define line width CGContextSetLineWidth(ctx, 4.0); // need some values to draw pie charts double snapshotCapacity =20; double rawCapacity = 100; double systemCapacity = 1; int offset = 5; double pie1_start = 315.0; double pie1_finish = snapshotCapacity *360.0/rawCapacity; double system_finish = systemCapacity*360.0/rawCapacity; CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor greenColor] CGColor])); CGContextMoveToPoint(ctx, x+2*offset, y); CGContextAddArc(ctx, x+2*offset, y, 100, radians(snapshot_start), radians(snapshot_start+snapshot_finish), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); // system capacity CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:15 green:165/255 blue:0 alpha:1 ] CGColor])); CGContextMoveToPoint(ctx, x+offset,y); CGContextAddArc(ctx, x+offset, y, 100, radians(snapshot_start+snapshot_finish+offset), radians(snapshot_start+snapshot_finish+system_finish), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); /* data capacity */ CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:99/255 green:184/255 blue:255/255 alpha:1 ] CGColor])); CGContextMoveToPoint(ctx, x, y); CGContextAddArc(ctx, x, y, 100, radians(snapshot_start+snapshot_finish+system_finish+offset), radians(snapshot_start), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); }

    Read the article

  • Adding a computed column to an ActiveRecord query

    - by bmwbzz
    Hi, I am running a query using a scope and some conditions. Something like this: conditions[:offset] = (options[:page].to_i - 1) * PAGE_SIZE unless options[:page].blank? conditions[:limit] = options[:limit] ||= PAGE_SIZE scope = Promo.enabled.active results = scope.all conditions I'd like to add a computed column to the query (at the point when I'm now calling scope.all). Something like this: (ACOS(least(1,COS(0.71106459055501)*COS(-1.2915436464758)*COS(RADIANS(addresses.lat))*COS(RADIANS(addresses.lng))+ COS(0.71106459055501)*SIN(-1.2915436464758)*COS(RADIANS(addresses.lat))*SIN(RADIANS(addresses.lng))+ SIN(0.71106459055501)*SIN(RADIANS(addresses.lat))))*3963.19) as accurate_distance Is there a way to do that without just using find_by_sql and rewriting the whole existing query? Thanks!

    Read the article

  • OpenStreetMap Proximity search using mySQL

    - by Chris
    Hi, I'm just playing around with a dataset of my region generated by JOSM. I moved it into a mySQL DB with the 0.6 API scheme using Osmosis and now I'm desperately trying the following: I want to get all streets of a city. AFAIK there is no tag/relation in the OSM data to determine this so I tried it using a proximity search to get all nodes in a radius around a node representing the city center. Most of the time I looked at the approaches here: http://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula What I got is the following SQL code that should get me the closest 100 nodes around the node with id 36187002 and within a radius of 10km. set @nodeid = 36187002; set @dist = 10; select longitude, latitude into @mylon, @mylat from nodes where id=@nodeid limit 1; SELECT id, ( 6371 * acos( cos( radians(@mylon) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(@mylat) ) + sin( radians(@mylon) ) * sin( radians( latitude ) ) ) ) AS distance FROM nodes HAVING distance < @dist ORDER BY distance LIMIT 0 , 100; Well.. it doesn't work. :( I guess the main problem is that OSM lats/lons are multiplied by 10.000.000 and I don't know how I can correct this function to make it work. Any ideas about this? All solutions/alternatives are very welcome! Have a nice weekend! Chris

    Read the article

  • Python and MySQLdb

    - by rohanbk
    I have the following query that I'm executing using a Python script (by using the MySQLdb module). conn=MySQLdb.connect (host = "localhost", user = "root",passwd = "<password>",db = "test") cursor = conn.cursor () preamble='set @radius=%s; set @o_lat=%s; set @o_lon=%s; '%(radius,latitude,longitude) query='SELECT *, 6371*1000 * acos(cos(radians(@o_lat)) * cos(radians(lat)) * cos(radians(lon) - radians(@o_lon)) + sin(radians(@o_lat)) * sin(radians(lat))) as distance FROM poi_table HAVING distance < @radius ORDER BY distance ASC LIMIT 0, 50' complete_query=preamble+query results=cursor.execute (complete_query) print results The values of radius, latitude, and longitude are not important, but they are being defined when the script executes. What bothers me is that the snippet of code above returns no results; essentially meaning that the way that the query is being executed is wonky. I executed the SQL query (including the set variables with actual values, and it returned the correct number of results). If I modify the query to just be a simple SELECT FROM query (SELECT * FROM poi_table) it returns results. What is going on here?

    Read the article

  • Sunrise / set calculations

    - by dassouki
    I'm trying to calculate the sunset / rise times using python based on the link provided below. My results done through excel and python do not match the real values. Any ideas on what I could be doing wrong? My Excel sheet can be found under .. http://transpotools.com/sun_time.xls # Created on 2010-03-28 # @author: dassouki # @source: [http://williams.best.vwh.net/sunrise_sunset_algorithm.htm][2] # @summary: this is based on the Nautical Almanac Office, United States Naval # Observatory. import math, sys class TimeOfDay(object): def calculate_time(self, in_day, in_month, in_year, lat, long, is_rise, utc_time_zone): # is_rise is a bool when it's true it indicates rise, # and if it's false it indicates setting time #set Zenith zenith = 96 # offical = 90 degrees 50' # civil = 96 degrees # nautical = 102 degrees # astronomical = 108 degrees #1- calculate the day of year n1 = math.floor( 275 * in_month / 9 ) n2 = math.floor( ( in_month + 9 ) / 12 ) n3 = ( 1 + math.floor( in_year - 4 * math.floor( in_year / 4 ) + 2 ) / 3 ) new_day = n1 - ( n2 * n3 ) + in_day - 30 print "new_day ", new_day #2- calculate rising / setting time if is_rise: rise_or_set_time = new_day + ( ( 6 - ( long / 15 ) ) / 24 ) else: rise_or_set_time = new_day + ( ( 18 - ( long/ 15 ) ) / 24 ) print "rise / set", rise_or_set_time #3- calculate sun mean anamoly sun_mean_anomaly = ( 0.9856 * rise_or_set_time ) - 3.289 print "sun mean anomaly", sun_mean_anomaly #4 calculate true longitude true_long = ( sun_mean_anomaly + ( 1.916 * math.sin( math.radians( sun_mean_anomaly ) ) ) + ( 0.020 * math.sin( 2 * math.radians( sun_mean_anomaly ) ) ) + 282.634 ) print "true long ", true_long # make sure true_long is within 0, 360 if true_long < 0: true_long = true_long + 360 elif true_long > 360: true_long = true_long - 360 else: true_long print "true long (360 if) ", true_long #5 calculate s_r_a (sun_right_ascenstion) s_r_a = math.degrees( math.atan( 0.91764 * math.tan( math.radians( true_long ) ) ) ) print "s_r_a is ", s_r_a #make sure it's between 0 and 360 if s_r_a < 0: s_r_a = s_r_a + 360 elif true_long > 360: s_r_a = s_r_a - 360 else: s_r_a print "s_r_a (modified) is ", s_r_a # s_r_a has to be in the same Quadrant as true_long true_long_quad = ( math.floor( true_long / 90 ) ) * 90 s_r_a_quad = ( math.floor( s_r_a / 90 ) ) * 90 s_r_a = s_r_a + ( true_long_quad - s_r_a_quad ) print "s_r_a (quadrant) is ", s_r_a # convert s_r_a to hours s_r_a = s_r_a / 15 print "s_r_a (to hours) is ", s_r_a #6- calculate sun diclanation in terms of cos and sin sin_declanation = 0.39782 * math.sin( math.radians ( true_long ) ) cos_declanation = math.cos( math.asin( sin_declanation ) ) print " sin/cos declanations ", sin_declanation, ", ", cos_declanation # sun local hour cos_hour = ( math.cos( math.radians( zenith ) ) - ( sin_declanation * math.sin( math.radians ( lat ) ) ) / ( cos_declanation * math.cos( math.radians ( lat ) ) ) ) print "cos_hour ", cos_hour # extreme north / south if cos_hour > 1: print "Sun Never Rises at this location on this date, exiting" # sys.exit() elif cos_hour < -1: print "Sun Never Sets at this location on this date, exiting" # sys.exit() print "cos_hour (2)", cos_hour #7- sun/set local time calculations if is_rise: sun_local_hour = ( 360 - math.degrees(math.acos( cos_hour ) ) ) / 15 else: sun_local_hour = math.degrees( math.acos( cos_hour ) ) / 15 print "sun local hour ", sun_local_hour sun_event_time = sun_local_hour + s_r_a - ( 0.06571 * rise_or_set_time ) - 6.622 print "sun event time ", sun_event_time #final result time_in_utc = sun_event_time - ( long / 15 ) + utc_time_zone return time_in_utc #test through main def main(): print "Time of day App " # test: fredericton, NB # answer: 7:34 am long = 66.6 lat = -45.9 utc_time = -4 d = 3 m = 3 y = 2010 is_rise = True tod = TimeOfDay() print "TOD is ", tod.calculate_time(d, m, y, lat, long, is_rise, utc_time) if __name__ == "__main__": main()

    Read the article

  • Bullet physics in python and pygame

    - by Pomg
    I am programming a 2D sidescroller in python and pygame and am having trouble making a bullet go farther than just farther than the player. The bullet travels straight to the ground after i fire it. How, in python code using pygame do I make the bullet go farther. If you need code, here is the method that handles the bullet firing: self.xv += math.sin(math.radians(self.angle)) * self.attrs['speed'] self.yv += math.cos(math.radians(self.angle)) * self.attrs['speed'] self.rect.left += self.xv self.rect.top += self.yv

    Read the article

  • rotating circle with swipe question

    - by Joe
    Okay so I'm making something that basically works as a knob, but only half on the screen -- so I just need horizontal swipes to cause it to rotate. I have it nearly all sorted with one exception: if you change direction of your swipe in mid-swipe, the rotation doesn't change direction. I even can see the problem, but not sure what to do about a solution. So in my touchesMoved, I get the swipe into radians in the predictable way: CGFloat radians = atan2f(location.y - centerY, location.x - centerX); I then store radians, add/subtract it to previous rotation and then give the result to the CATransform3D. So the prob is that even though the swipe changes direction, there is a "balance" which doesn't allow an immediate change of direction. Does this make any sense?

    Read the article

1 2 3 4 5  | Next Page >