Emit the text and form fields to support due dates
555779
public static function dueDate()
    {
        global $USER;
        if ( ! $USER ) return false;
        $due = Settings::linkGet('due', '');
        $timezone = Settings::linkGet('timezone', 'Pacific/Honolulu');
        $time = Settings::linkGet('penalty_time', 86400);
        $cost = Settings::linkGet('penalty_cost', 0.2);

        if ( ! $USER->instructor ) {
            if ( strlen($due) < 1 ) {
                echo("<p>"._m("There is currently no due date/time for this assignment.")."</p>\n");
                return;
            }
            $dueDate = self::getDueDate();
            echo("<p>"._m("Due date: ").htmlent_utf8($due)."</p>\n");
            echo("<p>".$dueDate->penaltyinfo."</p>\n");
            if ( $dueDate->message ) {
                echo('<p style="color:red;">'.$dueDate->message.'</p>'."\n");
            }
            return;
        }
?>
        <label for="due">
            <?= _m("Please enter a due date in ISO 8601 format (2015-01-30T20:30) or leave blank for no due date.
            You can leave off the time to allow the assignment to be turned in any time during the day.") ?><br/>
        <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($due)); ?>" name="due"></label>
        <label for="timezone">
            <?= _m("Please enter a valid PHP Time Zone like 'Pacific/Honolulu' (default).  If you are
            teaching in many time zones around the world, 'Pacific/Honolulu' is a good time
            zone to choose - this is why it is the default.") ?><br/>
        <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($timezone)); ?>" name="timezone"></label>
            <p><?= _m("The next two fields determine the 'overall penalty' for being late.  We define a time period
            (in seconds) and a fractional penalty per time period.  The penalty is assessed for each
            full or partial time period past the due date.  For example to deduct 20% per day, you would
            set the period to be 86400 (24*60*60) and the penalty to be 0.2.") ?>
            </p>
        <label for="penalty_time"><?= _m("Please enter the penalty time period in seconds.") ?><br/>
        <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($time)); ?>" name="penalty_time"></label>
        <label for="penalty_cost"><?= _m("Please enter the penalty deduction as a decimal between 0.0 and 1.0.") ?><br/>
        <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($cost)); ?>" name="penalty_cost"></label>
<?php
    }
769673
function(inst, date, noChange) {
		var clear = !date,
			origMonth = inst.selectedMonth,
			origYear = inst.selectedYear,
			newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));

		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
			this._notifyChange(inst);
		}
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? "" : this._formatDate(inst));
		}
	}
20474
def GenerateCalendarDatesFieldValuesTuples(self):
    """"""
    for date, (exception_type, _) in self.date_exceptions.items():
      yield (self.service_id, date, unicode(exception_type))
1084956
function calendarComponent() {
    $this->objName         = ( isset( $this->timezonetype )) ?
                          strtolower( $this->timezonetype )  :  get_class ( $this );
    $this->uid             = array();
    $this->dtstamp         = array();

    $this->action          = array();
    $this->attach          = array();
    $this->attendee        = array();
    $this->categories      = array();
    $this->class           = array();
    $this->comment         = array();
    $this->completed       = array();
    $this->contact         = array();
    $this->created         = array();
    $this->description     = array();
    $this->dtend           = array();
    $this->dtstart         = array();
    $this->due             = array();
    $this->duration        = array();
    $this->exdate          = array();
    $this->exrule          = array();
    $this->freebusy        = array();
    $this->geo             = array();
    $this->lastmodified    = array();
    $this->location        = array();
    $this->organizer       = array();
    $this->percentcomplete = array();
    $this->priority        = array();
    $this->rdate           = array();
    $this->recurrenceid    = array();
    $this->relatedto       = array();
    $this->repeat          = array();
    $this->requeststatus   = array();
    $this->resources       = array();
    $this->sequence        = array();
    $this->rrule           = array();
    $this->status          = array();
    $this->summary         = array();
    $this->transp          = array();
    $this->trigger         = array();
    $this->tzid            = array();
    $this->tzname          = array();
    $this->tzoffsetfrom    = array();
    $this->tzoffsetto      = array();
    $this->tzurl           = array();
    $this->url             = array();
    $this->xprop           = array();

    $this->components      = array();

    $this->language        = null;
    $this->nl              = null;
    $this->unique_id       = null;
    $this->allowEmpty      = TRUE;
    $this->xcaldecl        = array();

    $this->_makeDtstamp();
  }
