Scraping Calendar data problem with next day date - date

Good morning, I have a problem that I do not know how to solve, through web-scraping I take data from the website where I work and create a ics calendar file with my shifts, it works almost always well, only when I have a shift that ends at midnight or later I get an error, this is because in the page I find only the start date and not the end date, so if I finish at 00.00 the correct date should be the next day, but it is added the same as the beginning so I get an error, do you have any idea how to correct this error?
"python nameerror free variable referenced before assignment in enclosing scope"
# CLEANING DATETIME DATUM
datclnd = soup_datum.replace('.', ' ')
dated = tempo.datetime.strptime(datclnd, "%d %m %Y")
yearclnd = dated.year
monthclnd = dated.month
dayclnd = dated.day
# CLEANING DATETIME DATUM
# CLEANING DATETIME HOUR AND MINUTES
time_split = soup_dienstbegin.split(":")
dienstBH = int(time_split[0])
dienstBM = int(time_split[1])
#dienstende
time_split2 = soup_dienstende.split(":")
dienstEH = int(time_split2[0])
try:
dienstEM = int(time_split2[1])
except:
NOTHING
def ics_working():
event = Event()
event['uid'] = f'19970610T172345Z-AF23B2#{dayclnd}{monthclnd}{yearclnd}'
event.add('summary', f'{string1}{tagesinfo2} {soup_kommentar2} {kursinfo}')
event.add('description', f'{schiffinfo}Schichtdauer: {soup_schichtdauer}, Bezahlte Zeit: {soup_bezahltezeit}\n, Infos: {schiffinfo}')
event.add('dtstart', datetime(yearclnd,monthclnd,dayclnd,dienstBH,dienstBM,0))
event.add('dtend', datetime(yearclnd,monthclnd,dayclnd,dienstEH,dienstEM,0))
event.add('dtstamp', datetime(yearclnd,monthclnd,dayclnd,dienstBH,dienstBM,0))
organizer = vCalAddress(f'MAILTO:{receiver_email}')
organizer.params['cn'] = vText(f'{username} Monatsplan')
organizer.params['role'] = vText(f'{username} Monatsplan')
event['organizer'] = organizer
event['location'] = vText('Werftestrasse 5, 6002 Luzern')
# Adding events to calendar
cal.add_component(event)
# Printing working day info
print(f'Datum: {soup_datum} Dienst: {string1}{tagesinfo2} --> Mannschaft: {crew_list2} --> OK')
ics_working()

Related

Get Every Tuesday of the month with Coldfusion

I'm currently working with jquery FullCalendar plugin to create a specific calendar.
One of my tasks I have to work out is how to get any given specific day for the month.
I'm currently using Coldfusion 10 for the server side so I'm wondering is there any specific way of getting every instance of a Tuesday into an array of dates?
Ideally I would like to do this on the server side and populate the calendar plugin.
My issue is primarily trying to source every specific day of a calendar month.
Any advice greatly appreciated.
The firstXDayOfMonth() UDF on CFLlib allows you to find the first of a given day-of-week in a given month. From there you just need to loop from that date adding 7 each iteration until the month is no long the selected month.
theMonth = month(now());
startDate = firstXDayOfMonth(3, theMonth, year(now()));
tuesdays = [];
for (date=startDate; month(date) == theMonth; date +=7){
arrayAppend(tuesdays, dateAdd("s",0, date)); // this just converts date from a number back to a date
}
writeDump(tuesdays);
Update:
Actually the approach for that UDF on CFLib is terrible. Use this variation instead:
function firstXDayOfMonth(dayOfWeek,month,year){
var firstOfMonth = createDate(year, month,1);
var dowOfFirst = dayOfWeek(firstOfMonth);
var daysToAdd = (7 - (dowOfFirst - dayOfWeek)) MOD 7;
var dow = dateAdd("d", daysToAdd, firstOfMonth);
return dow;
}
I'll update the UDF on cflib a bit later: I need to write some decent unit tests for it first, and am a bit busy # the moment.
The Short Version:
At this time, there is not a function in CF that gets all the Tuesdays. But here's an easy way to do it:
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1
var dayOfWeekArray = []; // This is the outcome.
// loop through each day of the month adding the target days to the array.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, loopingDate );
}
}
dayOfWeekArray is an array of every Tuesday of a month.
More Detail:
Your title and post seem to conflict as far as what you're looking for, so I'm going to stick with the title, since that's why I came here...
Here's what you can do to find all the Tuesdays in a month:
Create a date Object
Loop through the days in the target month using the date Object
If the current day is Tuesday, add it to an array
Boom, you got all the Tuesdays of a month in an array
Here's the code I used (cfscript):
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var dayOfWeekArray = [];
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1. Do a quick writeDump in the loop if you're not sure.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, datePart( "d", loopingDate );
// ArrayAppend( dayOfWeekArray, loopingDate ); - use this if you'd rather have the whole date object
}
}
This gives you dayOfWeekArray which will be the date of each Tuesday of a particular month. For instance, this month (Jan 2019) will be [1, 8, 15, 22, 29]. You can change this to be the entire date object if you want - that's what I did in the short version at the top.

