I am in charge of a website, and I have set up a "Quote of the Day" which currently is quite simplistic. See Here (on the right of the page)
What it currently does is it gets the Day of the month and the month, and normalises to one, then multiplies by the number of quotes (stored in an xml file) and rounds down. While this method will give me the same quote whichever machine I am on (something a random number generator could never do) it has been pointed out to me that this method is flawed. If you consider January the first couple quotes are going to be the same, 1*1/360, 2*1/360, 3*1/360, thus the quote isn't unique.
Can anyone think of a better way to select a quote of the day?
Fun question. Instead of relying on days of the month, why not count days since a given date? JS provides a pretty good property for that: getTime(), which gives you the number of milliseconds since 12am UTC on Jan. 1 1970, which you can convert to days with some simple division.
The only thing that complicates it is that if you expect your quotes to shift at midnight (and who doesn't?), you have to take into account the timezone. Again, JS provides that with getTimezoneOffset(), which gives the number of minutes ahead or behind the user's locale is compared to UTC. If you want ALL users to flip at the same time, regardless of where they live, just set this to a static value.
Your code could look something like this:
var intQuoteCount = 51; // The number of quotes in your library
var dtNow = new Date();
var intTZOffset = dtNow.getTimezoneOffset() * 60000; // automatically adjust for user timezone
var intNow = dtNow.getTime() - intTZOffset;
var intDay = Math.floor(intNow / 86400000); // The number of 'local' days since Jan 1, 1970
var intQuoteToDisplay = intDay % intQuoteCount;
True, determinism is something "a random number generator could never do". Fortunately (for this case, at least), programming languages provide pseudo-random number generators, not the real thing. The pseudo-random numbers are generated by doing a bunch of calculations on a "seed" value.
To get a repeatable "random" selection, then, all you need to do is set the seed in a way which is consistent for each day - I would suggest using the date, in "yyyymmdd" format, as the seed, but any other number which will be unchanged over the course of a day will work just as well.
Once you have your seed, tell the PRNG to use it with the command srand(mySeed); and you'll get the same sequence of "random" numbers from rand() every time (until mySeed changes).
If you want to show the quotes in order, you could get the current Julian Day number, which will increase by one each day, and take the reminder after dividing it by the number of quotes as the number of today's quote. If you want to show all quotes but the order of them to change each cycle, you can xor the quote number and rearrange the bits using some logic that you get from the quotient of the division.
You could try rounding up on an even day and rounding down on an odd day. But I'm am sure there is better ways, this is just quick suggestion.
Also you could try using the current day of the year in the calculation as this is unique for each new day in the year as opposed to repeating each month.
Do you have to limit yourself to having a cycle of 360 days? If you have for example 500 quotes. some might never be used.
How about- Every day pick a random number between 1 and #OfQoutes, use it as the quote of day index, and mark it as "used in current cycle".
Next time when you pick a number, if you pick a quote that is marked as "used in current cycle" re-pick until you get a number of quote which isn't marked so. When all quotes are marked, un-mark all of them.
This will ensure you're going through all quotes in each cycle, together with randomness, and it will obviously work for any number of quotes.
<body onLoad="thoughts_authors()">
<script>
function thoughts_authors()
{
var authors=new Array()
authors[0] = "Charles Schulz";
authors[1] = "Jack Wagner";
authors[2] = "Mark Twain";
authors[3] = "Oscar Wilde";
authors[4] = "David Letterman";
authors[5] = "Lily Tomlin";
var thoughts=new Array()
thoughts[0] = "Good Day Is Today";
thoughts[1] = "Style Is What You Choose";
thoughts[2] = "Be The Best Version Of You.";
thoughts[3] = "Truth Along Triumphs.";
thoughts[4] = "How can Life Be Devastating When YOU Are Present in It.";
thoughts[5] = "Believe In What You Say";
index = Math.floor(Math.random() * thoughts.length);
alert(thoughts[index]+ "-" + authors[index]);
}
</script>
THIS WILL GENERATE RANDOM QUOTES ALONG WITH RANDOM AUTHORS
Related
I am looking for ways to convert a Duration (#sys.duration) system entity from Dialogflow in JavaScript code from minutes to seconds.
I ask the user for a certain duration, where the user can answer, e.g.:
20 minutes
5 minutes
etc.
that input is saved into a variable the_duration. Now to do certain calculations, I need to convert this into seconds. How can I achieve this?
EDIT: Perhaps it would help if I need to extract the number from the string? I've tried looking for this way, but provided examples don't really apply for this specific case with minutes.
The #sys.duration system entity will send you an Object with two attributes, "amount" which contains an integer, and "unit" which contains a string.
So in Javascript, this would be represented something like:
{
"amount": 20,
"unit": "min"
}
To convert this to seconds, you would lookup how many seconds are in the "unit" provided and multiply it by the amount.
A good way to do this lookup would be to create an object that has, as attributes, the possible unit names and as values the number of seconds. This works well for most units up to a week. When you hit a month or a year (or longer), however, you run into trouble since the number of seconds for these periods can be variable. To represent these, I'll mark these as a negative number, so you can check if the conversion failed. (I'm ignoring issues with clock changes such as due to Daylight Saving Time / Summer Time.)
I haven't fully tested this code, but it appears to be correct. This function lets you pass the object sent in the the_duration parameter and will return the number of seconds:
function durationToSeconds( duration ){
const mult = {
"s": 1,
"min": 60,
"h": 60*60,
"day": 60*60*24,
"wk": 60*60*24*7,
"mo": -1,
"yr": -1,
"decade": -1
};
return duration.amount * mult[duration.unit];
}
Extracting the number from the string is certainly possible, and you can adapt this function to work that way, but since Dialogflow already gives it to you as an object with normalized strings, it would be significantly more difficult.
I'm pretty new to javascript and I need to get a portion (slice) of a sorted array (Numbers, timestamps basically) by start_value and end_value.
For example, let's say I have an array of random timestamps from last month, and I want to get all timestamps between two weeks ago and a week ago.
This is a pretty simple algorithm to write (using a binary search) but I don't want to mess up my code with these computations.
I've been searching for a way to do this in javascript but haven't found any.
Thanks for any future help :)
Perhaps use filter?
var dates = [123, 234, 456, 468, 568, 678];
var min = 300;
var max = 500;
var inRange = dates.filter(function(date) {
return min < date && date < max;
});
console.log(inRange);
On the plus side, this doesn't even need them to be sorted. On the down side, it probably won't be as fast as a well-implemented binary search for the relevant start and end points. Unless you've got some really harsh performance requirements I don't think that'll matter.
Ok, I found a pure js library called binarysearch that has exactly what I'm looking for: https://www.npmjs.com/package/binarysearch. It has rangeValue function which accepts non-existing numbers as start-end. Seems to be working :)
I have a strange timezone/date formatting issue that recently came up with some new code, and what makes it more strange is that it only affects two months - August and September.
The code takes a date string with UTC time formatted like this:
10-06-2017 09:29:15
And converts it to a new string with the same format but with local time. The zeroPad function ensures that the format remains the same.
We implemented it in March and everything worked fine. It's within Classic ASP on IIS9/Server 2012.
As soon as we got to August, it broke. 08-10-2017 09:33:06 becomes 12-09-2016 20:33:06.
Can anyone see what I've done wrong?
function jsConvert(dateString) {
var patterns = dateString.split(/[\-\s:]/g);
var date = new Date(parseInt(patterns[2]),
parseInt(patterns[0]) - 1,
parseInt(patterns[1]),
parseInt(patterns[3]),
parseInt(patterns[4]),
parseInt(patterns[5]));
date.setTime(date.getTime() - getTimezoneOffset() * 60 * 1000);
var result = zeroPad(date.getMonth() + 1);
result += '-' + zeroPad(date.getDate());
result += '-' + date.getFullYear();
result += ' ' + zeroPad(date.getHours());
result += ':' + zeroPad(date.getMinutes());
result += ':' + zeroPad(date.getSeconds());
return result;
}
function zeroPad(number) {
return (number < 10) ? '0' + number : number;
}
What are the units of time in your getTimezoneOffset() function?
Your code is written as though the getTimezoneOffset() function returns a number of minutes, since you are multiplying by 60 and then 1000, to get millseconds.
But if your getTimezoneOffset is returning seconds, you will be over-doing the multiplication and therefore jumping back too far in time.
I think it would have to be milliseconds, to jump back the distance you are getting. #CBroe above mentions that perhaps you mean the builtin getTimezoneOffset function, which is indeed in minutes. Perhaps you have a separate getTimezoneOffset function defined in your code elsewhere, that returns an answer in milliseconds? In which case CBroe's answer fixes it.
My next suggestion would be to add lines of debugging code
For example, could you add the following?
At the beginning, add console.log("A",dateString).
After var patterns = dateString.split(/[\-\s:]/g); add a line console.log("B",patterns);.
After var date = ...(patterns[5])); add a line console.log("C",date);.
After date.setTime...1000); add a line console.log("D",date); console.log("E",getTimezoneOffset());.
If you show us the output of these lines, we should be able to pinpoint the problem easily. I have included item E because I am just wondering if there is yet another getTimezoneOffset() function in your system, which we are not aware of, or something. Seeing its value will help reassure everyone.
Meanwhile can you confirm the time zone you are running the code in? I am guessing it is in the USA rather than Europe, from your preference for putting month before the day?
So as it turns out this is a known, albeit obscure issue. It has to do with the fact that parseInt assumes that numbers with leading zeros are NOT base 10, but instead radix. It's well documented here: Javascript parseInt() with leading zeros
Once I made the change to:
parseInt(patterns[2]**, 10**);
All was good.
Thanks for the input.
Working through their MapReduce tutorial, and Basho posits a MR challenge here, given daily stock data for the GOOG ticker:
Find the largest day for each month in terms of dollars traded, and
subsequently the largest overall day. Hint: You will need at least
one each of map and reduce phases.
Each day in the goog bucket has a key that corresponds to its data and corresponding data that looks like this:
"2010-04-21":{
Date: "2010-04-21",
Open: "556.46",
High: "560.25",
Low: "552.16",
Close: "554.30",
Volume: "2391500",
Adj Close: "554.30"
}
Due to my relative lack of familiarity with the MR paradigm (and, candidly, Javascript), I wanted to work through how to do this. I assume that most of the work here would actually get done in the reduce function, and that you'd want a map function that looks something like:
function(value, keyData, arg){
var data = Riak.mapValuesJson(value)[0];
var obj = {};
obj[data.Date] = Math.abs(data.Open - data.Close);
return [ obj ];
}
which would give you a list, by day, if not of dollars traded per day, at least the change in the stock price by day.
The question I would then have would be how to structure a reduce function that is able to parse through by month, select for only the largest value per month, and then sort everything from largest month to smallest.
Am I shortchanging the work that I need to do in my map function here, or is this roughly the right idea?
I originally authored that challenge! Unless you'd like me to just give you the answer, I'll give you this hint: the key here is to think in terms of aggregate functions. How do you need to group the entries to find the maximum for each month, and then the maximum across the entire dataset?
Also, from the given data you can't know the exact amount of money exchanged in the day, but you could make a guess by multiplying the average price by the volume of shares traded.
I wonder if I can simplify and use less lines of code for this purpose:
I have a class called "worker", and that class has a method that reads the properties (name, age, etc...) from a series of simple arrays.
Until there, everything is fine. Now, one of the properties that I want to add is a boolean value that makes reference to which months of the year the worker is active. For the moment, I have solved it like this:
var months_worker_1 = [{"jan":true},{"feb":true},{"mar":true},{"apr":false}] //and so on
And then, my property reads months_worker_1, but I have one array like that for each worker. I wonder if there is a way to do this that requires less lines of code, like for example, create a "master" array with all the months of the year, and in the array for each worker, specify just the months they are working. Those months become "true", and the rest of months become "false" automatically without specifying so... I have been scratching my head for some time, and for the moment only my current system is working fine, but I am guessing that there must be a simpler way...
Thanks very much!
Edit: I clarify, there is no "big picture". I am just doing some exercises trying to learn javascript and this one woke my interest, because the solution I thought seems too complicated (repeating same array many times). There is no specific goal I need to achieve, I am just learning ways to do this.
A really nice trick that I use sometimes is to use a binary number to keep track of a fixed amount of flags, and convert it to a decimal for easier storage / URL embedding / etc. Let's assume Mark, a user, is active all months of the year. Considering a binary number, in which 1 means "active" and 0 inactive, Mark's flag would be:
111111111111 (twelve months)
if Mark would only be active during january, february and december, his flag value would be:
11000000001
Checking if Mark is active during a specific months is as simple as checking if the character that corresponds to that month's index in Mark's flag is 1 or 0.
This technique has helped me in the past to send values for a large number of flags via URLs, while also keeping the URL reasonably short. Of course, you probably don't need this, but it's a nice thing to know:
Converting from binary to decimal is easy in JS:
parseInt(11000000001, 2).toString(10); // returns 1537
And the reverse:
parseInt((1537).toString(2)); // returns 11000000001
Edit
You could just as easily use an array made out of the month numbers:
var months_worker_1 = [1, 2, 3]; // this would mean that the user is active during january, february and march