Does toLocaleTimeString in Node.js support the hour12 option? - node.js

I can't seem to get hour12 time working in node.js, however in the browser (Chrome) it's working just fine.
Node.js in terminal
var date = new Date();
var d12 = date.toLocaleTimeString('en-US', {hour12:true});
var d24 = date.toLocaleTimeString('en-US', {hour12:false});
console.log(d12) // output 13:43:38
console.log(d24) // output 13:43:38
Both yeild the same result:
13:43:38
Update
Adding fiddle to prove it works in browser
Could someone point me to the docs that explain why, or tell me what I'm doing wrong?

It's not just you. I tried running the same chunk in Node.js and couldn't get a way to print it in 12 hour format easily.
After doing some Googling, it seems like Moment.js is a popular tool for manipulating and displaying time and days. If you need to manipulate a lot of time/dates, it may be worth checking out, Moment.js.
// with Moment
var moment = require('moment');
console.log(moment().format('hh:mm'));
Otherwise,
// just one of many ways to do it in Javascript
function hour12 (hour) {
var mod = hour % 12;
if (mod < 10) {
return '0'.concat(mod);
} else {
return mod;
}
}
console.log(new Date().toLocaleTimeString().replace(/[\d]+/, hour12(date.getHours())));
EDIT I answered this question late at night, and realized I sort of missed the mark on addressing the question.
Since Node.js is based off Chrome's v8 JavaScript engine, I started poking around in the source code. I can't see a place where it takes into account arguments passed to it.
Code is here, toLocaleTimeString is line 324. In comparison, I looked around Mozilla's SpiderMonkey engine and it at a glance, it seems to account for this.

