w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
MongoDB - Querying between a time range of hours
Well, the best way to solve this is to store the minutes separately as well. But you can get around this with the aggregation framework, although that is not going to be very fast: db.so.aggregate( [ { $project: { loc: 1, vid: 1, datetime_recorded: 1, minutes: { $add: [ { $multiply: [ { $hour: '$datetime_recorded' }, 60 ] }, { $minute: '$datetime_recorded' } ] } } }, { $match: { 'minutes' : { $gte : 12 * 60, $lt : 16 * 60 } } } ] ); In the first step $project, we calculate the minutes from hour * 60 + min which we then match against in the second step: $match.

Categories : Mongodb

You are given a set of intervals S. You have to find all intervals in S that are contained in a given interval (a, b) in minimum time complexity
Persistent binary search tree may be used here. Pre-processing: Create empty persistent tree. It should store intervals sorted by their ending points. Sort intervals by their starting points. For each interval, starting from the end of sorted list, create a "copy" of persistent tree and add this interval to this copy. Search: Find starting point of the query interval in sorted list. Iterate corresponding "copy" of persistent tree from the smallest key to end of the query interval. Search time complexity is O(log(n) + m), where m is number of elements in the output.

Categories : Algorithm

speeding up moving time delta with irregular time intervals in a numpy array
Use a ready-made interpolation routine. If you really want nearest neighbor behavior, I think it will have to be scipy's scipy.interpolate.interp1d, but linear interpolation seems a better option, and then you could use numpy's numpy.interp: def trailing_diff(time, data, diff): ret = np.zeros_like(data) mask = (time - time[0]) >= diff ret[mask] = data[mask] - np.interp(time[mask] - diff, time, data) return ret time = np.arange(10) + np.random.rand(10)/2 weight = 82 + np.random.rand(10) >>> time array([ 0.05920317, 1.23000929, 2.36399981, 3.14701595, 4.05128494, 5.22100886, 6.07415922, 7.36161563, 8.37067107, 9.11371986]) >>> weight array([ 82.14004969, 82.36214992, 82.25663272, 82.33764514,

Categories : Python

Redis storing and querying complex structures
You can implement the functionality that you need in a Lua script. When evaluating Lua script Redis loads cjson library among others and this library allows you to parse your JSON to extract values from it. See the EVAL command. http://redis.io/commands/eval A code sample from http://www.kyne.com.au/~mark/software/lua-cjson-manual.html: json_text = '[ true, { "foo": "bar" } ]' value = cjson.decode(json_text) -- Returns: { true, { foo = "bar" } } Mind that Redis evaluates scripts one at a time, and no other clients can run their commands while a script is running, so this might now be suitable for you.

Categories : Database

What is a better approach of storing and querying a big dataset of meteorological data
It's a difficult question and I am not sure if I can give a definite answer but I have experience with both HDF5/pyTables and some NoSQL databases. Here are some thoughts. HDF5 per se has no notion of index. It's only a hierarchical storage format that is well suited for multidimensional numeric data. It's possible to extend on top of HDF5 to implement an index (i.e. PyTables, HDF5 FastQuery) for the data. HDF5 (unless you are using the MPI version) does not support concurrent write access (read access is possible). HDF5 supports compression filters which can - unlike popular belief - make data access actually faster (however you have to think about proper chunk size which depends on the way you access the data). HDF5 is no database. MongoDB has ACID properties, HDF5 doesn't (might be

Categories : Mongodb

Mongoid and Mongodb querying
A far as I know it's only possible to make such a query on the top-most model (in this case Course); I have not seen a way to directly obtain an embedded model like that yet. So this should work, but only gives you the Course: Course.where(name: 'Course1', 'subjects.short_name' => 'Maths', 'subjects.topics.name' => "Algebra 101") And this is the (unfortunately rather ugly) query that should give you what you want: Course.where(name: 'Course1').subjects.where(short_name: 'Maths').topics.where(name: 'Algebra 101')

Categories : Ruby On Rails

mongodb querying sub array
Your query should looks something like this db.alumnos111.find({"materias.id_materia" : { $in : [ "1234", "5678"] }}) to filter out documents w/ id_materia="1234" OR id_materia="5678" This example would be javascript executed straight in the mongo shell

Categories : PHP

Querying Embedded Documents MongoDB
I suggest you to change the schema, so that this someIdAsString text becomes a value instead of a key, making the object in test become a list of objects. If you know every key, you can try db.sample.find({$or: [ {"test.someIdAsString.field1": value1, "test.someIdAsString.field2": value2}, {"test.someOtherIdAsString.field1": value1, "test.someOtherIdAsString.field2": value2}, ... ]}) For all your "someIdAsString" possibilities. If you change the structure to: { _id : ObjectId("someObjectId"), test : [ { _id : someIdAsString, field1 : value1, field2 : value2 }, { _id : someOtherIdAsString, field1 : value3, field2 : value4 }, ... ] } You can

Categories : Mongodb

mongodb querying collection starting with _
Place it in quotes and use the getCollection method. See this article Example To create a collection _foo and insert the { a : 1 } document, use the following operation: db.getCollection("_foo").insert( { a : 1 } ) To perform a query, use the find() method, in as the following: db.getCollection("_foo").find()

Categories : Mongodb

Querying mongodb dbref inner field
Yes, you can query on the DbRef fields, but not the way you are doing it. DbRef is a small sub-documents which contains two fields: $ref -the referenced collection $id - the _id value of a document in that referenced collection (actually there is a third field $db if the reference is to a different db) So, using the shell you can only ask for contacter.$id (which returns the Object id in users collection) or $ref, but you can't query on something such as contract.isActive, as this is a field of the user, not the Ref, and the shell doesn't fetch the user. If you are using java driver, both Contacter and Contactee are represented as com.mongodb.DBRef which has a method fetch() to retrieve the DBObject (user) If using spring-data-mongodb, you might want to have class such as: class

Categories : Java

Mongodb querying from part of object in array
ElemMatch should do the trick. col.findOne({user:{$elemMatch:{"_id":"14bfgdsfg0-3708-46ee-8164-7ee1d029a507", "_id":"aasdfa89-5cfe-4861-8a9a-f77428158ca9" }}})

Categories : Node Js

Querying an array field that contains hashes in mongoDB?
db.collection.find( { "query": { $elemMatch: { "filterId": "5215b40c0ff5fa111e000001", "subfilterId": "60728003610375795" } } } ); You are most probably looking for elemMatch. Check out the docs

Categories : Mongodb

Multi level MongoDB object querying by key
Unfortunately there is no wild card that allows you to search for a field at any level in the db. If the position is not relevant and you can modify the document structure you have 2 choices here. You can store your document as { fieldname:"nickname", value : "Howie" } { fieldname:"user/nickname", value: "Howie" } You can then query using db.so.find({fieldname:/nickname/, value:"Howie"}) Alternatively you can store as db.so.insert({value:"Howie", fieldpath:["nickname"]}) db.so.insert({value:"Howie", fieldpath:["user", "nickname"]}) The advantage with the second approach is that you can now index {fieldpath:1, value:1} and a query on it such as db.so.find({fieldpath:"nickname", value:"Howie"}) will be an indexed query.

Categories : Mongodb

Querying and updating in mongodb using morphia datastore
I didn't understand why you're querying for data.channelId and data.data.topic if you want to find MoDBIAGlobals by id and channelId. And your data modeling it's a quite confusing too. Anyway, seems that your query does not match your document structure. The fields data.data.topic and data.channelId does not exists. Try to fix replacing with code bellow: MoDBIA_DAO dao = new MoDBIA_DAO(mongo, morphia, DB_Name); Datastore dataStore = morphia.createDatastore(mongo, DB_Name); Query<MoDBIAGlobals> query = dataStore.createQuery(MoDBIAGlobals.class).disableValidation(); query.field("data.FACEBOOK.channelId").equal("FB1234"); query.field("data.FACEBOOK.data.topic.NO_TOPIC").equal("NO_TOPIC"); QueryResults<MoDBIAGlobals> results = dao.find(query); System.out.println("results: " + res

Categories : Java

PHP time intervals
Off of the top of my head. You can tweak as necessary. $start = new DateTime('2013-08-14 09:00:00'); $end = new DateTime('2013-08-14 17:00:00'); $interval = new DateInterval('PT30M'); $period = new DatePeriod($start, $interval, $end); foreach ($period as $dt) { // do something echo $dt->format('H:iA'); } Links DateTime DateInterval DatePeriod

Categories : PHP

How to get values from a PHP file querying MongoDB in jQuery's getJSON()?
You want to convert the cursor returned from the find() function to something json_encode can actually use like so: $cursor = $collection->find(array("field2.subfield2" => "value 2")); echo json_encode(iterator_to_array($cursor, false)); This is because the query is not run until you iterate the cursor. Iterator_to_array basically will exhaust the cursor, get all documents, and put them into an array for json_encode. Edit Specifying false as the second $use_keys argument to iterator_to_array() will ensure that the results are indexed numerically (instead of by the _id field of each document).

Categories : PHP

querying array of objects using Java Mongodb driver
The Java drivver along with the python is the most developed one, so you can check it in the driver DOCS. Usually the idea (structure of the commands) is the same as in the shell you just need helpers to construct the command. In Java this documentation can make some hints about how it works:DOCS so for $push: Mongoshell DOCS example: db.students.update( { name: "joe" }, { $push: { scores: 89 } } ) Where { name: "joe" } is a query identifing the right document to update and the scores is an array field and 89 will be abbended. Java DOCS example: check out this question : (MongoDB Java) $push into array $elemmatch: Mongoshell DOCS example: check out this question:Covert MongoDB query into Java $slice: Mongoshell D

Categories : Mongodb

Best way to prepare hierarchical data for easy querying in MongoDB?
You are locking for projection and this. Its optional operator that specifies the fields to return using projection operators and it's boolean 1 - show & 0 - hide db.customers.findOne({"users.mail": "mail@address.org"}, {users: 1}) That's not secure to use findOne({"users.mail": "mail"}) for authentication, there is special Node.js module PassportJS.

Categories : Mongodb

Sum time intervals using linq
You can use Aggregate method. var sum = (from twh in db.MytimeMaster where ((twh.date >= lstsun && twh.date <= tilldate) && (twh.agentID == agentid)) select twh.totalworkinghours).Aggregate(TimeSpan.FromMinutes(0), (total, next) => total + next); p.s. assume used TimeSpan for time intervals.

Categories : C#

Node.js MongoDB .findOne returns best match when querying a String
I'm pretty certain you are getting confused. Your findOne call will do an exact, case-sensitive match. To do partial matches or case-insensitive you need to use a RegExp instance not a basic string. My suggestion is to make a simple test case separate from your app, and my suspicion is the DB is not behaving the way you think it is.

Categories : Javascript

Sort Intervals in Joda-Time
Just create a Comparator<Interval> which compares by start times: public class IntervalStartComparator implements Comparator<Interval> { @Override public int compare(Interval x, Interval y) { return x.getStart().compareTo(y.getStart()); } } Then sort using that: Collections.sort(intervals, new IntervalStartComparator());

Categories : Java

Updating an object with time intervals
I would avoid adding a timer to every object. Perhaps you can have a separate thread which is responsible for initiating updates on your objects. You can use Parallel.ForEach to run concurrent updates on all of your if you think this won't cause concurrency issues. For example, something like: Thread updateThread = new Thread(updateLoop); IEnumerable<Updateable> _updateableObjects; public static void Main() { updateThread.Start(); } private static function UpdateLoop() { while (true) { Parallel.ForEach(_updateableObjects, obj => obj.Update()); Thread.Sleep(1000); } }

Categories : C#

Group time intervals by date (in d3.js)
I would consider changing the data format to [{start: new Date(2013, 2, 4, 0), end: new Date(2013, 2, 4, 8)}, {start: new Date(2013, 2, 4, 22), end: new Date(2013, 2, 5, 2)}, {start: new Date(2013, 2, 5, 5), end: new Date(2013, 2, 7, 5)}] Since you have the start and end date, you don't really need a duration. Alternatively you could have just the start date and a duration. I'm not extremely familiar with the stacklayout, but it might be sufficent (and easier) for this project to simply append rect elements to the right position. I made an example here: http://tributary.io/inlet/5841372 which doesn't take into account the fact that you need to wrap events that start one day and end the next. This just displays all events in the same column, with t

Categories : D3 Js

Set time intervals on images with Javascript/PHP
The problem with having your array in PHP is that only PHP can access it, i.e. JavaScript doesn't know what url's to load. So if you're intent on keeping the php, go with option 1 below, otherwise scrap the php and go with option 2: Option 1 You'll have to use ajax on main view, and keep the php seperate. On the php page, instead of outputting the image, output the image info as a JSON object, e.g. $img = array_rand($img_rand); header('Content-type: application/json'); echo json_encode($img); and then on the page where you're displaying everything, use javascript (I'm using jQuery since it makes ajax way easier) to load the image: <div class="random-img"></div> <script type="text/javascript> imgLoop = function() { $.get('randomimage.php', function(img) {

Categories : PHP

fetch documents from mongodb collection by querying nested dictionary in mongo
You can use the $exists operator and dot notation to do this, but you need to build up your query dynamically like this (in the shell): var user = 'abc'; var query = {}; query['user_details.' + user] = { $exists: true }; db.coll.find(query);

Categories : Python

Grouping DateTime by arbitrary time intervals
You just need to offset all of the dates before grouping. TimeSpan offset = startTime.TimeOfDay; TimeSpan interval = TimeSpan.FromMinutes(45); var selected = from date in item.Dates group date by ((date.Ticks - offset.Ticks) / interval.Ticks) into g select g;

Categories : C#

Find overlapping or conflicting time intervals
You need to self-join the table and look for conflicts between pairs SELECT t1.id, t1.start, t1.end FROM table_name t1 JOIN table_name t2 WHERE t1.start < t2.end AND t2.start < t1.end AND t1.id <> t2.id AND t1.date = t2.date You can use a SELECT DISTINCT or a GROUP BY to trim the duplicates in the output.

Categories : Mysql

Find holes in Joda-Time intervals
A quick look at the Interval API gives this (UNTESTED): // SUPPOSED: the big interval is "bigInterval"; the list is "intervals" // Intervals returned List<Interval> ret = new ArrayList<>(); Interval gap, current, next; // First, compute the gaps between the elements in the list current = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { next = intervals.get(i); gap = current.gap(next); if (gap != null) ret.add(gap); current = next; } // Now, compute the time difference between the starting time of the first interval // and the starting time of the "big" interval; add it at the beginning ReadableInstant start, end; start = bigInterval.getStart(); end = intervals.get(0).getStart(); if (start.isBefore(end)) ret.add(0, new Inter

Categories : Java

Querying by example using MongoDb, Express in NodeJS is being escaped incorrectly for some reason. I am unable to search
I found a solution. I wasn't able to convert the objects directly to RegExp as explained in the comments below the quesiton. What I did is create a helper function to return a properly formatted regexp query for mongo, and then perform the .find into it. So, the find will be: exports.findByQuery = function(req, res) { var query = req.query; db.collection('users', function(err, collection) { collection.find( parseRegExpProperties(query) ).toArray(function(err, docs) { res.send(docs); }); }); }; And here's the : parseRegExpProperties method. I don't know how safe is this, but it's at least a start for me : function parseRegExpProperties(obj) { var newObject = {}; for(var propName in obj) { if(typeof(obj[propName]) != "undefin

Categories : Node Js

Group time by X minutes, splitting at X minute intervals
Conceptually I would approach this by first grouping by date, then iterate over all the date groups and place the different entries into 5 min time buckets. The time buckets could perhaps be implemented as a predefined Dictionary<int,List<DateTime>> that you add to

Categories : C#

Add 15 minutes to current time and snap to 15 minute intervals
Just to correct my post: $time = time(); $last_time = ($time - ($time % (15 * 60))); $in15mins = $last_time+ (15 * 60); echo 'Now: '. date('Y-m-d H:i') ." "; echo 'in 15 mins: '. date('Y-m-d H:i', $in15mins) ." "; I think it is quite self explaining. Optimize it, use it.

Categories : PHP

How to trigger the reload button in jQGrid at set time intervals
What you need, is to use the same method you've been using before, but to prevent the browser's cache. One method of doing so, is on the server-side, add a no-cache header to to the HTTP response for that request. Another way of doing so, is to change the request's URL, so the browser won't look it up its cache. One example is: var url = "..."; // Your URL url += "&nocache=" + (new Date()).getTime();

Categories : Javascript

Efficient algorithm to divide time intervals as equally as possible
Lets take an example: A = 0 B = 45 C = 100 N = 10 interval (10 interval = 11 bound) 1: Find the ratio X/N which is the closest to the ratio AB / AC 4/10 < 45/100 5/10 we will take X = 4 in this example (the result will vary depending on how you round it. 2: Set the bound number taken from previous calculation to have bound from A to B A to B: Interval number 4 (from previous value) Bound number 5 Average interval length is (45-0) / 4 = 11 Bound 0 = 0 Bound 1 = 11 Bound 2 = 22 Bound 3 = 33 Bound 4 = 45 3: Set the bound number taken from previous calculation to have bound from B to C B to C: Interval number 6 (the rest) Bound number 7 Average interval length is (100 - 45) / 6 = 9 Bound 4 = 45 Bound 5 = 54 Bound 6 = 63 Bound 7 = 72 Bound 8 = 81 Bound 9 = 90 Bound 1

Categories : Algorithm

Reliably select from a database table at fixed time intervals
I probably not got all the details but to answer to your question title "Reliably select from a database table at fixed time intervals"... I don't think you could even hope for a query to be run at "second precise" time. One key problem with that approach is that you will have to deal with concurrent access and lock. You might be able to send the query at fixed time maybe, but your query might be waiting on the DB server for several seconds (or being executed seeing fairly outdated snapshot of the db). Especially in your case since the table is apparently "busy". As a suggestion, if I were you, I would spend some time to think about queue messaging systems (like http://www.rabbitmq.com/ just to cite one, not presaging it is somehow "your" solution). Anyway those kind of tools are prob

Categories : Mysql

Comparing subsequent rows and finding overlapping time intervals?
If you were thinking of this as an N x N comparison, I would imagine that the answer would be some sort of ragged band matrix. (Look it up if band matrix is not a term you've seen before.) This code should test for overlap at the high end of the second column being greater than the first column, i.e., overlapping: Times <- read.table(text=" Num Start End 1 00:09:41 00:25:25 2 00:11:21 00:41:32 3 00:34:39 00:58:01", stringsAsFactors=FALSE, header=TRUE) mdat <- outer(Times$Start, Times$End, function(x,y) y > x) mdat[upper.tri(mdat)|col(mdat)==row(mdat)] <- NA mdat #------------------ [,1] [,2] [,3] [1,] NA NA NA [2,] TRUE NA NA [3,] FALSE TRUE NA You are not interested in the diagonal since End is alw

Categories : R

Using Shield UI JavaScript chart for showing data over small intervals of time
I think that there is a little bit misunderstanding of the type of X axis you actually need. That the results and the data you are representing graphically comes over time doesn’t mean necessary that you need to use the datetime axis. In general datetime type axis is used for showing dates. Setting the step to 1 for a datetime axis as I can see you have done, means that there shall be enough space for showing 86.400.000 points for the single day. Shall there be more days there will be an enormous amount of points which contradicts to the accuracy laboratory data implies. What I might suggest, is that you simply use a linear type of X axis. There are enough ways to show users that the points occur over intervals of 1 millisecond, or one nanosecond and so on.

Categories : Javascript

What could be the cause for GPS issues of variable length during specific time intervals (periodic gps problems)?
There are several factors that can influence the GPS accuracy. Before looking for bugs in your code I would suggest checking the following information: What factors influence GPS accuracy the most? Factors affecting GPS accuracy

Categories : Android

Maximum sum of the range non-overlapping intervals in a list of Intervals
public int longestNonOverLappingTI(TimeInterval[] tis){ Arrays.sort(tis); int[] mt = new int[tis.length]; mt[0] = tis[0].getTime(); for(int j=1;j<tis.length;j++){ for(int i=0;i<j;i++){ int x = tis[j].overlaps(tis[i])?tis[j].getTime():mt[i] + tis[j].getTime(); mt[j] = Math.max(x,mt[j]); } } return getMax(mt); } public class TimeInterval implements Comparable <TimeInterval> { public int start; public int end; public TimeInterval(int start,int end){ this.start = start; this.end = end; } public boolean overlaps(TimeInterval that){ return !(that.end < this.start || this.end < that.start); } public int getTime

Categories : Algorithm

Efficiently finding overlapping intervals from a list of intervals
Create a single, sorted array of transitions. Each transition has a position, and a cumulative number based on how many intervals you're joining or leaving. As you pass through the list, keep track of how many intervals you are in. When you're in as many intervals as series, that's when you're in a common interval. For your example the transitions would be: [2, 1], [6, -1], [7, 1], [11, -1], [1, 1], [3, -1], [5, 1], [10, -1], [11, 1], [13, -1] [2, 1], [5, -1], [6, 1], [8, -1] which after sorting by position and merging collapses to: [1, 1], [2, 2], [3, -1], [5, 0], [6, 0], [7, 1], [8, -1], [10, -1], [11, 0], [13, -1] which gives you transitions for running totals of: [1, 1], [2, 3], [3, 2], [7, 3], [8, 2], [10, 2], [13, 1] And then we can read off the intervals where we're at

Categories : Algorithm

MongoDB and storing a DateTime field
You're using the wrong format string for that date format. A %Y is for a four digit year, %y is for a two digit year. From the fine manual: %Y - Year with century (can be negative, 4 digits at least) -0001, 0000, 1995, 2009, 14292, etc. ... %y - year % 100 (00..99) You can even see that the year isn't right in your console: => #<DateTime: 0013-12-02T13:25:21+00:00 ((1726142j,48321s,0n),+0s,2299161j)> and the dt.year value: irb(main):005:0> dt.year => 13 0013 and 2013 aren't quite the same. You want to say: self.datetime = DateTime.strptime("12/02/13 13:25:21", "%m/%d/%y %H:%M:%S") # ------------------------------------------------------------^^

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.