Hello I am new to programming and came across a task abour google search api. I went through the docs and wonder what does the code below will do? below will do.
const myWebSearchStartingCallback = (gname, query) => {
const hour = new Date().getHours();
return query + (hour < 12 ? ' morning' : ' afternoon');
};
window.myImageSearchStartingCallbackName = myWebSearchStartingCallback;
Many thanks.
From the docs:
The example search starting callback in Example Search Starting Callback adds either morning or afternoon to the query depending on the time of day.
A callback is a function that gets called at a later point in time, for example when the user of the website takes some action. In this case, the callback gets called when the user enters a search query, and this callback modifies the search query to add either "morning" or "afternoon" to the end of that search depending on the user's current time.
Related
I want to display the last 10 messages of a conversation. Then as the conversation progresses, obviously, I need to show those messages as well:
I am doing something like this:
//function a
db.collection("conversations/" + messageID + "/messages").orderBy("timestamp", "desc").limit(10).
get().then(function(querySnapshot) {
const time = Date.now();
//call function b and pass time as a parameter
//function b
db.collection("conversations/" + messageID + "/messages").where("timestamp", ">=", time)
What security rules will allow me ensure that time in function b is somewhat close to the current time?
Thanks!
You can use request.time for when the specific document was created, which is type of Timestamp, as stated in the Rules documentation.
I found this StackOverflow post which might help as well.
I'm building an app that allows the user to reset his password.
The process is really simple .The user enters his email address and I sending him a link with the number of the new objectid that was created.
For exemple -> /reset-password?x=55555444475d41a000001.
After clicking the link he reaches other page and then I want to check if 24 hours have passed from the time he got the link?and yes i know there is function called "getTimestamp" but how to use it..?
get: function (request, response) {
???????
},
You can set a "creation_date" property in your object when you create it, like this:
obj = {
id: "xxxxxx...",
creation_date: new Date()
...
}
Then you store the object somewhere in your server, and then when the user opens the link with the id of the object you will do something like this to check if the object has been created more than 24hours ago:
var now = new Date();
if (now - obj.creation_date > 86400000) {
// more than 24h (86400000ms = 24h)
// do something
}
Actually reading the JavaScript API docs for ObjectId might help.
Checking wether 24 hours have passed since the creation of the object should be as easy as
var now = new Date();
/* Subtract the milliseconds a day lasts from the current time.
* If the timestamp of the ID converted to msecs after epoch is smaller
* the ObjectId was created before that.
*/
if ( myId.getTimestamp() < ( now.getTime() - 86400000 ) {
console.log("24 h have passed since creation");
}
else {
console.log("24 h haven't passed since creation");
var passed = new Date( now - myId.getTimestamp() );
console.log(passed.getUTCHours()+":"+passed.getUTCMinutes()+" have passed.");
}
Note: I downvoted your question as it would have been easily solvable by googling "MongoDB ObjectId getTimestamp JavaScript api", you didn't show any sign of working on the problem yourself and didn't bother to ask a specific question. May I politely suggest reading ESR's How To Ask Questions The Smart Way, especially the chapter about StackOverflow?
I have a couple questions about javascript:
Does javascript have the capability to identify a filename with a timestamp as a name?
Similar to the Perl code below utilizing the POSIX module?
my $filepath = sprintf("/path/to/file%s.JSON",strftime("%y%m%d",localtime));
this is just an example. I would like to find file in format yy/mm/dd/hh/min
For example say I want to find a file with the name 12_11_03_15:15.json how can I do this with javascript.
Say I create a function that I want to trigger every 15 minutes to read the file how is this possible with javascript? I looked at setInterval() but that won't work because it is dependent on when the browser is launched. Is it possible to schedule a function to execute every hh:00, hh:15, hh:30, hh:45?
Thank you very much in advance.
You can use the Date class to get information about the current time.
To schedule a function to run at a certain time, setInterval() is indeed the best choice. It seems like what you're really looking for is a way to find out when to start the first interval such that it will fall on a quarter-hour. For that, you should again use Date to get the current time and subtract it from the next quarter-hour; you can use the resulting value with setTimeout to time the start of the first interval.
Here's an example: http://jsfiddle.net/GSF6C/3/
var nextQuarterHour = new Date();
nextQuarterHour.setMilliseconds(0);
nextQuarterHour.setSeconds(0);
do {
nextQuarterHour.setMinutes(nextQuarterHour.getMinutes() + 1);
} while (nextQuarterHour.getMinutes() % 15)
var millisecondsToNextQuarterHour = nextQuarterHour.getTime() - Date.now();
document.write(millisecondsToNextQuarterHour);
setTimeout(function () {
alert("Ding!");
setInterval(function () { alert("Dong!"); }, 15 * 60 * 1000);
}, millisecondsToNextQuarterHour);
I am building a real-time system which (with a use of websockets) updates a table with live data of different frequencies (can be 3 times per second, can be once every 2 seconds - dependant on the type of data).
I am currently struggling to find a way of letting the user know when a particular field has not been updated in the last 5 seconds. That is, if no new data is fetched, I shouldn't keep the old value there, but rather change it to '--' or something similar.
After a long way to the javascript, final function which updates fields looks like that (extremely simplified):
function changeValue(data){
var fieldId= data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
}
This function gets called each time a field needs to be changed. I've got between 2 and 40 different fields (dependant on the user) that are changed.
What is the best way of setting timers in order to change the values of the fields to '--' every 5 seconds, if no update has been made?
I would be really grateful for some tips,
Thanks,
Karol.
Since you want to indicate timeout on a per-field basis, you have two obvious options:
Have a global interval timer that ticks over fairly frequently and looks through all of your fields for a timeout.
Have independent timers for each field which just deal with that field.
I think on balance I prefer (1) to (2), because we're only dealing with one interval timer then and it makes the housekeeping simpler.
Since IDs in documents must be unique, we can use your field ID values as a key in a hash (an object) to store last updated times. This is kind of a spin on the previous answer but works on a per-field basis. So here's how we'd set those last updated times:
var lastUpdatedTimes = {};
function changeValue(data){
var fieldId= data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
lastUpdatedTimes[fieldId] = new Date().getTime();
}
Then you set up an interval timer to check each of them.
function checkFieldsForTimeout(){
var now = new Date.getTime();
// For each ID in lastUpdatedTimes, see if 'now minus
// last updated' is > 5000 and is so, set the field
// text to '--' and remove that entry from the last
// updated list with "delete lastUpdatedTimes[itemId]".
}
Should a timed-out field spring back to life, the "--" will be replaced by some real text again.
By deleting the last updated time from "lastUpdatedTimes" whenever we put "--" into a field, we make sure that the interval timer isn't wasting time processing fields that have already been timed out.
This answer was extended to handling multiple fields after the comment by #Andrew (please see also his answer).
Introduce a property updatedTime, which holds the last time the data was updated, in each data. A periodic timer checks updatedTime for all data and updates the text field if appropriate. The check has to be twice as often as the detection period. Your function changeValue() updates updatedTime and the text field.
function checkData() {
var now = new Date.getTime();
for "each data" {
if (now - data.updatedTime >= 5000) {
var fieldId = data.fieldId;
$('span#'+fieldId).text('--');
}
}
}
function changeValue(data) {
var fieldId = data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
data.updatedTime = new Date.getTime();
}
// Install periodic timer to check last updates:
setInterval(checkData, 5000 / 2); // interval = half the required detection period
We have followed Tom Anthony's tutorial to calculate a geocode from a UK postcode to plot a marker on a Google Map. This has worked fine, but now we wish to add a popup when you click on a location. So we updated our function to place a marker and original usePointFromPostcode code to take in a description:
function usePointFromPostcode(postcode, description, callbackFunction) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0]) {
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point, description);
}else{
alert("Postcode not found!");
}
});
localSearch.execute(postcode + ", UK");
}
// loop through the array of postcodes to output markers
for(var i=0; i<postcodes; i++) {
usePointFromPostcode(postcodes[i], descriptions[i], placeMarkerAtPoint);
}
However, whilst the page loads without error, the markers all have the same description - that of the last item in the array. I believe this is due to a closure, or rather a lack of one, but am unable to hack out the solution. How can we get the descriptions in sync with the points?
If localsearch.execute initiates a search but returns before the search is complete, then that would explain the behaviour. Two possible solutions. Create a separate GlocalSearch object for each query or delay issuing the second query until the first is complete, etc.
I don't know enough about the GlocalSearch class to say if the former is sensible. If it is, you presumably will have several searches running in parallel that may finish in arbitrary order.
To do the later: Alter your callback to set a global flag done to true. Before initiating the first search, set done to false. After initiating the first search, set a timeout. The code executed by the timeout does the following: if done is now true, it sets done to false and initiates the second search. Otherwise, it simply repeats the same timeout. And of course this sort of thing repeats until all searches are complete, at which point the time out code initiates whatever you want to do after that loop. See http://www.ehow.com/how_4847411_simulate-whilesleep-loop-javascript.html for a short article that may be helpful.