63951
public static function calendar()
	{
		if (isset(self::$loaded[__METHOD__]))
		{
			return;
		}

		/*$tag = App::get('language')->getTag();

		$translation = self::_calendartranslation();
		if ($translation)
		{
			App::get('document')->addScriptDeclaration($translation);
		}*/

		Asset::stylesheet('assets/jquery.datepicker.css', array('media' => 'all'), true);
		Asset::stylesheet('assets/jquery.timepicker.css', array('media' => 'all'), true);

		self::framework(true);

		Asset::script('assets/jquery.timepicker.js', false, true);

		self::$loaded[__METHOD__] = true;
	}
198972
def print_fields(fields, sort_by_date=False, sort_by_open_projects=False):
    
    if (not sort_by_date) and (not sort_by_open_projects):
        for (_, name, works) in fields:
            print(name)
            for work in works:
                print('- '+str(work))
    else:
        works = all_works
        # Sort works by due_date
        if sort_by_date:
            works.sort(key=lambda x: (not x.is_open, x.due_date), reverse=True)
        for work in works:
            if sort_by_open_projects:
                if not work.is_open:
                    continue
            # This is ugly, but there is no way to know the field name of a work without searching for it, at the moment
            field_name = [name for id, name, _ in fields if id == work.field][0]
            print(field_name)
            print('- '+str(work))
398484
function(elem, inst) {
			elem.off('focus.' + inst.name);
			if (inst.options.showOnFocus) {
				elem.on('focus.' + inst.name, this.show);
			}
			if (inst.trigger) {
				inst.trigger.remove();
			}
			var trigger = inst.options.showTrigger;
			inst.trigger = (!trigger ? $([]) :
				$(trigger).clone().removeAttr('id').addClass(this._triggerClass)
					[inst.options.isRTL ? 'insertBefore' : 'insertAfter'](elem).
					click(function() {
						if (!plugin.isDisabled(elem[0])) {
							plugin[plugin.curInst === inst ? 'hide' : 'show'](elem[0]);
						}
					}));
			this._autoSize(elem, inst);
			var dates = this._extractDates(inst, elem.val());
			if (dates) {
				this.setDate(elem[0], dates, null, true);
			}
			var defaultDate = inst.get('defaultDate');
			if (inst.options.selectDefaultDate && defaultDate && inst.selectedDates.length === 0) {
				this.setDate(elem[0], (defaultDate || inst.options.calendar.today()).newDate());
			}
		}
1278582
def write_items(self, calendar):
        
        for item in self.items:
            event = Event()
            for ifield, efield in ITEM_EVENT_FIELD_MAP:
                val = item.get(ifield)
                if val is not None:
                    event.add(efield, val)
            calendar.add_component(event)
