Is there an error in the handling of formatter objects when using Perl6's Date? If I manipulate the dates after instantiating the object, it seems as if the formatter returns to the default.
my $d = Date.new(2019, 12, 25, formatter => { sprintf "%02d/%02d in %04d", .month, .day, .year });
# Outputs 12/25 in 2019
$d.later(:1day)
# Outputs 2019-12-26
I expected the output after invoking the .later method to be "12/26 in 2019".
When looking at Date.pm6 over on GitHub -- https://github.com/rakudo/rakudo/blob/master/src/core/Date.pm6 -- I see that the .later method creates new Date objects using .new without referencing to the formatter that's set. I.e. should line 151
self.new-from-daycount(self.daycount + $multiplier * $amount )
rather be something like
self.new-from-daycount(self.daycount + $multiplier * $amount, &!formatter )
?
If so this is missing in lots of places, not only in .later, but .succ, .pred etc.
Looks like this was an oversight in the dispatch to new-from-daycount, which got fixed with: https://github.com/rakudo/rakudo/commit/ac11774d73 .
I think this should fix all issues. Please do make an issue at https://github.com/rakudo/rakudo/issues/new if not.
#elizabeth - this fixed the issue when adding days, but not other intervals. I guess the same fix has to be done on multiple locations.
This fixed the problem for iterating days, but not for months, years, etc.
> my $d = Date.new(2019,12,24, formatter => { sprintf "%04d/%02d", .year, .month };
2019/12
> $d.later(:1day);
2019/12
...but...
> $d.later(:1month);
2020-01-24
Related
I am still a beginnner in R. For a project I am trying to fit a gam model on a simple dataset with a timeset and year. I am doing it in R and I keep getting an error message that claims an argument is unused, even though I specify it in the code.
It concerns a dataset which includes a categorical variable of "Year", with only two levels. 2020 and 2022. I want to investigate if there is a peak in the hourly rate of visitors ("H1") in a nature reserve. For each observation period the average time was taken, which is the predictor variable used here ("T"). I want to use a Gam model for this, and have the smoothing applied differently for the two years.
The following is the line of code that I tried to use
`gam1 <- gam(H1~Year+s(T,by=Year),data = d)`
When I try to run this code, I get the following error message
`Error in s(T, by = Year) : unused argument (by = Year)`
I also tried simply getting rid of the "by" argument
`gam1 <- gam(H1~Year+s(T,Year),data = d)`
This allows me to run the code, but when trying to summon the output using summary(gam1), I get
Error in [<-(tmp, snames, 2, value = round(nldf, 1)) : subscript out of bounds
Since I feel like both errors are probably related to the same thing that I'm doing wrong, I decided to combine the question.
Did you load the {mgcv} package or the {gam} package? The latter doesn't have factor by smooths and as such the first error message is what I would expect if you did library("gam") and then tried to fit the model you showed.
To fit the model you showed, you should restart R and try in a clean session:
library("mgcv")
# load you data
# fit model
gam1 <- gam(H1 ~ Year + s(T, by = Year), data = d)
It could well be that you have both {gam} and {mgcv} loaded, in which case whichever you loaded last will be earlier on the function search path. As both packages have functions gam() and s(), R might just be finding the wrong versions (masking), so you might also try
gam1 <- mgcv::gam(H1 ~ Year + mgcv::s(T, by = Year), data = d)
But you would be better off only loading {mgcv} if you wan factor by smooths.
#Gavin Simpson
I did have both loaded, and I tried just using mgcv as you suggested. However, then I get the following error.
Error in names(dat) <- object$term :
'names' attribute [1] must be the same length as the vector [0]
I am assuming this is simply because it's not actually trying to use the "gam" function, but rather it attempts to name something gam1. So I would assume I actually need the package of 'gam' before I could do this.
The second line of code also doesn't work. I get the following error
Error in model.frame.default(formula = H1 ~ Year + mgcv::s(T, by = Year), :
invalid type (list) for variable 'mgcv::s(T, by = Year)'
This happens no matter the order I download the two packages in. And if I don't download 'gam', I get the error as described above.
I'm making use of the datepicker from Element Ui where the user can select a range in dates. When the user fills in the datepicker, this is what I get back: ['2018-01', '2019-02'] . So just an array with two String elements. NOT a Date() object.
When dynamically outputting this to the user, I would like to show it as: January 2018 - February 2019
I got it somewhat working in my project but the code just really sucks and also doesn't work properly either. Checkout this gif of my current project and somewhat desired result. I was wondering if someone knows a good and easy way of achieving my desired result without too much hassle. I cannot use methods like toLocaleDateString() because it isn't a Date() object. I've got my code working in a Codesandbox. If any if you guys knows a solution feel free to edit the listed Codesandbox, I would highly highly appreciate it!
In the Codesandbox I got a computed property formateDate. The basic idea of the computed property is to cut the elements of the array I get back from the datepicker before and after the - effectively giving me the first & second month and first & second year. That data I store in these variables:
let monthOne;
let monthTwo;
let yearOne;
let yearTwo;
Since I get the months back as '01' and '02' for example, I created an array of objects to transform the '01' and '02' to January and February with a for loop. I then store the result in a new variable with:
displayDate = monthOne + ' ' + yearOne + ' - ' + monthTwo + ' ' + yearTwo;
Lastly, I tried to store that result into the timeperiodDisplayString at the correct index in the experience array of objects. Anyway, I'm probably overcomplicating this way to hard so I would REALLY appreciate any help with this.
Maybe you could map over the result from the datepicker component to create an array of Date objects. So you can use toLocaleDateString()
Something like this should work:
['2018-01', '2019-02'].map((date) => {
const split = date.split('-');
return new Date(split[0], +split[1] - 1);
});
You can use parse() function from javascript.
var d = Date.parse("2019-01");
console.log(new Date(d));
My plan is to display the past 3 days of various weather stats to the user but I am unable to use the time argument properly. Here is my code:
var forecastURL = "https://api.forecast.io/forecast/API_KEY/".concat(lat,lng,new Date().toISOString().replace("Z","-72:00"));
$.ajax({
url: forecastURL,
jsonp: "callback",
dataType: "jsonp",
success: function(response) {
console.log(response);
}
});
I'm not sure I'm doing the date right but all I'm getting is a warning saying getDefaultPrevent is deprecated. Is something else at fault or is it just my date? If it's the date, what's the proper structure for manipulating ISO 8601 strings to look in the past? Preferrably 7 days if possible.
Firstly, in this use concat does not return commas between the values, so my code below uses the + "," + method rather than create another variable which is what you would need to do if you wanted to use concat.
Secondly, in ISO timestamps, ie:
2015-05-25T20:56:15.179Z
The Z means the UTC offset of the time is zero. This can be replaced by something like +1000 for times in UTC + 10 hours. If you wish to change the time value itself then the UTC offset is not the place to do it.
var d = new Date();
d.setHours(d.getHours()-72);
var forecastURL = "https://api.forecast.io/forecast/API_KEY/" + lat + "," + lng + "," + d.toISOString();
//Your existing AJAX call would go here
You could replace getHours and setHours with getDate and setDate or any of the other JS date functions.
I can't test the JSON part of your question as I don't have an API key but it looks like it should work. Find some more info about JSON in jQuery here.
I am struggling a bit trying to generate some JSON from a query I execute. All of the groovy JsonBuilder examples I've looked at only seem to deal with statically defining a dataset.
code:
def db = new Sql(datasource)
def builder = new JsonBuilder()
db.eachRow('SELECT t.day, t.start FROM mytable') { row ->
builder.days {
day(
date row.day
)
}
}
println builder.toString()
I had it at 1 point where it was printing only the last value in the resultset out.
Currently I am receiving the following error:
unexpected token: $ # line 46, column 18.
date row.day
I'm still a bit of a novice at groovy, any help greatly appreciated.
I generally prefer to present JsonBuilder with a complete object rather than use the DSL, so my solution would look something like this:
def map = [days:[]]
def db = new Sql(dataSource)
db.eachRow('SELECT t.day, t.start FROM mytable') { row ->
map.days << [day : [date: row.day]]
}
println new JsonBuilder(map).toString()
If you have a large number of results, this approach has the advantage of not forcing you to compile a huge list of GroovyRowResult objects, only a huge list of much smaller LinkedHashMap objects.
The builder there does not opening a list, add items, then close it. you would have to provide it in a single go. E.g. collect all rows as maps:
def builder = new groovy.json.JsonBuilder()
def dbresult = [1,2,3]
builder {
days dbresult.collect{
[day: [date: it]]
}
}
println builder
Use db.rows to get the list. You might have to try, what is happening, if you just send in the result. Maybe needs a cast to a Map or you have to do the mapping yourself.
If your rowcount is very high, you might be better off some other library, that don't need you to manifest the list beforehand.
How do I retrieve the locale-specific date format string in Flex / ActionScript 3? I am unable to find a method to return the actual format string (that which specifies the date format) based on the current locale. I am asking this question because I was hoping to find a way to convert a String to a Date based on the current SHORT date format for the locale. Java allows one to call:
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, locale)
to retrieve an instance of DateFormat that formats according to the SHORT format based on the locale.
Does similar functionality exist in Adobe Flex (ActionScript 3) 3? If not, is there a reliable third party library that exists for this?
I'm just found this package that do the job. Here describe the class DateTimeFormatter:
var formatter:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.LONG, DateTimeStyle.SHORT);
var result:String = formatter.format(date);
Just cool.
Extending Gojan's answer:
private function cc(event:FlexEvent):void {
var formatter:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.SHORT, DateTimeStyle.NONE);
//now if publishDate is a mx:DateField, the formatString of spark and mx components are slightly different.
//So, we replace all d with D and y with Y
publishDate.formatString=replaceAll(formatter.getDateTimePattern(), ["d", "y"], ["D", "Y"]);
}
private function replaceAll(text:String, searchArray:Array, replArray:Array):String {
for (var i:int=0; i<searchArray.length; i++) {
var s:String=searchArray[i];
var d:String=replArray[i];
text=text.split(s).join(d);
}
return text;
}
Yeah I have to say Java is better with dates - you set the locale and automatically your dates are outputted correctly! I can't seem to find such a facility in Flex.
In order to output your dates correctly for each locale I think you have to do what is written in this article: http://livedocs.adobe.com/flex/3/html/help.html?content=l10n_1.html. Maybe you should do this, and in the same class just make these strings which you've pulled from the locale file available to the rest of your app, then you'll be able to operate on them.
Otherwise perhaps this guy's library will help you? I'm not sure.
http://flexoop.com/2008/12/flex-date-utils-date-and-time-format-part-ii/