Calabash: Select a date from a UIDatePickerview

In Calabash Automation testing on iPhone. I need to select a date from a date picker. Please guide me with a ruby step definition.
I want something like
Then I scroll datepicker to date "2002-10-22"
I made a solution after some research. This code is not bulletproof but it works fine for me. I guess someone will get a help from this. if anyone knows how to improve this. please add it here.
In step definitions I add..
Then /^I scroll datepicker to date "1985-01-01"
# Date Format "1985-01-01"
# make sure date picker is up
should_see_date_picker()
is_picker_in_date_mode()
maxdate = picker_maximum_date_time()
target = Date.parse(target_date)
current = Date.parse(datequery())
if(maxdate<target)
screenshot_and_raise "Target date'#{target}' is larger than maximum date'#{maxdate}' in date picker"
end
limit = 100
# => set year
count = 0
dir = (target.year < current.year) ? "down" : "up"
until (target.year == Date.parse(datequery()).year) or (count==limit) do
date = Date.parse(datequery())
scroll_date_component(dir, 2, date.year)
# puts("Inside the loop1 '#{count}'=> '#{date.year}'" )
count += 1
end
# => set month
count = 0
dir = (target.month < current.month) ? "down" : "up"
until (target.month == Date.parse(datequery()).month) or (count==limit) do
date = Date.parse(datequery())
scroll_date_component(dir, 0, date.month)
# puts("Inside the loop2 '#{count}'=> '#{date.month}'" )
count += 1
end
# => set day
count = 0
dir = (target.day < current.day) ? "down" : "up"
until (target.day == Date.parse(datequery()).day) or (count==limit) do
date = Date.parse(datequery())
scroll_date_component(dir, 1, date.day)
# puts("Inside the loop3 '#{count}'=> '#{date.day}'" )
count += 1
end
end
#########################################################
# => ##### Date picker helper methods. #####
def scroll_date_component(direction, column, component)
if(column==0)
# => Month scroll needs the month name string
if (direction.eql? "up")
month_str = Date::MONTHNAMES[component+1]
touch("pickerView scrollView index:#{column} label text:'#{month_str}'")
elsif (direction.eql? "down")
month_str = Date::MONTHNAMES[component-1]
touch("pickerView scrollView index:#{column} label text:'#{month_str}'")
end
else
# => Day and year scrolls are numeric
if (direction.eql? "up")
touch("pickerView scrollView index:#{column} label text:'#{component + 1}'")
elsif (direction.eql? "down")
touch("pickerView scrollView index:#{column} label text:'#{component - 1}'")
end
end
sleep(0.3)
end
def datequery()
return query("datePicker","date").first
end
def should_see_date_picker ()
if query("datePicker", :date).empty?
screenshot_and_raise "Could not find date picker"
end
end
def is_picker_in_date_mode()
res = query("datePicker", :datePickerMode)
screenshot_and_raise "expected to see a date picker" if res.empty?
screenshot_and_raise "expected to see UIDatePickerModeDate" if res.first!=1
end
def picker_maximum_date_time()
res = query("datePicker", :maximumDate)
screenshot_and_raise "expected to see a date picker" if res.empty?
return DateTime.parse(res.first) if (res.first)
end
That gist mentioned by Chathura is very out of date.
Calabash iOS now supports interaction with most date pickers natively.
https://github.com/calabash/calabash-ios/blob/develop/calabash-cucumber/features/step_definitions/calabash_steps.rb#L406
Scenario: I should be able to use the predefined steps to change the picker time
Then I change the date picker time to "10:45"
Scenario: I should be able to use the predefined steps to change the picker date
Then I change the date picker date to "July 28 2009"
Scenario: I should be able to use the predefined steps to change the picker date and time
Then I change the date picker date to "July 28" at "15:23"

Working with Dates in Google Apps Script

