text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.poi.ss.util.CellRangeAddressList (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.poi.ss.util.CellRangeAddressList

Packages that use CellRangeAddressList

org.apache.poi.hssf.record
Record package contains class representations for XLS binary strutures.

org.apache.poi.hssf.usermodel
usermodel package maps HSSF low level strutures to familiar workbook/sheet model

org.apache.poi.hssf.util
util package contains tools needed for writing HSSF files that are not necesarily "real"
HSSF concepts.

org.apache.poi.ss.usermodel

org.apache.poi.ss.util

org.apache.poi.xssf.usermodel

Uses of CellRangeAddressList in org.apache.poi.hssf.record

Methods in org.apache.poi.hssf.record that return CellRangeAddressList

 CellRangeAddressList
DVRecord.getCellRangeAddress()

Constructors in org.apache.poi.hssf.record with parameters of type CellRangeAddressList

DVRecord(int validationType,
         int operator,
         int errorStyle,
         boolean emptyCellAllowed,
         boolean suppressDropDownArrow,
         boolean isExplicitList,
         boolean showPromptBox,
         java.lang.String promptTitle,
         java.lang.String promptText,
         boolean showErrorBox,
         java.lang.String errorTitle,
         java.lang.String errorText,
         Ptg[] formula1,
         Ptg[] formula2,
         CellRangeAddressList regions)

Uses of CellRangeAddressList in org.apache.poi.hssf.usermodel

Methods in org.apache.poi.hssf.usermodel that return CellRangeAddressList

 CellRangeAddressList
HSSFDataValidation.getRegions()

Methods in org.apache.poi.hssf.usermodel with parameters of type CellRangeAddressList

 DataValidation
HSSFDataValidationHelper.createValidation(DataValidationConstraint constraint,
                 CellRangeAddressList cellRangeAddressList)

Constructors in org.apache.poi.hssf.usermodel with parameters of type CellRangeAddressList

HSSFDataValidation(CellRangeAddressList regions,
                   DataValidationConstraint constraint)

          Constructor which initializes the cell range on which this object will be
 applied

Uses of CellRangeAddressList in org.apache.poi.hssf.util

Subclasses of CellRangeAddressList in org.apache.poi.hssf.util

 class
CellRangeAddressList

          Deprecated. use CellRangeAddressList

Uses of CellRangeAddressList in org.apache.poi.ss.usermodel

Methods in org.apache.poi.ss.usermodel that return CellRangeAddressList

 CellRangeAddressList
DataValidation.getRegions()

Methods in org.apache.poi.ss.usermodel with parameters of type CellRangeAddressList

 DataValidation
DataValidationHelper.createValidation(DataValidationConstraint constraint,
                 CellRangeAddressList cellRangeAddressList)

Uses of CellRangeAddressList in org.apache.poi.ss.util

Methods in org.apache.poi.ss.util that return CellRangeAddressList

 CellRangeAddressList
CellRangeAddressList.copy()

Uses of CellRangeAddressList in org.apache.poi.xssf.usermodel

Methods in org.apache.poi.xssf.usermodel that return CellRangeAddressList

 CellRangeAddressList
XSSFDataValidation.getRegions()

Methods in org.apache.poi.xssf.usermodel with parameters of type CellRangeAddressList

 DataValidation
XSSFDataValidationHelper.createValidation(DataValidationConstraint constraint,
                 CellRangeAddressList cellRangeAddressList)

Constructors in org.apache.poi.xssf.usermodel with parameters of type CellRangeAddressList

XSSFDataValidation(XSSFDataValidationConstraint constraint,
                   CellRangeAddressList regions,
                   org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDataValidation ctDataValidation)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Tyler" >

    <title>Résumé</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/grayscale.css" rel="stylesheet">

    <link rel="stylesheet" href="css/mystyle.css">
    <link rel="stylesheet" href="css/resumestyle.css">

    <link href="font-awesome-4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link rel="shortcut icon" href="img/WebsiteLogo.ico.png">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                    Home

                        Education

                        Technical Skills

                        Professional Experience

Résumé

An overview of my knowledge, skills, and experience.

Explore

Education

                    California Polytechnic State University,
San Luis Obispo

                        Attending 4th Year

                        Computer Engineering

                        Graduating Spring 2016

                        View School Courses »

Technical Skills

                    Programming

                        Strongest Languages at Center >>

                        POSIX Multithreading

                        Object-Oriented Programming

                    Concepts

                        Operating Systems

                        Digital & Analog Logic

                        Computer Architecture

 Strong understanding of programming concepts allows me to learn new languages quickly (which I greatly enjoy).

Professional Experience

                    The Aerospace Corporation

                    El Segundo, CA

                        Software Development Internship

                        Summer 2011 - Summer 2014

                        Great Learning Experience

                        View Work Projects »

Copyright © Tyler Mau 2014

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Doctrine\ODM\CouchDB\Id;

use Doctrine\ODM\CouchDB\DocumentManager;
use Doctrine\ODM\CouchDB\Mapping\ClassMetadata;
use Doctrine\ODM\CouchDB\CouchDBException;

class AssignedIdGenerator extends IdGenerator
{
    /**
     * @param object $document
     * @param ClassMetadata $cm
     * @param DocumentManager $dm
     * @return array
     * @throws CouchDBException
     */
    public function generate($document, ClassMetadata $cm, DocumentManager $dm)
    {
        $id = $cm->getIdentifierValue($document);
        if (!$id) {
            throw CouchDBException::assignedIdGeneratorNoIdFound($cm->name);
        }
        return $id;
    }
}


text:
module Nexpose

  class GlobalBlackout < APIObject
    require 'json'
    include JsonSerializer

    # [Array] Blackout starting dates, times and duration for blackout periods.
    attr_accessor :blackout

    def initialize(blackout)
      @blackout = Array(blackout)
    end

    def save(nsc)
      params = to_json
      AJAX.post(nsc, '/api/2.1/silo_blackout/', params, AJAX::CONTENT_TYPE::JSON)
    end

    def to_h
      {
        blackouts: (@blackout || []).map(&:to_h)
      }
    end

    def to_json
      JSON.generate(to_h)
    end

    def self.json_initializer(data)
      new(blackout: data)
    end

    def self.load(nsc)
      uri               = '/api/2.1/silo_blackout/'
      resp              = AJAX.get(nsc, uri, AJAX::CONTENT_TYPE::JSON)
      hash              = JSON.parse(resp, symbolize_names: true)
      blackout          = self.json_initializer(hash).deserialize(hash)
      blackout.blackout = (hash[:blackouts] || []).map { |bout| Nexpose::Blackout.from_hash(bout) }
      blackout
    end
  end
end


text:
class RemoveOldGradeStuff < ActiveRecord::Migration
  def change
    remove_column :students, :grade
    remove_column :students, :last_completed_grade
  end
end


text:
package com.pkware.truth.android.telephony;

import android.annotation.TargetApi;
import android.telephony.CellSignalStrengthLte;

import com.google.common.truth.FailureMetadata;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;

/**
 * Propositions for {@link CellSignalStrengthLte} subjects.
 * <p/>
 * This class is final. To extend use {@link AbstractCellSignalStrengthSubject}.
 */
@TargetApi(JELLY_BEAN_MR1)
public final class CellSignalStrengthLteSubject
    extends AbstractCellSignalStrengthSubject<CellSignalStrengthLte> {

  @Nullable
  private CellSignalStrengthLte actual;

  public CellSignalStrengthLteSubject(@Nonnull FailureMetadata failureMetadata, @Nullable CellSignalStrengthLte actual) {
    super(failureMetadata, actual);
    this.actual = actual;
  }

  public void hasTimingAdvance(int timingAdvance) {
    check("getTimingAdvance()").that(actual.getTimingAdvance()).isEqualTo(timingAdvance);
  }
}


text:
class HruidService
  # build hruid from user info and check uniqness
  def self.generate(user)
    suffix = self.suffix_for(user)
    standard_hruid = self.build(user.firstname, user.lastname, suffix)
    hruid = standard_hruid
    homonyms_count = 1

    loop do
      break hruid unless MasterData::Account.exists?(hruid: hruid)
      homonyms_count += 1
      hruid = "#{standard_hruid}.#{homonyms_count.to_s}"
    end
  end

  # this method is used by alias_service and must stay public
  def self.canonical_name(first_name, last_name)
    first_name = "prenom" if first_name.blank?
    last_name = "nom" if last_name.blank?
    return "#{format_name(first_name)}.#{format_name(last_name.downcase)}"
  end

  private

  # build hruid from user info
  def self.build(first_name, last_name, suffix)
    canonical_name = self.canonical_name(first_name, last_name)
    hruid = "#{canonical_name}.#{suffix}"
  end

  # generate hruid from user type
  # suffix = {"soce", "ext", promo}
  def self.suffix_for(user)
    if user.gadz_proms_principale
      suffix = user.gadz_proms_principale.to_s
    elsif user.is_soce_employee
      suffix = "soce"
    else
      suffix = "ext"
    end
  end

  def self.format_name(name)
    #replace space by "-"
    name = name.gsub(" ", "-")
    #downcase
    name = name.downcase
    #convert special letters
    name = name.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/u, "").to_s
    #remove special char
    name = name.gsub(/[^a-z\-]/, "")
  end
end


text:
namespace Lucene.Net.Codecs.Lucene3x
{
    using Directory = Lucene.Net.Store.Directory;
    using IOContext = Lucene.Net.Store.IOContext;

    using SegmentInfo = Lucene.Net.Index.SegmentInfo;

    internal class PreFlexRWStoredFieldsFormat : Lucene3xStoredFieldsFormat
    {
        public override StoredFieldsWriter FieldsWriter(Directory directory, SegmentInfo segmentInfo, IOContext context)
        {
            return new PreFlexRWStoredFieldsWriter(directory, segmentInfo.Name, context);
        }
    }
}


text:
import React from "react";

import styles from "./Contact.module.css";

function Contact() {
  return (

        Say hello at{" "}

          nrmaskell@gmail.com

  );
}

export default Contact;