559392
function(inst) {
		var altFormat, date, dateStr,
			altField = this._get(inst, "altField");

		if (altField) { // update alternate field too
			altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
			date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	}
826363
function(item_data){
      var item_text, // The text that will display in the item
          todo_div, todo_checkbox, todo_delete, todo_wrapper; // DOM elements (main div, checkbox that indicates done-ness)

      todo.data[item_data.__id__] = item_data;

      item_text = ''; // By default, start with an empty string.
      if (item_data.hasOwnProperty('deadline')){ // Parse how much time is left to complete this task.
        parsed_deadline = todo.parse_remaining_time(item_data.deadline.timestamp);
        if (parsed_deadline <= 0){
          item_text += '<span class="overdue">Overdue</span>'; // If time is up, put a bold "Overdue" flag on the item.
        } else {
        item_text += '<span class="due">Due in ' + parsed_deadline + ' hours.</span>'; // Else, put a subtler flag indicating the hours left to complete the task.
        }
      }
      // Build the elements
      todo_wrapper = $('<span item="' + item_data.__id__ + '"><br></span>');
      todo_div = $('<div class="todo_item"><span class="value"></span>' + item_text + '</div>');
      todo_div.find('.value').text(item_data.text); // Use $.text() to prevent script injection
      todo_checkbox = $('<input type="checkbox" />'),
      todo_delete = $('<div class="delete_button"></div>');

      // Styling for if the item is done: "done" class crosses out text and makes it lighter. Check off the checkbox, too.
      if (item_data.done){
        todo_div.addClass('done');
        todo_checkbox.attr('checked', true);
      }

      /*
        Prepend the checkbox to the div element and give the whole thing
        a click function to toggle the listing's done status.
        (This is just for UI's sake: it's easier to click the whole thing than ticking the checkbox itself.
        The CSS cursor: pointer on the item will make it clear that it's clickable)
      */
      todo_div.prepend(todo_checkbox).click(function(){
        var item_data = todo.data[$(this).parent().attr('item')];
        todo.toggle_item(item_data);
      }).css({
        background: todo.priority_colors[item_data.priority] // Give the item the color corresponding to its priority level.
      });

      // Bind click event to the delete button
      todo_delete.click(function(e){
        e.stopPropagation();
        todo.delete_item($(this).parent().parent().attr('item'))
      });

      // Commit the element to the page.
      $(todo_div).append(todo_delete);
      $(todo_wrapper).prepend(todo_div);
      $('#todo').prepend(todo_wrapper);

      // In case this is the first item added, hide the "You haven't added any items yet" message.
      $('#empty_list').hide();
    }
796647
def _pressed(self, evt):
        """"""
        x, y, widget = evt.x, evt.y, evt.widget
        item = widget.identify_row(y)
        column = widget.identify_column(x)

        if not column or not item in self._items:
            # clicked in the weekdays row or just outside the columns
            return

        item_values = widget.item(item)['values']
        if not len(item_values):  # row is empty for this month
            return

        text = item_values[int(column[1]) - 1]
        if not text:  # date is empty
            return

        bbox = widget.bbox(item, column)
        if not bbox:  # calendar not visible yet
            return

        # update and then show selection
        text = '%02d' % text
        self._selection = (text, item, column)
        self._show_selection(text, bbox)
        year, month = self._date.year, self._date.month
        try:
            self._TargetElement.Update(self.datetime(year, month, int(self._selection[0])))
            if self._TargetElement.ChangeSubmits:
                self._TargetElement.ParentForm.LastButtonClicked = self._TargetElement.Key
                self._TargetElement.ParentForm.FormRemainedOpen = True
                self._TargetElement.ParentForm.TKroot.quit()  # kick the users out of the mainloop
        except:
            pass
        if self.close_when_chosen:
            self._master.destroy()
941678
void submit() {

        //        if (!m_dateField.isValid()) {
        //            return;
        //        }
        long current = System.currentTimeMillis();
        Date dateValue = m_dateField.getDate();
        long publishTime = dateValue.getTime();
        if (current > publishTime) {
            m_context.error(
                new CmsException(Messages.get().container(Messages.ERR_PUBLISH_SCHEDULED_DATE_IN_PAST_1, dateValue)));
        } else {
            try {
                // make copies from the admin cmsobject and the user cmsobject
                // get the admin cms object
                CmsWorkplaceAction action = CmsWorkplaceAction.getInstance();
                CmsObject cmsAdmin = action.getCmsAdminObject();
                // get the user cms object
                CmsObject cms = OpenCms.initCmsObject(m_context.getCms());

                // set the current user site to the admin cms object
                cmsAdmin.getRequestContext().setSiteRoot(cms.getRequestContext().getSiteRoot());
                CmsProject tmpProject = createTempProject(cmsAdmin, m_context.getResources(), dateValue);
                // set project as current project
                cmsAdmin.getRequestContext().setCurrentProject(tmpProject);
                cms.getRequestContext().setCurrentProject(tmpProject);

                Set<CmsUUID> changeIds = new HashSet<CmsUUID>();
                for (CmsResource resource : m_context.getResources()) {
                    addToTempProject(cmsAdmin, cms, resource, tmpProject);
                    if (resource.isFolder() && m_includeSubResources.getValue().booleanValue()) {
                        List<CmsResource> subResources = cms.readResources(
                            resource,
                            CmsResourceFilter.ONLY_VISIBLE.addExcludeState(CmsResourceState.STATE_UNCHANGED),
                            true);
                        for (CmsResource sub : subResources) {
                            // check publish permissions on sub resource
                            if (cms.hasPermissions(
                                sub,
                                CmsPermissionSet.ACCESS_DIRECT_PUBLISH,
                                false,
                                CmsResourceFilter.ALL)) {
                                addToTempProject(cmsAdmin, cms, sub, tmpProject);
                            }
                        }
                    }

                    changeIds.add(resource.getStructureId());
                }
                // create a new scheduled job
                CmsScheduledJobInfo job = new CmsScheduledJobInfo();
                // the job name
                String jobName = tmpProject.getName();
                jobName = jobName.replace("&#47;", "/");
                // set the job parameters
                job.setJobName(jobName);
                job.setClassName("org.opencms.scheduler.jobs.CmsPublishScheduledJob");
                // create the cron expression
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dateValue);
                String cronExpr = ""
                    + calendar.get(Calendar.SECOND)
                    + " "
                    + calendar.get(Calendar.MINUTE)
                    + " "
                    + calendar.get(Calendar.HOUR_OF_DAY)
                    + " "
                    + calendar.get(Calendar.DAY_OF_MONTH)
                    + " "
                    + (calendar.get(Calendar.MONTH) + 1)
                    + " "
                    + "?"
                    + " "
                    + calendar.get(Calendar.YEAR);
                // set the cron expression
                job.setCronExpression(cronExpr);
                // set the job active
                job.setActive(true);
                // create the context info
                CmsContextInfo contextInfo = new CmsContextInfo();
                contextInfo.setProjectName(tmpProject.getName());
                contextInfo.setUserName(cmsAdmin.getRequestContext().getCurrentUser().getName());
                // create the job schedule parameter
                SortedMap<String, String> params = new TreeMap<String, String>();
                // the user to send mail to
                String userName = m_context.getCms().getRequestContext().getCurrentUser().getName();
                params.put(CmsPublishScheduledJob.PARAM_USER, userName);
                // the job name
                params.put(CmsPublishScheduledJob.PARAM_JOBNAME, jobName);
                // the link check
                params.put(CmsPublishScheduledJob.PARAM_LINKCHECK, "true");
                // add the job schedule parameter
                job.setParameters(params);
                // add the context info to the scheduled job
                job.setContextInfo(contextInfo);
                // add the job to the scheduled job list
                OpenCms.getScheduleManager().scheduleJob(cmsAdmin, job);
                // update the XML configuration
                OpenCms.writeConfiguration(CmsSchedulerConfiguration.class);
                m_context.finish(changeIds);
            } catch (CmsException ex) {
                LOG.error("Error performing publish scheduled dialog operation.", ex);
                m_context.error(ex);
            }
        }

    }