What I am trying to do here is this - I want to give index to only the workdays in each week.
So, if in a week, Monday and Wednesday are holidays, then Tuesday should get 1, Thursday should get 2, Friday should get the index 3. Otherwise, in a normal week without any holidays, Monday should get 1, Tuesday 2, Wednesday 3, and so on ...
Here is the code I have written (I haven't coded in years now, so please pardon the crude approach)
Sheet 'Holidays' contains a list of holidays in the column B starting from row 2
Variable date is the date for which I want to find out the index for
Variable dayOfTheWeek is the number of day of 'date' counted from last Sunday, so if date is a Monday, dayOfTheWeek is 1; if date is Tuesday, dayOfTheWeek is 2, and so on ...
function indexOfWorkdayOfTheWeek (date, dayOfTheWeek, lastSundayDate)
{
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var activeCell = activeSheet.getActiveRange();
var activeRow = activeCell.getRowIndex();
var activeColumn = activeCell.getColumn();
var count = 1;
for (var j = 1; j < dayOfTheWeek; j++)
{
var date2 = lastSundayDate.valueOf() + j*86400;
Logger.log('Date ' + j + ' is:' + date2);
Logger.log('Last Sunday is:' + lastSundayDate);
if (holidayOrNot(date2) == true)
{
}
else
{
count = count + 1;
}
}
return count;
}
function holidayOrNot(date2)
{
var holidaysSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Holidays');
var listOfHolidays = holidaysSheet.getSheetValues(2, 2, 95, 1);
var isDateMatch = false;
for (var k = 0; k < 90; k++)
{
if (date2 == listOfHolidays[k].valueOf())
{
isDateMatch = true;
break;
}
else
{
continue;
}
}
return isDateMatch;
}
I think the problem is two-fold here:
The date2 calculation isn't working for some reason (var date2 = lastSundayDate.valueOf() + j*86400;)
The function holidayOrNot is returning false, no matter what, even if it encounters a holiday ... the condition date2 == listOfHolidays[k] isn't working for some reason...
Help would be appreciated!
maybe this method below could help you in your calculations, it returns an integer corresponding to the day of the year so if you apply this to your holidays days and compare to the days of interest it could be a good way to find matches.
here it is, just add these lines outside of any function in your script (so you can use it anywhere) then use it like this :
var d = new Date().getDOY();
Logger.log(d)
Here the method :
Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}
Assuming that lastSundayDate is being passed around correctly, I see a glaring problem:
lastSundayDate.valueOf().
valueOf() on Date objects returns the primitive value... it looks like you're going for adding a day to the date (86400 seconds * j)? I can't tell what the logic is supposed to be here. But the valueOf() date2 is definitely giving you an integer something like: 1384628769399 (see here).
What you really want to accomplish is something like Date.getDay(), or something similar so that you can add hours, days, etc. to the original Date. This is likely the source of all your problems.
What you can do is read the Mozilla Developer Network documentation on Date objects to see all of the functions on Dates and their uses. You can greatly simplify what you're trying to do by using these functions, instead of doing abstract operations like j * 86400.
It should also be noted that you can do simple operations such as the following, to add 4 hours to the current Date (time):
var myDate = new Date();
Logger.log(myDate); // ~ console.write
var laterDate = new Date(myDate.setHours(myDate.getHours() + 4));
Logger.log(laterDate); // ~ console.write
which gives the following:
[13-11-16 14:13:38:947 EST] Sat Nov 16 14:13:38 GMT-05:00 2013
[13-11-16 14:13:38:954 EST] Sat Nov 16 18:13:38 GMT-05:00 2013
Working with dates can be tricky - but it's always best to use the simplest methods that are available, which are built into the Date objects themselves. There are also numerous other libraries that provide extended functionality for Dates such as Date js.
If you're still running into your problem after attempting to try using methods I displayed above, please run your script and post both the Execution Transcript and the content of the Logger so that I can help you narrow down the issue :)

How to get a list of days or a number of days in a month with GWT?