text:
package com.amazonaws.services.guardduty.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The account within the organization specified as the GuardDuty delegated administrator.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AdminAccount implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The Amazon Web Services account ID for the account.
     *

     */
    private String adminAccountId;
    /**
     *

     * Indicates whether the account is enabled as the delegated administrator.
     *

     */
    private String adminStatus;

    /**
     *

     * The Amazon Web Services account ID for the account.
     *

     *
     * @param adminAccountId
     *        The Amazon Web Services account ID for the account.
     */

    public void setAdminAccountId(String adminAccountId) {
        this.adminAccountId = adminAccountId;
    }

    /**
     *

     * The Amazon Web Services account ID for the account.
     *

     *
     * @return The Amazon Web Services account ID for the account.
     */

    public String getAdminAccountId() {
        return this.adminAccountId;
    }

    /**
     *

     * The Amazon Web Services account ID for the account.
     *

     *
     * @param adminAccountId
     *        The Amazon Web Services account ID for the account.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AdminAccount withAdminAccountId(String adminAccountId) {
        setAdminAccountId(adminAccountId);
        return this;
    }

    /**
     *

     * Indicates whether the account is enabled as the delegated administrator.
     *

     *
     * @param adminStatus
     *        Indicates whether the account is enabled as the delegated administrator.
     * @see AdminStatus
     */

    public void setAdminStatus(String adminStatus) {
        this.adminStatus = adminStatus;
    }

    /**
     *

     * Indicates whether the account is enabled as the delegated administrator.
     *

     *
     * @return Indicates whether the account is enabled as the delegated administrator.
     * @see AdminStatus
     */

    public String getAdminStatus() {
        return this.adminStatus;
    }

    /**
     *

     * Indicates whether the account is enabled as the delegated administrator.
     *

     *
     * @param adminStatus
     *        Indicates whether the account is enabled as the delegated administrator.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AdminStatus
     */

    public AdminAccount withAdminStatus(String adminStatus) {
        setAdminStatus(adminStatus);
        return this;
    }

    /**
     *

     * Indicates whether the account is enabled as the delegated administrator.
     *

     *
     * @param adminStatus
     *        Indicates whether the account is enabled as the delegated administrator.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AdminStatus
     */

    public AdminAccount withAdminStatus(AdminStatus adminStatus) {
        this.adminStatus = adminStatus.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAdminAccountId() != null)
            sb.append("AdminAccountId: ").append(getAdminAccountId()).append(",");
        if (getAdminStatus() != null)
            sb.append("AdminStatus: ").append(getAdminStatus());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AdminAccount == false)
            return false;
        AdminAccount other = (AdminAccount) obj;
        if (other.getAdminAccountId() == null ^ this.getAdminAccountId() == null)
            return false;
        if (other.getAdminAccountId() != null && other.getAdminAccountId().equals(this.getAdminAccountId()) == false)
            return false;
        if (other.getAdminStatus() == null ^ this.getAdminStatus() == null)
            return false;
        if (other.getAdminStatus() != null && other.getAdminStatus().equals(this.getAdminStatus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAdminAccountId() == null) ? 0 : getAdminAccountId().hashCode());
        hashCode = prime * hashCode + ((getAdminStatus() == null) ? 0 : getAdminStatus().hashCode());
        return hashCode;
    }

    @Override
    public AdminAccount clone() {
        try {
            return (AdminAccount) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.guardduty.model.transform.AdminAccountMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
class AddExternalAuthorizationServiceClassificationLabelToProjects < ActiveRecord::Migration[4.2]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  def change
    add_column :projects,
               :external_authorization_classification_label,
               :string
  end
end


text:
<?php
/**
 * Migration. Adds "author" column to "comics" table.
 *
 * @package ComicCMS2
 * @author Cezary Kluczyński
 * @license https://github.com/cezarykluczynski/ComicCMS2/blob/master/LICENSE.txt MIT
 */

namespace DoctrineMigrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20150607103005 extends AbstractMigration
{
    /**
     * @param Schema $schema
     * @return void
     */
    public function up(Schema $schema)
    {
        $this->extendTableComics($schema);
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function down(Schema $schema)
    {
        $this->pruneTableComics($schema);
    }

    /**
     * Add column "author" to "comics" table.
     *
     * @param Schema $schema
     * @return void
     */
    public function extendTableComics(Schema $schema)
    {
        $comics = $schema->getTable('comics');
        $comics->addColumn('author', 'string', array('limit' => 255, 'notNull' => false));
    }

    /**
     * Remove column "author" from "comics" table.
     *
     * @param Schema $schema
     * @return void
     */
    public function pruneTableComics(Schema $schema)
    {
        $comics = $schema->getTable('comics');
        $comics->dropColumn('author');
    }
}


text:
package org.synyx.urlaubsverwaltung.web.application;

import org.joda.time.DateMidnight;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.Errors;
import org.synyx.urlaubsverwaltung.core.application.domain.Application;
import org.synyx.urlaubsverwaltung.core.application.domain.VacationCategory;
import org.synyx.urlaubsverwaltung.core.application.domain.VacationType;
import org.synyx.urlaubsverwaltung.core.application.service.CalculationService;
import org.synyx.urlaubsverwaltung.core.overtime.OvertimeService;
import org.synyx.urlaubsverwaltung.core.period.DayLength;
import org.synyx.urlaubsverwaltung.core.person.Person;
import org.synyx.urlaubsverwaltung.core.settings.Settings;
import org.synyx.urlaubsverwaltung.core.settings.SettingsService;
import org.synyx.urlaubsverwaltung.core.workingtime.OverlapCase;
import org.synyx.urlaubsverwaltung.core.workingtime.OverlapService;
import org.synyx.urlaubsverwaltung.core.workingtime.WorkDaysService;
import org.synyx.urlaubsverwaltung.core.workingtime.WorkingTimeService;
import org.synyx.urlaubsverwaltung.test.TestDataCreator;

import java.math.BigDecimal;
import java.sql.Time;
import java.util.Optional;
import java.util.function.Consumer;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

/**
 * Unit test for {@link ApplicationValidator}.
 *
 * @author  Aljona Murygina - murygina@synyx.de
 */
public class ApplicationValidatorTest {

    private ApplicationValidator validator;

    private WorkingTimeService workingTimeService;
    private WorkDaysService calendarService;
    private OverlapService overlapService;
    private CalculationService calculationService;
    private SettingsService settingsService;

    private Errors errors;
    private ApplicationForLeaveForm appForm;

    private Settings settings;
    private OvertimeService overtimeService;

    @Before
    public void setUp() {

        settingsService = mock(SettingsService.class);
        settings = new Settings();
        settings.getWorkingTimeSettings().setOvertimeActive(true);
        when(settingsService.getSettings()).thenReturn(settings);

        calendarService = mock(WorkDaysService.class);
        overlapService = mock(OverlapService.class);
        calculationService = mock(CalculationService.class);
        workingTimeService = mock(WorkingTimeService.class);
        overtimeService = mock(OvertimeService.class);

        validator = new ApplicationValidator(workingTimeService, calendarService, overlapService, calculationService,
                settingsService, overtimeService);
        errors = mock(Errors.class);

        appForm = new ApplicationForLeaveForm();

        appForm.setVacationType(TestDataCreator.createVacationType(VacationCategory.HOLIDAY));
        appForm.setDayLength(DayLength.FULL);
        appForm.setStartDate(DateMidnight.now());
        appForm.setEndDate(DateMidnight.now().plusDays(2));
        appForm.setPerson(TestDataCreator.createPerson());

        // Default: everything is alright, override for negative cases
        when(errors.hasErrors()).thenReturn(Boolean.FALSE);

        when(workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(any(Person.class), any(DateMidnight.class)))
            .thenReturn(Optional.of(TestDataCreator.createWorkingTime()));
        when(calendarService.getWorkDays(any(DayLength.class), any(DateMidnight.class), any(DateMidnight.class),
                    any(Person.class))).thenReturn(BigDecimal.ONE);
        when(overlapService.checkOverlap(any(Application.class))).thenReturn(OverlapCase.NO_OVERLAPPING);
        when(calculationService.checkApplication(any(Application.class))).thenReturn(Boolean.TRUE);
        when(overtimeService.getLeftOvertimeForPerson(any(Person.class))).thenReturn(BigDecimal.TEN);
    }

    // Supports --------------------------------------------------------------------------------------------------------

    @Test
    public void ensureSupportsAppFormClass() {

        assertTrue(validator.supports(ApplicationForLeaveForm.class));
    }

    @Test
    public void ensureDoesNotSupportNull() {

        assertFalse(validator.supports(null));
    }

    @Test
    public void ensureDoesNotSupportOtherClass() {

        assertFalse(validator.supports(Person.class));
    }

    // Validate period (date) ------------------------------------------------------------------------------------------

    @Test
    public void ensureStartDateIsMandatory() {

        appForm.setDayLength(DayLength.FULL);
        appForm.setStartDate(null);

        validator.validate(appForm, errors);

        verify(errors).rejectValue("startDate", "error.entry.mandatory");
    }

    @Test
    public void ensureEndDateIsMandatory() {

        appForm.setDayLength(DayLength.FULL);
        appForm.setEndDate(null);

        when(errors.hasErrors()).thenReturn(true);

        validator.validate(appForm, errors);

        verify(errors).rejectValue("endDate", "error.entry.mandatory");
    }

    @Test
    public void ensureStartDateMustBeBeforeEndDate() {

        appForm.setDayLength(DayLength.FULL);
        appForm.setStartDate(new DateMidnight(2012, 1, 17));
        appForm.setEndDate(new DateMidnight(2012, 1, 12));

        validator.validate(appForm, errors);

        verify(errors).reject("error.entry.invalidPeriod");
    }

    @Test
    public void ensureVeryPastDateIsNotValid() {

        DateMidnight pastDate = DateMidnight.now().minusYears(10);

        appForm.setDayLength(DayLength.FULL);
        appForm.setStartDate(pastDate);
        appForm.setEndDate(pastDate.plusDays(1));

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.tooFarInThePast");
    }

    @Test
    public void ensureVeryFutureDateIsNotValid() {

        DateMidnight futureDate = DateMidnight.now().plusYears(10);

        appForm.setDayLength(DayLength.FULL);
        appForm.setStartDate(futureDate);
        appForm.setEndDate(futureDate.plusDays(1));

        validator.validate(appForm, errors);

        verify(errors)
            .reject("application.error.tooFarInTheFuture",
                new Object[] { settings.getAbsenceSettings().getMaximumMonthsToApplyForLeaveInAdvance() }, null);
    }

    @Test
    public void ensureMorningApplicationForLeaveMustBeOnSameDate() {

        appForm.setDayLength(DayLength.MORNING);
        appForm.setStartDate(DateMidnight.now());
        appForm.setEndDate(DateMidnight.now().plusDays(1));

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.halfDayPeriod");
    }

    @Test
    public void ensureNoonApplicationForLeaveMustBeOnSameDate() {

        appForm.setDayLength(DayLength.NOON);
        appForm.setStartDate(DateMidnight.now());
        appForm.setEndDate(DateMidnight.now().plusDays(1));

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.halfDayPeriod");
    }

    @Test
    public void ensureSameDateAsStartAndEndDateIsValidForFullDayPeriod() {

        DateMidnight date = DateMidnight.now();

        appForm.setDayLength(DayLength.FULL);
        appForm.setStartDate(date);
        appForm.setEndDate(date);

        validator.validate(appForm, errors);

        verify(errors, never()).reject(anyString());
    }

    @Test
    public void ensureSameDateAsStartAndEndDateIsValidForMorningPeriod() {

        DateMidnight date = DateMidnight.now();

        appForm.setDayLength(DayLength.MORNING);
        appForm.setStartDate(date);
        appForm.setEndDate(date);

        validator.validate(appForm, errors);

        verify(errors, never()).reject(anyString());
    }

    @Test
    public void ensureSameDateAsStartAndEndDateIsValidForNoonPeriod() {

        DateMidnight date = DateMidnight.now();

        appForm.setDayLength(DayLength.NOON);
        appForm.setStartDate(date);
        appForm.setEndDate(date);

        validator.validate(appForm, errors);

        verify(errors, never()).reject(anyString());
    }

    // Validate period (time) ------------------------------------------------------------------------------------------

    @Test
    public void ensureTimeIsNotMandatory() {

        appForm.setStartTime(null);
        appForm.setEndTime(null);

        validator.validate(appForm, errors);

        verify(errors, never()).reject(anyString());
    }

    @Test
    public void ensureProvidingStartTimeWithoutEndTimeIsInvalid() {

        appForm.setStartTime(Time.valueOf("09:15:00"));
        appForm.setEndTime(null);

        validator.validate(appForm, errors);

        verify(errors).reject("error.entry.invalidPeriod");
    }

    @Test
    public void ensureProvidingEndTimeWithoutStartTimeIsInvalid() {

        appForm.setStartTime(null);
        appForm.setEndTime(Time.valueOf("09:15:00"));

        validator.validate(appForm, errors);

        verify(errors).reject("error.entry.invalidPeriod");
    }

    @Test
    public void ensureStartTimeMustBeBeforeEndTime() {

        DateMidnight date = DateMidnight.now();

        appForm.setDayLength(DayLength.MORNING);
        appForm.setStartDate(date);
        appForm.setEndDate(date);
        appForm.setStartTime(Time.valueOf("13:30:00"));
        appForm.setEndTime(Time.valueOf("09:15:00"));

        validator.validate(appForm, errors);

        verify(errors).reject("error.entry.invalidPeriod");
    }

    @Test
    public void ensureStartTimeAndEndTimeMustNotBeEquals() {

        DateMidnight date = DateMidnight.now();
        Time time = Time.valueOf("13:30:00");

        appForm.setDayLength(DayLength.MORNING);
        appForm.setStartDate(date);
        appForm.setEndDate(date);
        appForm.setStartTime(time);
        appForm.setEndTime(time);

        validator.validate(appForm, errors);

        verify(errors).reject("error.entry.invalidPeriod");
    }

    // Validate reason -------------------------------------------------------------------------------------------------

    @Test
    public void ensureReasonIsNotMandatoryForHoliday() {

        VacationType vacationType = TestDataCreator.createVacationType(VacationCategory.HOLIDAY);

        appForm.setVacationType(vacationType);
        appForm.setReason("");

        validator.validate(appForm, errors);

        verify(errors, never()).reject(anyString());
        verify(errors, never()).rejectValue(eq("reason"), anyString());
    }

    @Test
    public void ensureReasonIsNotMandatoryForUnpaidLeave() {

        VacationType vacationType = TestDataCreator.createVacationType(VacationCategory.UNPAIDLEAVE);

        appForm.setVacationType(vacationType);
        appForm.setReason("");

        validator.validate(appForm, errors);

        verify(errors, never()).reject(anyString());
        verify(errors, never()).rejectValue(eq("reason"), anyString());
    }

    @Test
    public void ensureReasonIsNotMandatoryForOvertime() {

        VacationType vacationType = TestDataCreator.createVacationType(VacationCategory.OVERTIME);

        appForm.setVacationType(vacationType);
        appForm.setReason("");

        validator.validate(appForm, errors);

        verify(errors, never()).reject(anyString());
        verify(errors, never()).rejectValue(eq("reason"), anyString());
    }

    @Test
    public void ensureReasonIsMandatoryForSpecialLeave() {

        VacationType vacationType = TestDataCreator.createVacationType(VacationCategory.SPECIALLEAVE);

        appForm.setVacationType(vacationType);
        appForm.setReason("");

        validator.validate(appForm, errors);

        verify(errors).rejectValue("reason", "application.error.missingReasonForSpecialLeave");
    }

    // Validate address ------------------------------------------------------------------------------------------------

    @Test
    public void ensureThereIsAMaximumCharLength() {

        appForm.setAddress(
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt"
            + " ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud "
            + "exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. ");

        validator.validate(appForm, errors);

        verify(errors).rejectValue("address", "error.entry.tooManyChars");
    }

    // Validate vacation days ------------------------------------------------------------------------------------------

    @Test
    public void ensureApplicationForLeaveWithZeroVacationDaysIsNotValid() {

        when(errors.hasErrors()).thenReturn(Boolean.FALSE);

        when(calendarService.getWorkDays(any(DayLength.class), any(DateMidnight.class), any(DateMidnight.class),
                    any(Person.class))).thenReturn(BigDecimal.ZERO);

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.zeroDays");

        verifyZeroInteractions(overlapService);
        verifyZeroInteractions(calculationService);
    }

    @Test
    public void ensureApplyingForLeaveWithNotEnoughVacationDaysIsNotValid() {

        appForm.setDayLength(DayLength.FULL);
        appForm.setStartDate(DateMidnight.now());
        appForm.setEndDate(DateMidnight.now());
        appForm.setVacationType(TestDataCreator.createVacationType(VacationCategory.HOLIDAY));

        when(errors.hasErrors()).thenReturn(Boolean.FALSE);

        when(calendarService.getWorkDays(any(DayLength.class), any(DateMidnight.class), any(DateMidnight.class),
                    any(Person.class))).thenReturn(BigDecimal.ONE);

        when(overlapService.checkOverlap(any(Application.class))).thenReturn(OverlapCase.NO_OVERLAPPING);

        when(calculationService.checkApplication(any(Application.class))).thenReturn(Boolean.FALSE);

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.notEnoughVacationDays");
    }

    @Test
    public void ensureApplyingHalfDayForLeaveWithNotEnoughVacationDaysIsNotValid() {

        appForm.setDayLength(DayLength.NOON);
        appForm.setStartDate(DateMidnight.now());
        appForm.setEndDate(DateMidnight.now());
        appForm.setVacationType(TestDataCreator.createVacationType(VacationCategory.HOLIDAY));

        when(errors.hasErrors()).thenReturn(Boolean.FALSE);

        when(calendarService.getWorkDays(eq(appForm.getDayLength()), eq(appForm.getStartDate()),
                    eq(appForm.getEndDate()), eq(appForm.getPerson())))
            .thenReturn(BigDecimal.ONE);

        when(overlapService.checkOverlap(any(Application.class))).thenReturn(OverlapCase.NO_OVERLAPPING);

        when(calculationService.checkApplication(any(Application.class))).thenReturn(Boolean.FALSE);

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.notEnoughVacationDays");
    }

    // Validate overlapping --------------------------------------------------------------------------------------------

    @Test
    public void ensureOverlappingApplicationForLeaveIsNotValid() {

        when(errors.hasErrors()).thenReturn(Boolean.FALSE);

        when(calendarService.getWorkDays(any(DayLength.class), any(DateMidnight.class), any(DateMidnight.class),
                    any(Person.class))).thenReturn(BigDecimal.ONE);

        when(overlapService.checkOverlap(any(Application.class))).thenReturn(OverlapCase.FULLY_OVERLAPPING);

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.overlap");

        verifyZeroInteractions(calculationService);
    }

    // Validate hours --------------------------------------------------------------------------------------------------

    @Test
    public void ensureHoursIsMandatoryForOvertime() {

        appForm.setVacationType(TestDataCreator.createVacationType(VacationCategory.OVERTIME));
        appForm.setHours(null);

        validator.validate(appForm, errors);

        verify(errors).rejectValue("hours", "application.error.missingHoursForOvertime");
    }

    @Test
    public void ensureHoursIsNotMandatoryForOtherTypesOfVacation() {

        Consumer<VacationType> assertHoursNotMandatory = (type) -> {
            appForm.setVacationType(type);
            appForm.setHours(null);

            validator.validate(appForm, errors);

            verify(errors, never()).rejectValue(eq("hours"), anyString());
        };

        VacationType holiday = TestDataCreator.createVacationType(VacationCategory.HOLIDAY);
        VacationType specialLeave = TestDataCreator.createVacationType(VacationCategory.SPECIALLEAVE);
        VacationType unpaidLeave = TestDataCreator.createVacationType(VacationCategory.UNPAIDLEAVE);

        assertHoursNotMandatory.accept(holiday);
        assertHoursNotMandatory.accept(specialLeave);
        assertHoursNotMandatory.accept(unpaidLeave);
    }

    @Test
    public void ensureHoursIsNotMandatoryForOvertimeIfOvertimeFunctionIsDeactivated() {

        settings.getWorkingTimeSettings().setOvertimeActive(false);

        appForm.setVacationType(TestDataCreator.createVacationType(VacationCategory.OVERTIME));
        appForm.setHours(null);

        validator.validate(appForm, errors);

        verify(errors, never()).rejectValue(eq("hours"), anyString());
    }

    @Test
    public void ensureHoursCanNotBeZero() {

        appForm.setHours(BigDecimal.ZERO);

        validator.validate(appForm, errors);

        verify(errors).rejectValue("hours", "application.error.invalidHoursForOvertime");
    }

    @Test
    public void ensureHoursCanNotBeNegative() {

        appForm.setHours(BigDecimal.ONE.negate());

        validator.validate(appForm, errors);

        verify(errors).rejectValue("hours", "application.error.invalidHoursForOvertime");
    }

    @Test
    public void ensureDecimalHoursAreValid() {

        appForm.setVacationType(TestDataCreator.createVacationType(VacationCategory.OVERTIME));
        appForm.setHours(new BigDecimal("0.5"));

        validator.validate(appForm, errors);

        verify(errors, never()).rejectValue(eq("hours"), anyString());
    }

    @Test
    public void ensureNoErrorMessageForMandatoryIfHoursIsNullBecauseOfTypeMismatch() {

        settings.getWorkingTimeSettings().setOvertimeActive(true);

        appForm.setVacationType(TestDataCreator.createVacationType(VacationCategory.OVERTIME));
        appForm.setHours(null);

        when(errors.hasFieldErrors("hours")).thenReturn(true);

        validator.validate(appForm, errors);

        verify(errors).hasFieldErrors("hours");
        verify(errors, never()).rejectValue("hours", "application.error.missingHoursForOvertime");
    }

    // Validate working time exists ------------------------------------------------------------------------------------

    @Test
    public void ensureWorkingTimeConfigurationMustExistForPeriodOfApplicationForLeave() {

        when(errors.hasErrors()).thenReturn(Boolean.FALSE);

        when(workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(any(Person.class),
                    eq(appForm.getStartDate()))).thenReturn(Optional.empty());

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.noValidWorkingTime");

        verify(workingTimeService)
            .getByPersonAndValidityDateEqualsOrMinorDate(appForm.getPerson(), appForm.getStartDate());
        verifyZeroInteractions(calendarService);
        verifyZeroInteractions(overlapService);
        verifyZeroInteractions(calculationService);
    }

    @Test
    public void ensureWorkingTimeConfigurationMustExistForHalfDayApplicationForLeave() {

        // Yes, this can really happen...
        appForm.setStartDate(null);
        appForm.setEndDate(null);

        appForm.setStartDate(DateMidnight.now());
        appForm.setEndDate(DateMidnight.now());
        appForm.setDayLength(DayLength.MORNING);

        when(errors.hasErrors()).thenReturn(Boolean.FALSE);

        when(workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(any(Person.class),
                    eq(appForm.getStartDate())))
            .thenReturn(Optional.empty());

        validator.validate(appForm, errors);

        verify(errors).reject("application.error.noValidWorkingTime");

        verify(workingTimeService)
            .getByPersonAndValidityDateEqualsOrMinorDate(appForm.getPerson(), appForm.getStartDate());
        verifyZeroInteractions(calendarService);
        verifyZeroInteractions(overlapService);
        verifyZeroInteractions(calculationService);
    }

    // Validate maximal overtime reduction -----------------------------------------------------------------------------

    /**
     * User tries to make an application (overtime reduction) but has not enough overtime left and minimum overtime is
     * reached.
     *
     * <p>0h overtime - 6h (application) < -5h overtime minimum</p>
     */
    @Test
    public void ensureErrorDueToMinimumOvertimeReached() {

        BigDecimal overtimeReductionHours = new BigDecimal("6");
        overtimeMinimumTest(overtimeReductionHours);
        verify(overtimeService).getLeftOvertimeForPerson(appForm.getPerson());
        verify(errors).reject("application.error.notEnoughOvertime");
    }

    /**
     * User tries to make an application (overtime reduction) but has not enough overtime left and minimum overtime is
     * reached exactly -> application is valid.
     *
     * <p>0h overtime - 5h (application) == -5h overtime minimum</p>
     */
    @Test
    public void ensureNoErrorDueToExactMinimumOvertimeReached() {

        BigDecimal overtimeReductionHours = new BigDecimal("5");
        overtimeMinimumTest(overtimeReductionHours);
        verify(overtimeService).getLeftOvertimeForPerson(appForm.getPerson());
        assertFalse(errors.hasErrors());
    }

    private void overtimeMinimumTest(BigDecimal hours) {

        VacationType vacationType = TestDataCreator.createVacationType(VacationCategory.OVERTIME);

        appForm.setHours(hours);
        appForm.setVacationType(vacationType);

        settings.getWorkingTimeSettings().setOvertimeActive(true);
        settings.getWorkingTimeSettings().setMinimumOvertime(5);

        when(overtimeService.getLeftOvertimeForPerson(any(Person.class))).thenReturn(BigDecimal.ZERO);

        validator.validate(appForm, errors);
    }
}


text:
using System;
using DlibDotNet.Dnn;
using uint8_t = System.Byte;
using uint16_t = System.UInt16;
using uint32_t = System.UInt32;
using int8_t = System.SByte;
using int16_t = System.Int16;
using int32_t = System.Int32;

// ReSharper disable once CheckNamespace
namespace DlibDotNet
{

    public static partial class Dlib
    {

        public static DPoint InputTensorToOutputTensor(Net net, DPoint point)
        {
            if (net == null)
                throw new ArgumentNullException(nameof(net));

            net.ThrowIfDisposed();
            return net.InputTensorToOutputTensor(point);
        }

        public static void NetToXml(Net net, string filename)
        {
            if (net == null)
                throw new ArgumentNullException(nameof(net));
            if (string.IsNullOrWhiteSpace(filename))
                throw new ArgumentException();

            net.ThrowIfDisposed();
            net.NetToXml(filename);
        }

    }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CyPhyReliabilityAnalysis
{
    public partial class MainForm : Form
    {
        private CyPhyReliabilityAnalysisSettings settings;
        private double angularMin;
        private double angularMax;
        private double gussetMin;
        private double gussetMax;
        private double angularThickness;
        private double gussetThickness;

        public MainForm(CyPhyReliabilityAnalysisSettings oldSettings)
        {
            InitializeComponent();
            this.settings = oldSettings;
            this.angularThickness = this.settings.AngularThickness;
            this.gussetThickness = this.settings.GussetThickness;
            if (this.settings.Material == "Steel")
            {
                this.cbMaterial.SelectedIndex = 0;
            }
            else
            {
                this.cbMaterial.SelectedIndex = 1;
            }

            this.cbSize.SelectedIndex = this.settings.Size - 1;
        }

        private bool SaveSettings()
        {
            if (this.angularThickness < this.angularMin || this.angularThickness > this.angularMax ||
                this.gussetThickness < this.gussetMin || this.gussetThickness > this.gussetMax)
            {
                MessageBox.Show("Entered thicknesses are not within given ranges!", "Invalid values", MessageBoxButtons.OK);
                return false;
            }

            this.settings.AngularThickness = this.angularThickness;
            this.settings.GussetThickness = this.gussetThickness;
            this.settings.Material = this.cbMaterial.SelectedItem.ToString();
            this.settings.Size = this.cbSize.SelectedIndex + 1;

            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (SaveSettings())
            {
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }

        private void tbAngular_TextChanged(object sender, EventArgs e)
        {
            double value;
            if (double.TryParse(this.tbAngular.Text, out value))
            {
                this.angularThickness = value;
            }
            else
            {
                this.angularThickness = -1;
            }

            if (this.angularThickness < this.angularMin || this.angularThickness > this.angularMax)
            {
                this.lblAngular.ForeColor = Color.Red;
                this.lblAngular.Font = new Font(this.lblAngular.Font, FontStyle.Bold);
            }
            else
            {
                this.lblAngular.ForeColor = Color.Black;
                this.lblAngular.Font = new Font(this.lblAngular.Font, FontStyle.Regular);
            }
        }

        private void tbGusset_TextChanged(object sender, EventArgs e)
        {
            double value;
            if (double.TryParse(this.tbGusset.Text, out value))
            {
                this.gussetThickness = value;
            }
            else
            {
                this.gussetThickness = -1;
            }

            if (this.gussetThickness < this.gussetMin || this.gussetThickness > this.gussetMax)
            {
                this.lblGusset.ForeColor = Color.Red;
                this.lblGusset.Font = new Font(this.lblGusset.Font, FontStyle.Bold);
            }
            else
            {
                this.lblGusset.ForeColor = Color.Black;
                this.lblGusset.Font = new Font(this.lblGusset.Font, FontStyle.Regular);
            }
        }

        private void cbMaterial_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbMaterial.SelectedIndex == 0)
            {
                // Steel
                this.angularMin = 10.16;
                this.angularMax = 20.32;
                this.gussetMin = 3.81;
                this.gussetMax = 8.89;
            }
            else
            {
                // Aluminium
                this.angularMin = 17.78;
                this.angularMax = 22.86;
                this.gussetMin = 12.7;
                this.gussetMax = 17.78;
            }

            if (this.angularThickness < this.angularMin || this.angularThickness > this.angularMax)
            {
                this.angularThickness = this.angularMin;
            }

            if (this.gussetThickness < this.gussetMin || this.gussetThickness > this.gussetMax)
            {
                this.gussetThickness = this.gussetMin;
            }

            this.lblAngular.Text = string.Format("min={0}, max={1}", this.angularMin, this.angularMax);
            this.lblAngular.ForeColor = Color.Black;
            this.lblAngular.Font = new Font(this.lblAngular.Font, FontStyle.Regular);

            this.lblGusset.Text = string.Format("min={0}, max={1}", this.gussetMin, this.gussetMax);
            this.lblGusset.ForeColor = Color.Black;
            this.lblGusset.Font = new Font(this.lblGusset.Font, FontStyle.Regular);

            this.tbAngular.Text = this.angularThickness.ToString();
            this.tbGusset.Text = this.gussetThickness.ToString();
        }
    }
}


text:
import { ajax } from 'jquery';
import {
  onAjaxStartedAction,
  onAjaxFinishedAction,
} from '../actions/config';
import {
  onErrorsAction,
} from '../actions/errors';
import {
  ERROR_MSG,
} from '../constants/utils';

export const dispatcher = (data, actions, dispatch) => {
  if (Array.isArray(actions)) {
    for (let i = 0; i < actions.length; i += 1) {
      const func = actions[i];
      dispatch(func(data));
    }
  } else {
    dispatch(actions(data));
  }
};

export const ajaxCall = (method, url, inputData, actionData, actions, dispatch, resolve, reject) => {
  const data = inputData ? JSON.stringify(inputData) : null;
  dispatch(onAjaxStartedAction());
  return ajax({
    url,
    data,
    method,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
  }).done((result) => {
    const resultData = result ? Object.assign({}, result, actionData) : actionData;
    if (resolve) {
      resolve(resultData);
    }
    return dispatcher(resultData, actions, dispatch);
  }).fail(() => {
    if (reject) {
      reject(ERROR_MSG);
    }
    dispatch(onErrorsAction([ERROR_MSG]));
  }).always(() => dispatch(onAjaxFinishedAction()));
};

export const get = (url, actionData, actions, dispatch, resolve, reject) => {
  ajaxCall('GET', url, null, actionData, actions, dispatch, resolve, reject);
};

export const post = (url, data, actionData, actions, dispatch, resolve, reject) => {
  ajaxCall('POST', url, data, actionData, actions, dispatch, resolve, reject);
};

export const put = (url, data, actionData, actions, dispatch, resolve, reject) => {
  ajaxCall('PUT', url, data, actionData, actions, dispatch, resolve, reject);
};

export const del = (url, actionData, actions, dispatch, resolve, reject) => {
  ajaxCall('DELETE', url, null, actionData, actions, dispatch, resolve, reject);
};


text:
call config.bat
cd %rootDrive%:\Users\%username%\Desktop
cls


text:
namespace base {
class File;
}

namespace zip {

class WriterDelegate;

// Paths passed as span to avoid copying them.
using Paths = base::span<const base::FilePath>;

// Abstraction for file access operation required by Zip().
//
// Can be passed to the ZipParams for providing custom access to the files,
// for example over IPC.
//
// All parameters paths are expected to be relative to the source directory.
class FileAccessor {
 public:
  virtual ~FileAccessor() = default;

  struct Info {
    bool is_directory = false;
    base::Time last_modified;
  };

  // Opens files specified in |paths|.
  // Directories should be mapped to invalid files.
  virtual bool Open(Paths paths, std::vector<base::File>* files) = 0;

  // Lists contents of a directory at |path|.
  virtual bool List(const base::FilePath& path,
                    std::vector<base::FilePath>* files,
                    std::vector<base::FilePath>* subdirs) = 0;

  // Gets info about a file or directory.
  virtual bool GetInfo(const base::FilePath& path, Info* info) = 0;
};

// Progress of a ZIP creation operation.
struct Progress {
  // Total number of bytes read from files getting zipped so far.
  std::int64_t bytes = 0;

  // Number of file entries added to the ZIP so far.
  // A file entry is added after its bytes have been processed.
  int files = 0;

  // Number of directory entries added to the ZIP so far.
  // A directory entry is added before items in it.
  int directories = 0;

  // Number of errors encountered so far (files that cannot be opened,
  // directories that cannot be listed).
  int errors = 0;
};

// Prints Progress to output stream.
std::ostream& operator<<(std::ostream& out, const Progress& progress);

// Callback reporting the progress of a ZIP creation operation.
//
// This callback returns a boolean indicating whether the ZIP creation operation
// should continue. If it returns false once, then the ZIP creation operation is
// immediately cancelled and the callback won't be called again.
using ProgressCallback = base::RepeatingCallback<bool(const Progress&)>;

using FilterCallback = base::RepeatingCallback<bool(const base::FilePath&)>;

// ZIP creation parameters and options.
struct ZipParams {
  // Source directory. Ignored if |file_accessor| is set.
  base::FilePath src_dir;

  // Abstraction around file system access used to read files.
  // If left null, an implementation that accesses files directly is used.
  FileAccessor* file_accessor = nullptr;  // Not owned

  // Destination file path.
  // Either dest_file or dest_fd should be set, but not both.
  base::FilePath dest_file;

#if defined(OS_POSIX) || defined(OS_FUCHSIA)
  // Destination file passed a file descriptor.
  // Either dest_file or dest_fd should be set, but not both.
  int dest_fd = base::kInvalidPlatformFile;
#endif

  // The relative paths to the files and directories that should be included in
  // the ZIP file. If this is empty, the whole contents of |src_dir| are
  // included.
  //
  // These paths must be relative to |src_dir| and will be used as the file
  // names in the created ZIP file. All files must be under |src_dir| in the
  // file system hierarchy.
  //
  // All the paths in |src_files| are included in the created ZIP file,
  // irrespective of |include_hidden_files| and |filter_callback|.
  Paths src_files;

  // Filter used to exclude files from the ZIP file. This is only taken in
  // account when recursively adding subdirectory contents.
  FilterCallback filter_callback;

  // Optional progress reporting callback.
  ProgressCallback progress_callback;

  // Progress reporting period. The final callback is always called when the ZIP
  // creation operation completes.
  base::TimeDelta progress_period;

  // Should add hidden files? This is only taken in account when recursively
  // adding subdirectory contents.
  bool include_hidden_files = true;

  // Should recursively add subdirectory contents?
  bool recursive = false;

  // Should ignore errors when discovering files and zipping them?
  bool continue_on_error = false;
};

// Zip files specified into a ZIP archives. The source files and ZIP destination
// files (as well as other settings) are specified in |params|.
bool Zip(const ZipParams& params);

// Zip the contents of src_dir into dest_file. src_path must be a directory.
// An entry will *not* be created in the zip for the root folder -- children
// of src_dir will be at the root level of the created zip. For each file in
// src_dir, include it only if the callback |filter_cb| returns true. Otherwise
// omit it.
bool ZipWithFilterCallback(const base::FilePath& src_dir,
                           const base::FilePath& dest_file,
                           FilterCallback filter_cb);

// Convenience method for callers who don't need to set up the filter callback.
// If |include_hidden_files| is true, files starting with "." are included.
// Otherwise they are omitted.
bool Zip(const base::FilePath& src_dir,
         const base::FilePath& dest_file,
         bool include_hidden_files);

#if defined(OS_POSIX) || defined(OS_FUCHSIA)
// Zips files listed in |src_relative_paths| to destination specified by file
// descriptor |dest_fd|, without taking ownership of |dest_fd|. The paths listed
// in |src_relative_paths| are relative to the |src_dir| and will be used as the
// file names in the created zip file. All source paths must be under |src_dir|
// in the file system hierarchy.
bool ZipFiles(const base::FilePath& src_dir,
              Paths src_relative_paths,
              int dest_fd);
#endif  // defined(OS_POSIX) || defined(OS_FUCHSIA)

// Options of the Unzip function, with valid default values.
struct UnzipOptions {
  // Encoding of entry paths in the ZIP archive. By default, paths are assumed
  // to be in UTF-8.
  std::string encoding;

  // Only extract the entries for which |filter_cb| returns true. By default,
  // everything gets extracted.
  FilterCallback filter;

  // Password to decrypt the encrypted files.
  std::string password;

  // Should ignore errors when extracting files?
  bool continue_on_error = false;
};

typedef base::RepeatingCallback<std::unique_ptr<WriterDelegate>(
    const base::FilePath&)>
    WriterFactory;

typedef base::RepeatingCallback<bool(const base::FilePath&)> DirectoryCreator;

// Unzips the contents of |zip_file|, using the writers provided by
// |writer_factory|.
bool Unzip(const base::PlatformFile& zip_file,
           WriterFactory writer_factory,
           DirectoryCreator directory_creator,
           UnzipOptions options = {});

// Unzips the contents of |zip_file| into |dest_dir|.
// This function does not overwrite any existing file.
// A filename collision will result in an error.
// Therefore, |dest_dir| should initially be an empty directory.
bool Unzip(const base::FilePath& zip_file,
           const base::FilePath& dest_dir,
           UnzipOptions options = {});

}  // namespace zip

#endif  // THIRD_PARTY_ZLIB_GOOGLE_ZIP_H_


text:
if(!dojo._hasResource["dojox.encoding.tests.bits"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.encoding.tests.bits"] = true;
dojo.provide("dojox.encoding.tests.bits");
dojo.require("dojox.encoding.bits");

(function(){
	var msg1 = "The rain in Spain falls mainly on the plain.";
	var msg2 = "The rain in Spain falls mainly on the plain.1";
	var msg3 = "The rain in Spain falls mainly on the plain.ab";
	var msg4 = "The rain in Spain falls mainly on the plain.!@#";
	var dcb = dojox.encoding.bits;

	var s2b = function(s){
		var b = [];
		for(var i = 0; i < s.length; ++i){
			b.push(s.charCodeAt(i));
		}
		return b;
	};

	var b2s = function(b){
		var s = [];
		dojo.forEach(b, function(c){ s.push(String.fromCharCode(c)); });
		return s.join("");
	};

	var testOut = function(msg){
		var a = new dojox.encoding.bits.OutputStream();
		for(var i = 0; i < msg.length; ++i){
			var v = msg.charCodeAt(i);
			var j = Math.floor(Math.random() * 7) + 1;
			a.putBits(v >>> (8 - j), j);
			a.putBits(v, 8 - j);
		}
		return b2s(a.getBuffer());
	};

	var testIn = function(msg){
		var a = new dojox.encoding.bits.InputStream(s2b(msg), msg.length * 8);
		var r = [];
		for(var i = 0; i < msg.length; ++i){
			var j = Math.floor(Math.random() * 7) + 1;
			r.push((a.getBits(j) << (8 - j)) | a.getBits(8 - j));
		}
		return b2s(r);
	};

	var test = function(msg){
		var a = new dojox.encoding.bits.InputStream(s2b(msg), msg.length * 8);
		var o = new dojox.encoding.bits.OutputStream();
		while(a.getWidth() > 0){
			var w = Math.min(a.getWidth(), 3);
			o.putBits(a.getBits(w), w);
		}
		return b2s(o.getBuffer());
	};

	tests.register("dojox.encoding.tests.bits", [
		function testBitsOut1(t){ t.assertEqual(msg1, testOut(msg1)); },
		function testBitsOut2(t){ t.assertEqual(msg2, testOut(msg2)); },
		function testBitsOut3(t){ t.assertEqual(msg3, testOut(msg3)); },
		function testBitsOut4(t){ t.assertEqual(msg4, testOut(msg4)); },
		function testBitsIn1(t){ t.assertEqual(msg1, testIn(msg1)); },
		function testBitsIn2(t){ t.assertEqual(msg2, testIn(msg2)); },
		function testBitsIn3(t){ t.assertEqual(msg3, testIn(msg3)); },
		function testBitsIn4(t){ t.assertEqual(msg4, testIn(msg4)); },
		function testBits1(t){ t.assertEqual(msg1, test(msg1)); },
		function testBits2(t){ t.assertEqual(msg2, test(msg2)); },
		function testBits3(t){ t.assertEqual(msg3, test(msg3)); },
		function testBits4(t){ t.assertEqual(msg4, test(msg4)); }
	]);
})();

}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Returns all non-view and non-temp tables with sane names.
 * Prints list of non-supported tables using $OUTPUT->notification()
 *
 * @return array
 */
function upgrade_mysql_get_supported_tables() {
    global $OUTPUT, $DB;

    $tables = array();
    $patprefix = str_replace('_', '\\_', $DB->get_prefix());
    $pregprefix = preg_quote($DB->get_prefix(), '/');

    $sql = "SHOW FULL TABLES LIKE '$patprefix%'";
    $rs = $DB->get_recordset_sql($sql);
    foreach ($rs as $record) {
        $record = array_change_key_case((array)$record, CASE_LOWER);
        $type = $record['table_type'];
        unset($record['table_type']);
        $fullname = array_shift($record);

        if ($pregprefix === '') {
            $name = $fullname;
        } else {
            $count = null;
            $name = preg_replace("/^$pregprefix/", '', $fullname, -1, $count);
            if ($count !== 1) {
                continue;
            }
        }

        if (!preg_match("/^[a-z][a-z0-9_]*$/", $name)) {
            echo $OUTPUT->notification("Database table with invalid name '$fullname' detected, skipping.", 'notifyproblem');
            continue;
        }
        if ($type === 'VIEW') {
            echo $OUTPUT->notification("Unsupported database table view '$fullname' detected, skipping.", 'notifyproblem');
            continue;
        }
        $tables[$name] = $name;
    }
    $rs->close();

    return $tables;
}

/**
 * Remove all signed numbers from current database and change
 * text fields to long texts - mysql only.
 */
function upgrade_mysql_fix_unsigned_and_lob_columns() {
    // We are not using standard API for changes of column
    // because everything 'signed'-related will be removed soon.

    // If anybody already has numbers higher than signed limit the execution stops
    // and tables must be fixed manually before continuing upgrade.

    global $DB;

    if ($DB->get_dbfamily() !== 'mysql') {
        return;
    }

    $pbar = new progress_bar('mysqlconvertunsignedlobs', 500, true);

    $prefix = $DB->get_prefix();
    $tables = upgrade_mysql_get_supported_tables();

    $tablecount = count($tables);
    $i = 0;
    foreach ($tables as $table) {
        $i++;

        $changes = array();

        $sql = "SHOW COLUMNS FROM `{{$table}}`";
        $rs = $DB->get_recordset_sql($sql);
        foreach ($rs as $column) {
            $column = (object)array_change_key_case((array)$column, CASE_LOWER);
            if (stripos($column->type, 'unsigned') !== false) {
                $maxvalue = 0;
                if (preg_match('/^int/i', $column->type)) {
                    $maxvalue = 2147483647;
                } else if (preg_match('/^medium/i', $column->type)) {
                    $maxvalue = 8388607;
                } else if (preg_match('/^smallint/i', $column->type)) {
                    $maxvalue = 32767;
                } else if (preg_match('/^tinyint/i', $column->type)) {
                    $maxvalue = 127;
                }
                if ($maxvalue) {
                    // Make sure nobody is abusing our integer ranges - moodle int sizes are in digits, not bytes!!!
                    $invalidcount = $DB->get_field_sql("SELECT COUNT('x') FROM `{{$table}}` WHERE `$column->field` > :maxnumber", array('maxnumber'=>$maxvalue));
                    if ($invalidcount) {
                        throw new moodle_exception('notlocalisederrormessage', 'error', new moodle_url('/admin/'), "Database table '{$table}'' contains unsigned column '{$column->field}' with $invalidcount values that are out of allowed range, upgrade can not continue.");
                    }
                }
                $type = preg_replace('/unsigned/i', 'signed', $column->type);
                $notnull = ($column->null === 'NO') ? 'NOT NULL' : 'NULL';
                $default = (!is_null($column->default) and $column->default !== '') ? "DEFAULT '$column->default'" : '';
                $autoinc = (stripos($column->extra, 'auto_increment') !== false) ? 'AUTO_INCREMENT' : '';
                // Primary and unique not necessary here, change_database_structure does not add prefix.
                $changes[] = "MODIFY COLUMN `$column->field` $type $notnull $default $autoinc";

            } else if ($column->type === 'tinytext' or $column->type === 'mediumtext' or $column->type === 'text') {
                $notnull = ($column->null === 'NO') ? 'NOT NULL' : 'NULL';
                $default = (!is_null($column->default) and $column->default !== '') ? "DEFAULT '$column->default'" : '';
                // Primary, unique and inc are not supported for texts.
                $changes[] = "MODIFY COLUMN `$column->field` LONGTEXT $notnull $default";

            } else if ($column->type === 'tinyblob' or $column->type === 'mediumblob' or $column->type === 'blob') {
                $notnull = ($column->null === 'NO') ? 'NOT NULL' : 'NULL';
                $default = (!is_null($column->default) and $column->default !== '') ? "DEFAULT '$column->default'" : '';
                // Primary, unique and inc are not supported for blobs.
                $changes[] = "MODIFY COLUMN `$column->field` LONGBLOB $notnull $default";
            }

        }
        $rs->close();

        if ($changes) {
            // Set appropriate timeout - 1 minute per thousand of records should be enough, min 60 minutes just in case.
            $count = $DB->count_records($table, array());
            $timeout = ($count/1000)*60;
            $timeout = ($timeout < 60*60) ? 60*60 : (int)$timeout;
            upgrade_set_timeout($timeout);

            $sql = "ALTER TABLE `{$prefix}$table` ".implode(', ', $changes);
            $DB->change_database_structure($sql);
        }

        $pbar->update($i, $tablecount, "Converted unsigned/lob columns in MySQL database - $i/$tablecount.");
    }
}

/**
 * Migrate NTEXT to NVARCHAR(MAX).
 */
function upgrade_mssql_nvarcharmax() {
    global $DB;

    if ($DB->get_dbfamily() !== 'mssql') {
        return;
    }

    $pbar = new progress_bar('mssqlconvertntext', 500, true);

    $prefix = $DB->get_prefix();
    $tables = $DB->get_tables(false);

    $tablecount = count($tables);
    $i = 0;
    foreach ($tables as $table) {
        $i++;

        $columns = array();

        $sql = "SELECT column_name
                  FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE table_name = '{{$table}}' AND UPPER(data_type) = 'NTEXT'";
        $rs = $DB->get_recordset_sql($sql);
        foreach ($rs as $column) {
            $columns[] = $column->column_name;
        }
        $rs->close();

        if ($columns) {
            // Set appropriate timeout - 1 minute per thousand of records should be enough, min 60 minutes just in case.
            $count = $DB->count_records($table, array());
            $timeout = ($count/1000)*60;
            $timeout = ($timeout < 60*60) ? 60*60 : (int)$timeout;
            upgrade_set_timeout($timeout);

            $updates = array();
            foreach ($columns as $column) {
                // Change the definition.
                $sql = "ALTER TABLE {$prefix}$table ALTER COLUMN $column NVARCHAR(MAX)";
                $DB->change_database_structure($sql);
                $updates[] = "$column = $column";
            }

            // Now force the migration of text data to new optimised storage.
            $sql = "UPDATE {{$table}} SET ".implode(', ', $updates);
            $DB->execute($sql);
        }

        $pbar->update($i, $tablecount, "Converted NTEXT to NVARCHAR(MAX) columns in MS SQL Server database - $i/$tablecount.");
    }
}

/**
 * Migrate IMAGE to VARBINARY(MAX).
 */
function upgrade_mssql_varbinarymax() {
    global $DB;

    if ($DB->get_dbfamily() !== 'mssql') {
        return;
    }

    $pbar = new progress_bar('mssqlconvertimage', 500, true);

    $prefix = $DB->get_prefix();
    $tables = $DB->get_tables(false);

    $tablecount = count($tables);
    $i = 0;
    foreach ($tables as $table) {
        $i++;

        $columns = array();

        $sql = "SELECT column_name
                  FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE table_name = '{{$table}}' AND UPPER(data_type) = 'IMAGE'";
        $rs = $DB->get_recordset_sql($sql);
        foreach ($rs as $column) {
            $columns[] = $column->column_name;
        }
        $rs->close();

        if ($columns) {
            // Set appropriate timeout - 1 minute per thousand of records should be enough, min 60 minutes just in case.
            $count = $DB->count_records($table, array());
            $timeout = ($count/1000)*60;
            $timeout = ($timeout < 60*60) ? 60*60 : (int)$timeout;
            upgrade_set_timeout($timeout);

            foreach ($columns as $column) {
                // Change the definition.
                $sql = "ALTER TABLE {$prefix}$table ALTER COLUMN $column VARBINARY(MAX)";
                $DB->change_database_structure($sql);
            }

            // Binary columns should not be used, do not waste time optimising the storage.
        }

        $pbar->update($i, $tablecount, "Converted IMAGE to VARBINARY(MAX) columns in MS SQL Server database - $i/$tablecount.");
    }
}

/**
 * This upgrade script fixes the mismatches between DB fields course_modules.section
 * and course_sections.sequence. It makes sure that each module is included
 * in the sequence of at least one section.
 * Note that this script is different from admin/cli/fix_course_sortorder.php
 * in the following ways:
 * 1. It does not fix the cases when module appears several times in section(s) sequence(s) -
 *    it will be done automatically on the next viewing of the course.
 * 2. It does not remove non-existing modules from section sequences - administrator
 *    has to run the CLI script to do it.
 * 3. When this script finds an orphaned module it adds it to the section but makes hidden
 *    where CLI script does not change the visiblity specified in the course_modules table.
 */
function upgrade_course_modules_sequences() {
    global $DB;

    // Find all modules that point to the section which does not point back to this module.
    $sequenceconcat = $DB->sql_concat("','", "s.sequence", "','");
    $moduleconcat = $DB->sql_concat("'%,'", "m.id", "',%'");
    $sql = "SELECT m.id, m.course, m.section, s.sequence
        FROM {course_modules} m LEFT OUTER JOIN {course_sections} s
        ON m.course = s.course and m.section = s.id
        WHERE s.sequence IS NULL OR ($sequenceconcat NOT LIKE $moduleconcat)
        ORDER BY m.course";
    $rs = $DB->get_recordset_sql($sql);
    $sections = null;
    foreach ($rs as $cm) {
        if (!isset($sections[$cm->course])) {
            // Retrieve all sections for the course (only once for each corrupt course).
            $sections = array($cm->course =>
                    $DB->get_records('course_sections', array('course' => $cm->course),
                            'section', 'id, section, sequence, visible'));
            if (empty($sections[$cm->course])) {
                // Very odd - the course has a module in it but has no sections. Create 0-section.
                $newsection = array('sequence' => '', 'section' => 0, 'visible' => 1);
                $newsection['id'] = $DB->insert_record('course_sections',
                        $newsection + array('course' => $cm->course, 'summary' => '', 'summaryformat' => FORMAT_HTML));
                $sections[$cm->course] = array($newsection['id'] => (object)$newsection);
            }
        }
        // Attempt to find the section that has this module in it's sequence.
        // If there are several of them, pick the last because this is what get_fast_modinfo() does.
        $sectionid = null;
        foreach ($sections[$cm->course] as $section) {
            if (!empty($section->sequence) && in_array($cm->id, preg_split('/,/', $section->sequence))) {
                $sectionid = $section->id;
            }
        }
        if ($sectionid) {
            // Found the section. Update course_module to point to the correct section.
            $params = array('id' => $cm->id, 'section' => $sectionid);
            if (!$sections[$cm->course][$sectionid]->visible) {
                $params['visible'] = 0;
            }
            $DB->update_record('course_modules', $params);
        } else {
            // No section in the course has this module in it's sequence.
            if (isset($sections[$cm->course][$cm->section])) {
                // Try to add module to the section it points to (if it is valid).
                $sectionid = $cm->section;
            } else {
                // Section not found. Just add to the first available section.
                reset($sections[$cm->course]);
                $sectionid = key($sections[$cm->course]);
            }
            $newsequence = ltrim($sections[$cm->course][$sectionid]->sequence . ',' . $cm->id, ',');
            $sections[$cm->course][$sectionid]->sequence = $newsequence;
            $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $newsequence));
            // Make module invisible because it was not displayed at all before this upgrade script.
            $DB->update_record('course_modules', array('id' => $cm->id, 'section' => $sectionid, 'visible' => 0, 'visibleold' => 0));
        }
    }
    $rs->close();
    unset($sections);

    // Note that we don't need to reset course cache here because it is reset automatically after upgrade.
}

/**
 * Updates a single item (course module or course section) to transfer the
 * availability settings from the old to the new format.
 *
 * Note: We do not convert groupmembersonly for modules at present. If we did,
 * $groupmembersonly would be set to the groupmembersonly option for the
 * module. Since we don't, it will be set to 0 for modules, and 1 for sections
 * if they have a grouping.
 *
 * @param int $groupmembersonly 1 if activity has groupmembersonly option
 * @param int $groupingid Grouping id (0 = none)
 * @param int $availablefrom Available from time (0 = none)
 * @param int $availableuntil Available until time (0 = none)
 * @param int $showavailability Show availability (1) or hide activity entirely
 * @param array $availrecs Records from course_modules/sections_availability
 * @param array $fieldrecs Records from course_modules/sections_avail_fields
 */
function upgrade_availability_item($groupmembersonly, $groupingid,
        $availablefrom, $availableuntil, $showavailability,
        array $availrecs, array $fieldrecs) {
    global $CFG, $DB;
    $conditions = array();
    $shows = array();

    // Group members only condition (if enabled).
    if ($CFG->enablegroupmembersonly && $groupmembersonly) {
        if ($groupingid) {
            $conditions[] = '{"type":"grouping"' .
                    ($groupingid ? ',"id":' . $groupingid : '') . '}';
        } else {
            // No grouping specified, so allow any group.
            $conditions[] = '{"type":"group"}';
        }
        // Group members only condition was not displayed to students.
        $shows[] = 'false';

        // In the unlikely event that the site had enablegroupmembers only
        // but NOT enableavailability, we need to turn this on now.
        if (!$CFG->enableavailability) {
            set_config('enableavailability', 1);
        }
    }

    // Date conditions.
    if ($availablefrom) {
        $conditions[] = '{"type":"date","d":">=","t":' . $availablefrom . '}';
        $shows[] = $showavailability ? 'true' : 'false';
    }
    if ($availableuntil) {
        $conditions[] = '{"type":"date","d":"<","t":' . $availableuntil . '}';
        // Until dates never showed to students.
        $shows[] = 'false';
    }

    // Conditions from _availability table.
    foreach ($availrecs as $rec) {
        if (!empty($rec->sourcecmid)) {
            // Completion condition.
            $conditions[] = '{"type":"completion","cm":' . $rec->sourcecmid .
                    ',"e":' . $rec->requiredcompletion . '}';
        } else {
            // Grade condition.
            $minmax = '';
            if (!empty($rec->grademin)) {
                $minmax .= ',"min":' . sprintf('%.5f', $rec->grademin);
            }
            if (!empty($rec->grademax)) {
                $minmax .= ',"max":' . sprintf('%.5f', $rec->grademax);
            }
            $conditions[] = '{"type":"grade","id":' . $rec->gradeitemid . $minmax . '}';
        }
        $shows[] = $showavailability ? 'true' : 'false';
    }

    // Conditions from _fields table.
    foreach ($fieldrecs as $rec) {
        if (isset($rec->userfield)) {
            // Standard field.
            $fieldbit = ',"sf":' . json_encode($rec->userfield);
        } else {
            // Custom field.
            $fieldbit = ',"cf":' . json_encode($rec->shortname);
        }
        // Value is not included for certain operators.
        switch($rec->operator) {
            case 'isempty':
            case 'isnotempty':
                $valuebit = '';
                break;

            default:
                $valuebit = ',"v":' . json_encode($rec->value);
                break;
        }
        $conditions[] = '{"type":"profile","op":"' . $rec->operator . '"' .
                $fieldbit . $valuebit . '}';
        $shows[] = $showavailability ? 'true' : 'false';
    }

    // If there are some conditions, set them into database.
    if ($conditions) {
        return '{"op":"&","showc":[' . implode(',', $shows) . '],' .
                '"c":[' . implode(',', $conditions) . ']}';
    } else {
        return null;
    }
}

/**
 * Using data for a single course-module that has groupmembersonly enabled,
 * returns the new availability value that incorporates the correct
 * groupmembersonly option.
 *
 * Included as a function so that it can be shared between upgrade and restore,
 * and unit-tested.
 *
 * @param int $groupingid Grouping id for the course-module (0 if none)
 * @param string $availability Availability JSON data for the module (null if none)
 * @return string New value for availability for the module
 */
function upgrade_group_members_only($groupingid, $availability) {
    // Work out the new JSON object representing this option.
    if ($groupingid) {
        // Require specific grouping.
        $condition = (object)array('type' => 'grouping', 'id' => (int)$groupingid);
    } else {
        // No grouping specified, so require membership of any group.
        $condition = (object)array('type' => 'group');
    }

    if (is_null($availability)) {
        // If there are no conditions using the new API then just set it.
        $tree = (object)array('op' => '&', 'c' => array($condition), 'showc' => array(false));
    } else {
        // There are existing conditions.
        $tree = json_decode($availability);
        switch ($tree->op) {
            case '&' :
                // For & conditions we can just add this one.
                $tree->c[] = $condition;
                $tree->showc[] = false;
                break;
            case '!|' :
                // For 'not or' conditions we can add this one
                // but negated.
                $tree->c[] = (object)array('op' => '!&', 'c' => array($condition));
                $tree->showc[] = false;
                break;
            default:
                // For the other two (OR and NOT AND) we have to add
                // an extra level to the tree.
                $tree = (object)array('op' => '&', 'c' => array($tree, $condition),
                        'showc' => array($tree->show, false));
                // Inner trees do not have a show option, so remove it.
                unset($tree->c[0]->show);
                break;
        }
    }

    return json_encode($tree);
}

/**
 * Updates the mime-types for files that exist in the database, based on their
 * file extension.
 *
 * @param array $filetypes Array with file extension as the key, and mimetype as the value
 */
function upgrade_mimetypes($filetypes) {
    global $DB;
    $select = $DB->sql_like('filename', '?', false);
    foreach ($filetypes as $extension=>$mimetype) {
        $DB->set_field_select(
            'files',
            'mimetype',
            $mimetype,
            $select,
            array($extension)
        );
    }
}

/**
 * Marks all courses with changes in extra credit weight calculation
 *
 * Used during upgrade and in course restore process
 *
 * This upgrade script is needed because we changed the algorithm for calculating the automatic weights of extra
 * credit items and want to prevent changes in the existing student grades.
 *
 * @param int $onlycourseid
 */
function upgrade_extra_credit_weightoverride($onlycourseid = 0) {
    global $DB;

    // Find all courses that have categories in Natural aggregation method where there is at least one extra credit
    // item and at least one item with overridden weight.
    $courses = $DB->get_fieldset_sql(
        "SELECT DISTINCT gc.courseid
          FROM {grade_categories} gc
          INNER JOIN {grade_items} gi ON gc.id = gi.categoryid AND gi.weightoverride = :weightoverriden
          INNER JOIN {grade_items} gie ON gc.id = gie.categoryid AND gie.aggregationcoef = :extracredit
          WHERE gc.aggregation = :naturalaggmethod" . ($onlycourseid ? " AND gc.courseid = :onlycourseid" : ''),
        array('naturalaggmethod' => 13,
            'weightoverriden' => 1,
            'extracredit' => 1,
            'onlycourseid' => $onlycourseid,
        )
    );
    foreach ($courses as $courseid) {
        $gradebookfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
        if (!$gradebookfreeze) {
            set_config('gradebook_calculations_freeze_' . $courseid, 20150619);
        }
    }
}

/**
 * Marks all courses that require calculated grade items be updated.
 *
 * Used during upgrade and in course restore process.
 *
 * This upgrade script is needed because the calculated grade items were stuck with a maximum of 100 and could be changed.
 * This flags the courses that are affected and the grade book is frozen to retain grade integrity.
 *
 * @param int $courseid Specify a course ID to run this script on just one course.
 */
function upgrade_calculated_grade_items($courseid = null) {
    global $DB, $CFG;

    $affectedcourses = array();
    $possiblecourseids = array();
    $params = array();
    $singlecoursesql = '';
    if (isset($courseid)) {
        $singlecoursesql = "AND ns.id = :courseid";
        $params['courseid'] = $courseid;
    }
    $siteminmaxtouse = 1;
    if (isset($CFG->grade_minmaxtouse)) {
        $siteminmaxtouse = $CFG->grade_minmaxtouse;
    }
    $courseidsql = "SELECT ns.id
                      FROM (
                        SELECT c.id, coalesce(" . $DB->sql_compare_text('gs.value') . ", :siteminmax) AS gradevalue
                          FROM {course} c
                          LEFT JOIN {grade_settings} gs
                            ON c.id = gs.courseid
                           AND ((gs.name = 'minmaxtouse' AND " . $DB->sql_compare_text('gs.value') . " = '2'))
                        ) ns
                    WHERE " . $DB->sql_compare_text('ns.gradevalue') . " = '2' $singlecoursesql";
    $params['siteminmax'] = $siteminmaxtouse;
    $courses = $DB->get_records_sql($courseidsql, $params);
    foreach ($courses as $course) {
        $possiblecourseids[$course->id] = $course->id;
    }

    if (!empty($possiblecourseids)) {
        list($sql, $params) = $DB->get_in_or_equal($possiblecourseids);
        // A calculated grade item grade min != 0 and grade max != 100 and the course setting is set to
        // "Initial min and max grades".
        $coursesql = "SELECT DISTINCT courseid
                        FROM {grade_items}
                       WHERE calculation IS NOT NULL
                         AND itemtype = 'manual'
                         AND (grademax <> 100 OR grademin <> 0)
                         AND courseid $sql";
        $affectedcourses = $DB->get_records_sql($coursesql, $params);
    }

    // Check for second type of affected courses.
    // If we already have the courseid parameter set in the affectedcourses then there is no need to run through this section.
    if (!isset($courseid) || !in_array($courseid, $affectedcourses)) {
        $singlecoursesql = '';
        $params = array();
        if (isset($courseid)) {
            $singlecoursesql = "AND courseid = :courseid";
            $params['courseid'] = $courseid;
        }
        $nestedsql = "SELECT id
                        FROM {grade_items}
                       WHERE itemtype = 'category'
                         AND calculation IS NOT NULL $singlecoursesql";
        $calculatedgradecategories = $DB->get_records_sql($nestedsql, $params);
        $categoryids = array();
        foreach ($calculatedgradecategories as $key => $gradecategory) {
            $categoryids[$key] = $gradecategory->id;
        }

        if (!empty($categoryids)) {
            list($sql, $params) = $DB->get_in_or_equal($categoryids);
            // A category with a calculation where the raw grade min and the raw grade max don't match the grade min and grade max
            // for the category.
            $coursesql = "SELECT DISTINCT gi.courseid
                            FROM {grade_grades} gg, {grade_items} gi
                           WHERE gi.id = gg.itemid
                             AND (gg.rawgrademax <> gi.grademax OR gg.rawgrademin <> gi.grademin)
                             AND gi.id $sql";
            $additionalcourses = $DB->get_records_sql($coursesql, $params);
            foreach ($additionalcourses as $key => $additionalcourse) {
                if (!array_key_exists($key, $affectedcourses)) {
                    $affectedcourses[$key] = $additionalcourse;
                }
            }
        }
    }

    foreach ($affectedcourses as $affectedcourseid) {
        if (isset($CFG->upgrade_calculatedgradeitemsonlyregrade) && !($courseid)) {
            $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $affectedcourseid->courseid));
        } else {
            // Check to see if the gradebook freeze is already in affect.
            $gradebookfreeze = get_config('core', 'gradebook_calculations_freeze_' . $affectedcourseid->courseid);
            if (!$gradebookfreeze) {
                set_config('gradebook_calculations_freeze_' . $affectedcourseid->courseid, 20150627);
            }
        }
    }
}