You can use toLocaleDateString and toLocaleTimeString to format times and dates. The first parameter passed to these methods is a locale value, such as "en-us". The second parameter, where present, specifies formatting options, such as the long form for the weekday.
I've used Chrome and works well.
var date = new Date(Date.UTC(2016, 3, 7, 14, 30, 0));
var options = {
weekday: "long", year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
document.write(date.toLocaleTimeString("en-US", options));
https://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx

Related

GPT-3 completions not working with API KEY

Sorry if this is a simple problem but I'm new to this stuff.
İ have my code below, but the API returns saying İ don't have the right API key put it.
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function test() {
const response = await openai.createCompletion("text-davinci-002", {
prompt: "Summarize this for a college student:\n\nJupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[20] and is on average the third-brightest natural object in the night sky after the Moon and Venus.",
temperature: 0.7,
max_tokens: 64,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
}
test()
the API key seems to be found in a process.env file that İ don't have, and when İ made a file named process.env and made a variable called OPENAI_API_KEY, but it didn't seem to work. It returns something when İ set apiKey equal to the actual key, but that seems like a roundabout solution. Thanks
process.env is not a folder, it is used to get an environment variable from the host OS. You can simply replace process.env.OPENAI_API_KEY with "your-api-key-here"
process.env is most commonly used when publishing to something like github where you need to keep your api keys secret so that nobody else can use them but so that you can still use them when deploying

AWS Lambda Timezone

I've been searching for a while and can't find a definitive answer on that or any oficial documentation from AWS.
I have a Lambda function on which I need to get the current date according to my timezone, but I'm unsure on which premisses I may rely to do that, and as this is a critical app, I can't simply rely on a single test or empirical result.
I would expect that lambda functions follow the timezone of the AWS region that they are hosted in OR a unique timezone for any GMT 0, but couldn't confirm it anywhere.
Could anyone please clarify how this works and if possible also point to any official documentation about that? Also, any special concerns related to daylight saving time?
My Lambda function is written on NodeJS and what I've been doing locally (on my machine) to retrieve the current date time is using new Date().
Lambda time using the date object will return a date in UTC unix time
TZ – The environment's time zone (UTC).
To get a time in a specific timezone you can use moment-timezone.
Using Javascript Date().now():
var moment = require("moment-timezone");
moment(Date().now()).tz("America/Los_Angeles").format("DD-MM-YYYY");
or using new Date():
var moment = require("moment-timezone");
var date = new Date();
moment(date.getTime()).tz("America/Los_Angeles").format("DD-MM-YYYY");
You can change the moment .js format to whatever you require
Regarding daylight savings time, it is possible to detect it using isDST() method.
To avoid using an external library, you can use toLocaleString() which relies on Intl.DateTimeFormat().
You can pass it a locale and an option object that supports a "timezone" and other formating parameters.
var today = new Date(); //UTC in lambda
var localeDate = today.toLocaleString('fr-FR', { timeZone: 'Europe/Paris'}); // to get the full date string
var localeHour = today.toLocaleString('fr-FR', { timeZone: 'Europe/Paris',hour: 'numeric' }); //to get just the hour
console.log(localeDate);
console.log(localeHour);
If #bbas answer didn't work for you in nodejs14.x, try this out as mentioned in :
let date = new Date(); // UTC in lambda.
let dateString = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Kolkata', year: 'numeric', month: '2-digit', day: '2-digit'}).format(date);
console.log(dateString); // prints out date in mm/dd/yyyy in 'Asia/Kolkata' timezone

Hiding _all_ remote methods in loopback model

I'm using loopback 3.
I have this lines of codes in my model's js (survey.js):
let enabledRemoteMethods = []
Survey.sharedClass.methods().forEach(function(method) {
console.log(method.name, method.isStatic)
let matchingEnabledRemoteMethod = _.find(enabledRemoteMethods, {name: method.name});
if (!matchingEnabledRemoteMethod) {
Survey.disableRemoteMethodByName(method.name, method.isStatic);
}
});
It works.... almost. I could still see in the explorer the REST endpoint for "PATCH /surveys/{id}". My expectation is: there shouldn't be any REST endpoints listed in the explorer.
Then I examined the URL corresponding to that operation, it is:
http://localhost:3000/explorer/#!/Survey/Survey_prototype_patchAttributes
Which, according to the documentation, means that patchAttributes is a static method.
Then I cross checked with the output in the console... there it says: pathAttributes is not static.
Incosistency!
I even have tried adding this line:
Survey.disableRemoteMethodByName("patchAttributes", true);
Also
Survey.disableRemoteMethodByName("patchAttributes", false);
No luck.
Can someone confirm if it's a bug in loopback 3 (I don't know about loopback 2, haven't checked)? If it's a bug I wouldn't have to spend time on it and just wait until it gets fixed. But if it's not a bug, can someone point out what's missing in my code?
Thanks!
UPDATE: figured out how
With this line I'm able to get rid of it:
Survey.disableRemoteMethodByName("prototype.patchAttributes", true);
The second parameter doesn't seem to matter (you can put false as well). Not sure why though (I suppose it should've accepted true only).
This is my current solution:
let disabledPrototypesRemoteMethods = ['patchAttributes']
let enabledRemoteMethods = [
"create", "findById", "replaceById", "deleteById",
"replaceOrCreateQuestion"
]
Survey.sharedClass.methods().forEach(function(method) {
if (enabledRemoteMethods.indexOf(method.name) == -1) {
Survey.disableRemoteMethodByName(method.name);
}
if (disabledPrototypesRemoteMethods.indexOf(method.name) > -1) {
Survey.disableRemoteMethodByName("prototype." + method.name);
}
});
Still, one small detail: this thing still shows up (I suppose it provides the POST alternative for the normal PUT for the replaceById operation..., but I don't want it; I want to force user of my API to go with the PUT only):
http://localhost:3000/explorer/#!/Survey/Survey_replaceById_post_surveys_id_replace
I tried adding this line:
Survey.disableRemoteMethodByName("replaceById_post_surveys_id_replace");
No luck.
Anyway... hope this useful for others; loopback doc is kind of sketchy.
You can get the prototype methods as well by looking at the stringName property. That way you can include the prototypes in your list.
The stringName includes the sharedClass name in the value, so you will need to parse that out.
module.exports = BusinessProfileContacted => {
const enabledRemoteMethods = ["create", "findById", "replaceById", "deleteById", "replaceOrCreateQuestion", "prototype.replaceAttributes"];
Survey.sharedClass.methods().forEach(method => {
const methodName = method.stringName.replace(/.*?(?=\.)/, '').substr(1);
if (enabledRemoteMethods.indexOf(methodName) === -1) {
Survey.disableRemoteMethodByName(methodName);
}
});
};

Setting a model attribute to a value based on, but not equal to, the input in angular-formly

I'm trying to figure out how to parse a form entry to set the model attribute to something else; e.g., extracting the video ID of a youtube video from a URL input. Is there a way to use parsers/formatters (6.21 features?) to accomplish this easily? I hoped to find a good example for this, and maybe there is one somewhere, but perhaps this would make a good one if there's not.
Here is a working example of what I'm attempting to accomplish, but in multiple steps and without the use of parsers. Any help adapting the code to set model.videoID from a URL in a single step (or fewer than 3 steps, at least) would be very appreciated. Thank you for your help with this and my other past questions. :)
Wow, this was much easier than I expected to implement. Here is the modification of the JS Bin which uses parsers, recently added with angular-formly#6.21.0, to extract the video ID from a YouTube URL in one function. It also, conveniently, validates itself!
Here is the relevant code, to summarize:
{
key: 'vidid',
type: 'input',
parsers: [extractID],
templateOptions: {
label: 'YouTube Video',
placeholder: 'Insert video URL here'
},
...
function extractID(value) {
if (value != undefined || value != '') {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
var match = value.match(regExp);
if (match && match[2].length == 11) {
return match[2];
}
}
};

Display a formatted timestamp in template

How do i format a timestamp inside the template? I followed a tutorial on building a chat and it works. Now i expanded the chat with some features like deleting the message and putting the time in front of the message. But when i write {{timestamp}} inside the template a UNIX timestamp is being given. How do i format it to show time like '6:12'. The timestamp is being stored in a Messages collection.
Is the right place to manipulate the timestamp inside of the
Template.Messages.created = function ( ) { ... }
function?
Thanks in advance.
Although not essential in this case, I would recommend using Moment.js, it makes working with dates and times in Javascript a breeze.
You can install the package from Atmosphere or download the script into your client dir then use a helper similar to the one below:-
Template.Messages.helpers({
created: function() {
var time = moment(this.timestamp);
return time.format('h:mm a');
}
});
NB: I've assumed timestamp is a var on the context object.
I use this library. It gives you all the date formatting you will ever need. With meteor just drop it in and you can use it in any helper to return the formatted date.
http://stevenlevithan.com/assets/misc/date.format.js
If you want to avoid libraries and manipulate with Javascript Date object I would suggest (this assumes that date is in ISO format 2010-06-15T00:00:00, wich you can get from Date.toISOString()):
Implement format method (thanks JavaScript equivalent to printf/string.format), put it in i.e. lib/utils.js:
String.prototype.format = function(args, index) {
return this.replace(/{(\w+)}/g, function(match, number) {
return typeof args[index[number]] != 'undefined'
? args[index[number]]
: match
;
});
};
Create helper (put it into client/client.js)
Handlebars.registerHelper('formatDate',function(input, pattern){
var iso = /^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?$/;
if(this[input]) {
var parts = this[input].match(iso);
return pattern.format(parts, {yyyy:1,MM:4,dd:5,hh:6,mm:7,ss:8,SSS:9});
}
return this[input];
});
Use the helper:
{{#each logs}}
<tr>
<td>{{formatDate 'ts' '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}'}}</td>
Have a look at this package swag which offers lots of useful handlebars helpers.
Checkout its date/time helpers: https://github.com/elving/swag#dates
You can format date/time as easily like:
var date = new Date()
{{formatDate date "%m/%d/%Y"}}
{{formatDate date "%I:%M%p"}}
{{formatDate date "%F"}}
{{formatDate date "%Y%m%dT%H%M%S%z"}}
07/26/2015
11:38PM
2015-08-28
20150828T233805-0004
Have a look at Template helpers and the JavaScript Date object.

Resources