456853
def _dates(self, key, value):
    
    if value.get('q'):
        self['date_proposed'] = normalize_date(value['q'])
    if value.get('r'):
        self['date_approved'] = normalize_date(value['r'])
    if value.get('s'):
        self['date_started'] = normalize_date(value['s'])
    if value.get('c'):
        self['date_cancelled'] = normalize_date(value['c'])
    if value.get('t'):
        self['date_completed'] = normalize_date(value['t'])

    raise IgnoreKey
354195
def setCurrentDate( self, date ):
        
        if ( date == self._currentDate or not date.isValid() ):
            return
        
        self._currentDate = date
        self.markForRebuild()
        
        parent = self.parent()
        if ( not parent.signalsBlocked() ):
            parent.currentDateChanged.emit(date)
            parent.titleChanged.emit(self.title())
1373176
def _make_notice_date(self, response):
        
        today = date.today()
        yesterday = today - timedelta(days=1)
        tomorrow = today + timedelta(days=1)
        week = today + timedelta(days=2)
        next_week = today + timedelta(weeks=1)
        future = today + timedelta(weeks=3)
        future_end = today + timedelta(weeks=5)

        json_data = json.loads(response.data)
        for notice in json_data["Notices"]:
            if notice["NoticeAttributes"] and\
                    len(notice["NoticeAttributes"]) > 0:
                for attr in notice["NoticeAttributes"]:
                    if attr["DataType"] == "date":
                        if attr["Value"] == "yesterday":
                            attr["Value"] = yesterday.strftime("%Y%m%d")
                        elif attr["Value"] == "today":
                            attr["Value"] = today.strftime("%Y%m%d")
                        elif attr["Value"] == "tomorrow":
                            attr["Value"] = tomorrow.strftime("%Y%m%d")
                        elif attr["Value"] == "future":
                            attr["Value"] = future.strftime("%Y%m%d")
                        elif attr["Value"] == "future_end":
                            attr["Value"] = future_end.strftime("%Y%m%d")
                        elif attr["Value"] == "next_week":
                            attr["Value"] = next_week.strftime("%Y%m%d")
                        elif attr["Value"] == "week":
                            attr["Value"] = week.strftime("%Y%m%d")
                        else:
                            pass   # use original

        response.data = json.dumps(json_data)
816694
public function definition_after_data() {
        global $CFG;

        $mform = $this->_form;

        // If calendar type does not exist, use site default calendar type.
        if ($calendarselected = $mform->getElementValue('calendartype')) {
            if (is_array($calendarselected)) {
                // There are multiple calendar types available.
                $calendar = reset($calendarselected);
            } else {
                // There is only one calendar type available.
                $calendar = $calendarselected;
            }
            // Check calendar type exists.
            if (!array_key_exists($calendar, \core_calendar\type_factory::get_list_of_calendar_types())) {
                $calendartypeel = $mform->getElement('calendartype');
                $calendartypeel->setValue($CFG->calendartype);
            }
        }
    }
80416
def get_date_field(datetimes, field):
    """"""
    return np.array([getattr(date, field) for date in datetimes])