text:
import * as WsChannel from '../model/ws-channel';
import { CardStatusListState } from './card-status-list-state';
import { KeyChainListState } from './key-chain-list-state';
import { ProgressorState } from '../components/controls';
import { AssistentState } from '../components/assistent';
import { createMuiTheme, Theme } from '@material-ui/core';

export class AppState {
      public readonly channel: WsChannel.Dispatch;
      public readonly cardStatusListState: CardStatusListState;
      public readonly keyChainListState: KeyChainListState;
      public readonly progressorState: ProgressorState;
      public readonly assistentState: AssistentState;
      public readonly appTheme: Theme;

      public static create(): AppState {
            return new AppState();
      }

      private constructor() {
            this.channel = WsChannel.Dispatch.create();
            this.cardStatusListState = new CardStatusListState(this.channel);
            this.keyChainListState = new KeyChainListState(this.channel);
            this.progressorState = new ProgressorState(this.channel);
            this.assistentState = new AssistentState();
            this.appTheme = createMuiTheme({ typography: { useNextVariants: true } });
      }
}


text:
package org.usfirst.frc.team1736.lib.WebServer;

import javax.servlet.annotation.WebServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

@SuppressWarnings("serial")
@WebServlet(name = "Casserole Driver Data Streamer Servlet", urlPatterns = {"/driverviewstream"})
class CasseroleDriverViewStreamerServlet extends WebSocketServlet {