What is counter part of this code in GWT ?
public int returnAllDaysOf(2012,6){
Calendar calendar = Calendar.getInstance();
calendar.set(2012, Calendar.FEBRUARY, 1);
int daysOfFeb = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return daysOfFeb;
}
Thanks in advance for your help.
I want to get the number of days of a month in the client side. I searched Google and StackOverFlow but didn't get anything.
for example Feb has 29 days, Match has 31 days and so on ...
I don't know a direct way, but you can calculate this value by adding one month to your date, and then calcualting the difference in days:
final Date myDate = ...;
final Date copyOfDate = CalendarUtil.copyDate(myDate);
CalendarUtil.addMonthsToDate(copyOfDate, 1);
final int daysBetween = CalendarUtil.getDaysBetween(myDate, copyOfDate);
Note: This even works if myDate is something like 2012-01-31. copyOfDate is then 2012-03-02 (because february doesn't have 31 days), and the result is correct again.
"Cheating" way to do it:
int daysInCurrentMonth = new Date(year-1900, month+1, 0).getDate();
I.E.
int daysInJanuary2014 = new Date(114, 1, 0).getDate();
basically set the Date object to the 0th day of the NEXT month, then get the day of the month.
NOTE: Date(int year, int month, int date) expects year=calendarYear-1900 (i.e. 2014=114) and month is 0-based (i.e. January would be month 0)
and yes, I know this constructor is deprecated, but I still use it.
DateField dfMois = new DateField();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dfMois.getValue());
Date date = dfMois.getValue();
Date dateCopy = dateFin;
dateCopy.setDate(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
if(date.getMonth() == Calendar.FEBRUARY + 1){
date.setDate(31 - dateCopy.getDate());
date.setMonth(date.getMonth()-1);
}
else{
date.setDate(dateCopy.getDate());
}
dfMois.setValue(date);
In your code... it work.

Relative formatting for timestamps

I wrote the CS 462 Office Hours app over the past two days. The most recent iteration tells the user when the next office hour time block will be. Right now, it just formats it as "Thursday (February 3) at 3 PM." I'd like it to be a little smarter, though, and say something like "this afternoon at 3 PM" or "tomorrow at 10 AM".
This is similar to Twitter's relative timestamps on tweets (it says "3 minutes ago" or "23 hours ago;" beyond that it lists the date). In my case, though, it will be the opposite, since we're dealing with future times.
Basically, it needs to be smart enough to know that an event is today or tomorrow. Beyond that, I just want to display the date and day of the week.
Is there a way to do this with KRL? Do I just need to use logic like this and write a function (or module)?
These are the functions I have:
// First define some constants to measuring relative time
now = time:now({"tz": "America/Denver"});
midnight = time:new("23:59:59.000-07:00");
tomorrow_midnight = time:add(midnight, {"days": 1});
yesterday_midnight = time:add(midnight, {"days": -1});
// Functions for calculating relative time
relativefuturedate = function(d){
ispast(d) => "today (past) at " + justtime(d)
| istoday(d) => "today at " + justtime(d)
| istomorrow(d) => "tomorrow at " + justtime(d)
| datetime(d);
};
istoday = function(d){
d > now && d <= midnight;
};
istomorrow = function(d){
not istoday(d) && d <= tomorrow_midnight;
};
ispast = function(d){
d < now;
};
isfuture = function(d){
d > now;
};
justtime = function(d){
time:strftime(d, "%l:%M %p");
};
datetime = function(d){
time:strftime(d, "%A (%B %e) at %l:%M %p");
};
This should do the trick. Right now I'm testing it with this rule:
rule first_rule {
select when pageview ".*"
pre {
today_9 = time:new("2011-02-09T09:00:00.000-07:00");
today_12 = time:new("2011-02-09T12:00:00.000-07:00");
today_4 = time:new("2011-02-09T16:00:00.000-07:00");
tomorrow_9 = time:new("2011-02-10T09:00:00.000-07:00");
tomorrow_4 = time:new("2011-02-10T16:00:00.000-07:00");
nextday_9 = time:new("2011-02-11T09:00:00.000-07:00");
relative_now = relativefuturedate(now);
relative_today_9 = relativefuturedate(today_9);
relative_today_12 = relativefuturedate(today_12);
relative_today_4 = relativefuturedate(today_4);
relative_tomorrow_9 = relativefuturedate(tomorrow_9);
relative_tomorrow_4 = relativefuturedate(tomorrow_4);
relative_nextday_9 = relativefuturedate(nextday_9);
message = <<
Now: #{relative_now}<br />
Today at 9: #{relative_today_9}<br />
Today at 12: #{relative_today_12}<br />
Today at 4: #{relative_today_4}<br />
Tomorrow at 9: #{relative_tomorrow_9}<br />
Tomorrow at 4: #{relative_tomorrow_4}<br />
Day after tomorrow at 9: #{relative_nextday_9}<br />
>>;
}
notify("Time calculations:", message) with sticky=true;
}
However, that doesn't seem to be working yet. I get this output:
Can anyone see what's wrong?
There currently isn't built in functionality to do this in KRL. You will probably need to write a function or a module to do this and I would love to see it if/when you do.