    @Override
    public void configure(WebSocketServletFactory factory) {
        factory.getPolicy().setIdleTimeout(10000);
        factory.register(CasseroleDriverViewStreamerSocket.class);
    }
}


text:
const expect = require('expect.js')
import fn from '../core/fn'
import db from '../core/db'
import hal from '../core/hal'
import pipeline from '../core/pipeline'
import authn from '../middleware/authn'
import authr from '../middleware/authr'
import resolver from '../middleware/resolver'
import invoker from '../middleware/invoker'
import Apple from './apple'
import server from './http-mock'

db.init('./datastore')
db.clear()

const apiEndPoint = server.createEndPoint(
  pipeline
    .use(authn.func)
    .use(resolver(Apple))
    .use(authr.func)
    .use(invoker.func)
    .use(hal.func)
)
const headers = { accept: 'application/hal+json' }

fn.log('------ Run Apple tests -----')
fn.log('test bad get all apples')
var all = apiEndPoint.GET('bad', headers)
expect(all.statusCode).to.be(500)
expect(all.data.Error).to.be('type resolver error')

fn.log('test get all - empty set')
all = apiEndPoint.GET('/api/apples/', headers)
expect(all.statusCode).to.be(200)
expect(all.data.listLinkRels().length).to.be(2)
expect(fn.contains('self', all.data.listLinkRels())).to.be(true)
expect(fn.contains('create', all.data.listLinkRels())).to.be(true)

fn.log('test create apple 1')
var link = all.data.getLink('create')
var apple = apiEndPoint[link.method](link.href, headers, {
  weight: 10,
  color: 'red'
})
expect(apple.data.listLinkRels().length).to.be(3)
expect(apple.data.weight).to.be(10)
expect(fn.contains('self', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('grow', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('toss', apple.data.listLinkRels())).to.be(true)

fn.log('test create apple 2')
link = all.data.getLink('create')
apple = apiEndPoint[link.method](link.href, headers, {
  weight: 20,
  color: 'green'
})
expect(apple.data.listLinkRels().length).to.be(3)
expect(apple.data.weight).to.be(20)
expect(fn.contains('self', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('grow', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('toss', apple.data.listLinkRels())).to.be(true)

fn.log('test create apple 3 - full page size')
link = all.data.getLink('create')
apple = apiEndPoint[link.method](link.href, headers, {
  weight: 20,
  color: 'orange'
})
expect(apple.data.listLinkRels().length).to.be(3)
expect(apple.data.weight).to.be(20)
expect(fn.contains('self', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('grow', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('toss', apple.data.listLinkRels())).to.be(true)

fn.log('test create apple 4 - page 2')
link = all.data.getLink('create')
apple = apiEndPoint[link.method](link.href, headers, {
  weight: 20,
  color: 'blue'
})
expect(apple.data.listLinkRels().length).to.be(3)
expect(apple.data.weight).to.be(20)
expect(fn.contains('self', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('grow', apple.data.listLinkRels())).to.be(true)
expect(fn.contains('toss', apple.data.listLinkRels())).to.be(true)

fn.log('test if create sucessful')
var self = apiEndPoint.GET(apple.data.getLink('self').href, headers)
expect(self.data.weight).to.be(20)
expect(self.data.listLinkRels().length).to.be(3)
expect(fn.contains('self', self.data.listLinkRels())).to.be(true)
expect(fn.contains('grow', self.data.listLinkRels())).to.be(true)
expect(fn.contains('toss', self.data.listLinkRels())).to.be(true)

fn.log('test get all - 2 pages')
all = apiEndPoint.GET('/api/apples/', headers)
expect(all.statusCode).to.be(200)
expect(all.data.listLinkRels().length).to.be(5)
expect(fn.contains('create', all.data.listLinkRels())).to.be(true)

fn.log("call 'grow' api (post - with id and propertis that don't exist on entity")
link = self.data.getLink('grow')
var appleGrown = apiEndPoint[link.method](link.href, headers, {
  weightIncr: 230
})
expect(appleGrown.data.weight).to.be(250)
expect(appleGrown.data.listLinkRels().length).to.be(3)
expect(fn.contains('self', appleGrown.data.listLinkRels())).to.be(true)
expect(fn.contains('eat', appleGrown.data.listLinkRels())).to.be(true)
expect(fn.contains('toss', appleGrown.data.listLinkRels())).to.be(true)

fn.log("call 'eat' api (full put)")
link = appleGrown.data.getLink('eat')
var appleEaten = apiEndPoint[link.method](link.href, headers, {
  weight: 0,
  color: 'orange'
})
expect(appleEaten.data.weight).to.be(0)
expect(appleEaten.data.listLinkRels().length).to.be(2)
expect(fn.contains('self', appleEaten.data.listLinkRels())).to.be(true)

fn.log("test api whitelisting - should not be able to call 'grow' in this state")
link = appleGrown.data.getLink('eat')
var notAllowedResult = apiEndPoint[link.method](link.href, headers, {
  weight: 0,
  color: '<or></or>ange'
})
expect(notAllowedResult.statusCode).to.be(405)

fn.log('test get before toss')
all = apiEndPoint.GET('/api/apples/', headers)
// fn.log(JSON.stringify(all.data))
var embeds = all.data.getEmbeds('apples')
expect(embeds.length).to.be(3) // page 1

// todo: get page 2 and a test that is has 1 embed

fn.log('test toss one of the apples')
link = appleEaten.data.getLink('toss')
var result = apiEndPoint[link.method](link.href, headers, {})

fn.log('test get after toss')
all = apiEndPoint.GET('/api/apples/', headers)
// fn.log(JSON.stringify(all.data))
embeds = all.data.getEmbeds('apples')
expect(embeds.length).to.be(3)

// - cleanup after
db.clear()


text:
export ZK_HOST=

# Push the sample data file to HDFS
hdfs dfs -put data/crimes_sample1000.csv

# Use the Geohash Pig UDF to compute the geohash column and add to the csv file
pig -f scripts/add_geohash.pig

# Create the CRIMES table in Phoenix
/usr/hdp/current/phoenix-client/bin/psql.py $ZK_HOST:2181:/hbase-unsecure scripts/create_table.sql

# Load the crime data with geohash via Pig
pig -f scripts/ingest_crime_data.pig -param ZK_HOST=$ZK_HOST


text:
{{form.title}}

      <form ng-submit="processPasswordReset($event)" ng-show="form.show_form">

          {{form.success.form}}

            {{form.error.form}}

            New password
            <input type="password" class="form-control" ng-class="{'is-invalid': form.error.newPassword}" id="new-password" placeholder="New password" ng-model="form.passwordReset.newPassword" ng-keyup="formChanged($event)" ng-changed="formChanged($event)">

{{form.error.newPassword}}

            Confirm password
            <input type="password" class="form-control" ng-class="{'is-invalid': form.error.confirmPassword}" id="confirm-password" placeholder="Confirm password" ng-model="form.passwordReset.confirmPassword" ng-keyup="formChanged($event)" ng-changed="formChanged($event)">

{{form.error.confirmPassword}}

            <button type="submit" class="btn btn-primary mr-4">Save</button>

      </form>

          Your password reset link has expired.
          Please request a new link.

        You are already logged in!


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Cake.Common.Tests.Fixtures.Build;
using Xunit;

namespace Cake.Common.Tests.Unit.Build.GitHubActions.Data
{
    public sealed class GitHubActionsEnvironmentInfoTests
    {
        public sealed class TheHomeProperty
        {
            [Fact]
            public void Should_Return_Correct_Values()
            {
                // Given
                var info = new GitHubActionsInfoFixture().CreateEnvironmentInfo();

                // When
                var result = info.Home.FullPath;

                // Then
                Assert.Equal("/home/runner", result);
            }
        }

        public sealed class TheWorkflowProperty
        {
            [Fact]
            public void Should_Return_Correct_Value()
            {
                // Given
                var info = new GitHubActionsInfoFixture().CreateEnvironmentInfo();

                // When
                var result = info.Workflow;

                // Then
                Assert.NotNull(result);
            }
        }

        public sealed class ThePullRequestProperty
        {
            [Fact]
            public void Should_Return_Correct_Value()
            {
                // Given
                var info = new GitHubActionsInfoFixture().CreateEnvironmentInfo();

                // When
                var result = info.PullRequest;

                // Then
                Assert.NotNull(result);
            }
        }
    }
}