text:
package org.joda.time;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.joda.time.chrono.BuddhistChronology;
import org.joda.time.chrono.CopticChronology;
import org.joda.time.chrono.GJChronology;
import org.joda.time.chrono.GregorianChronology;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.chrono.LenientChronology;
import org.joda.time.chrono.StrictChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * This class is a Junit unit test for LocalDate.
 *
 * @author Stephen Colebourne
 */
public class TestLocalDate_Basics extends TestCase {

    private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris");
    private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London");
    private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo");
    private static final DateTimeZone NEW_YORK = DateTimeZone.forID("America/New_York");
//    private static final int OFFSET = 1;
    private static final GJChronology GJ_UTC = GJChronology.getInstanceUTC();
    private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS);
    private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON);
    private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO);
    private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC();
//    private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS);
    private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON);
    private static final Chronology ISO_NEW_YORK = ISOChronology.getInstance(NEW_YORK);
//    private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO);
//    private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC();
    private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS);
    private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON);
    private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO);
//    private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC();

    /** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */
    private static long CUTOVER_GAZA = 1175378400000L;
    private static int OFFSET_GAZA = 7200000;  // +02:00
    private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600);

    private long TEST_TIME_NOW =
            (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;

//    private long TEST_TIME1 =
//        (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY
//        + 12L * DateTimeConstants.MILLIS_PER_HOUR
//        + 24L * DateTimeConstants.MILLIS_PER_MINUTE;
//
//    private long TEST_TIME2 =
//        (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY
//        + 14L * DateTimeConstants.MILLIS_PER_HOUR
//        + 28L * DateTimeConstants.MILLIS_PER_MINUTE;

    private DateTimeZone zone = null;

    private Locale systemDefaultLocale = null;

    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }

    public static TestSuite suite() {
        return new TestSuite(TestLocalDate_Basics.class);
    }

    public TestLocalDate_Basics(String name) {
        super(name);
    }

    protected void setUp() throws Exception {
        DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
        zone = DateTimeZone.getDefault();
        DateTimeZone.setDefault(LONDON);
        systemDefaultLocale = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);
    }

    protected void tearDown() throws Exception {
        DateTimeUtils.setCurrentMillisSystem();
        DateTimeZone.setDefault(zone);
        zone = null;
        Locale.setDefault(systemDefaultLocale);
        systemDefaultLocale = null;
    }

    //-----------------------------------------------------------------------
    public void testGet_DateTimeFieldType() {
        LocalDate test = new LocalDate();
        assertEquals(1970, test.get(DateTimeFieldType.year()));
        assertEquals(6, test.get(DateTimeFieldType.monthOfYear()));
        assertEquals(9, test.get(DateTimeFieldType.dayOfMonth()));
        assertEquals(2, test.get(DateTimeFieldType.dayOfWeek()));
        assertEquals(160, test.get(DateTimeFieldType.dayOfYear()));
        assertEquals(24, test.get(DateTimeFieldType.weekOfWeekyear()));
        assertEquals(1970, test.get(DateTimeFieldType.weekyear()));
        try {
            test.get(null);
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            test.get(DateTimeFieldType.hourOfDay());
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    public void testSize() {
        LocalDate test = new LocalDate();
        assertEquals(3, test.size());
    }

    public void testGetFieldType_int() {
        LocalDate test = new LocalDate(COPTIC_PARIS);
        assertSame(DateTimeFieldType.year(), test.getFieldType(0));
        assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(1));
        assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(2));
        try {
            test.getFieldType(-1);
        } catch (IndexOutOfBoundsException ex) {}
        try {
            test.getFieldType(3);
        } catch (IndexOutOfBoundsException ex) {}
    }

    public void testGetFieldTypes() {
        LocalDate test = new LocalDate(COPTIC_PARIS);
        DateTimeFieldType[] fields = test.getFieldTypes();
        assertSame(DateTimeFieldType.year(), fields[0]);
        assertSame(DateTimeFieldType.monthOfYear(), fields[1]);
        assertSame(DateTimeFieldType.dayOfMonth(), fields[2]);
        assertNotSame(test.getFieldTypes(), test.getFieldTypes());
    }

    public void testGetField_int() {
        LocalDate test = new LocalDate(COPTIC_PARIS);
        assertSame(COPTIC_UTC.year(), test.getField(0));
        assertSame(COPTIC_UTC.monthOfYear(), test.getField(1));
        assertSame(COPTIC_UTC.dayOfMonth(), test.getField(2));
        try {
            test.getField(-1);
        } catch (IndexOutOfBoundsException ex) {}
        try {
            test.getField(3);
        } catch (IndexOutOfBoundsException ex) {}
    }

    public void testGetFields() {
        LocalDate test = new LocalDate(COPTIC_PARIS);
        DateTimeField[] fields = test.getFields();
        assertSame(COPTIC_UTC.year(), fields[0]);
        assertSame(COPTIC_UTC.monthOfYear(), fields[1]);
        assertSame(COPTIC_UTC.dayOfMonth(), fields[2]);
        assertNotSame(test.getFields(), test.getFields());
    }

    public void testGetValue_int() {
        LocalDate test = new LocalDate();
        assertEquals(1970, test.getValue(0));
        assertEquals(6, test.getValue(1));
        assertEquals(9, test.getValue(2));
        try {
            test.getValue(-1);
        } catch (IndexOutOfBoundsException ex) {}
        try {
            test.getValue(3);
        } catch (IndexOutOfBoundsException ex) {}
    }

    public void testGetValues() {
        LocalDate test = new LocalDate();
        int[] values = test.getValues();
        assertEquals(1970, values[0]);
        assertEquals(6, values[1]);
        assertEquals(9, values[2]);
        assertNotSame(test.getValues(), test.getValues());
    }

    public void testIsSupported_DateTimeFieldType() {
        LocalDate test = new LocalDate(COPTIC_PARIS);
        assertEquals(true, test.isSupported(DateTimeFieldType.year()));
        assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear()));
        assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth()));
        assertEquals(true, test.isSupported(DateTimeFieldType.dayOfWeek()));
        assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear()));
        assertEquals(true, test.isSupported(DateTimeFieldType.weekOfWeekyear()));
        assertEquals(true, test.isSupported(DateTimeFieldType.weekyear()));
        assertEquals(true, test.isSupported(DateTimeFieldType.yearOfCentury()));
        assertEquals(true, test.isSupported(DateTimeFieldType.yearOfEra()));
        assertEquals(true, test.isSupported(DateTimeFieldType.centuryOfEra()));
        assertEquals(true, test.isSupported(DateTimeFieldType.weekyearOfCentury()));
        assertEquals(true, test.isSupported(DateTimeFieldType.era()));
        assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay()));
        assertEquals(false, test.isSupported((DateTimeFieldType) null));
    }

    public void testIsSupported_DurationFieldType() {
        LocalDate test = new LocalDate(1970, 6, 9);
        assertEquals(false, test.isSupported(DurationFieldType.eras()));
        assertEquals(true, test.isSupported(DurationFieldType.centuries()));
        assertEquals(true, test.isSupported(DurationFieldType.years()));
        assertEquals(true, test.isSupported(DurationFieldType.months()));
        assertEquals(true, test.isSupported(DurationFieldType.weekyears()));
        assertEquals(true, test.isSupported(DurationFieldType.weeks()));
        assertEquals(true, test.isSupported(DurationFieldType.days()));

        assertEquals(false, test.isSupported(DurationFieldType.hours()));
        assertEquals(false, test.isSupported((DurationFieldType) null));
    }

    @SuppressWarnings("deprecation")
    public void testEqualsHashCode() {
        LocalDate test1 = new LocalDate(1970, 6, 9, COPTIC_PARIS);
        LocalDate test2 = new LocalDate(1970, 6, 9, COPTIC_PARIS);
        assertEquals(true, test1.equals(test2));
        assertEquals(true, test2.equals(test1));
        assertEquals(true, test1.equals(test1));
        assertEquals(true, test2.equals(test2));
        assertEquals(true, test1.hashCode() == test2.hashCode());
        assertEquals(true, test1.hashCode() == test1.hashCode());
        assertEquals(true, test2.hashCode() == test2.hashCode());

        LocalDate test3 = new LocalDate(1971, 6, 9);
        assertEquals(false, test1.equals(test3));
        assertEquals(false, test2.equals(test3));
        assertEquals(false, test3.equals(test1));
        assertEquals(false, test3.equals(test2));
        assertEquals(false, test1.hashCode() == test3.hashCode());
        assertEquals(false, test2.hashCode() == test3.hashCode());

        assertEquals(false, test1.equals("Hello"));
        assertEquals(true, test1.equals(new MockInstant()));
        assertEquals(true, test1.equals(new YearMonthDay(1970, 6, 9, COPTIC_PARIS)));
        assertEquals(true, test1.hashCode() == new YearMonthDay(1970, 6, 9, COPTIC_PARIS).hashCode());
        assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE));
    }

    class MockInstant extends MockPartial {
        public Chronology getChronology() {
            return COPTIC_UTC;
        }
        public DateTimeField[] getFields() {
            return new DateTimeField[] {
                COPTIC_UTC.year(),
                COPTIC_UTC.monthOfYear(),
                COPTIC_UTC.dayOfMonth(),
            };
        }
        public int[] getValues() {
            return new int[] {1970, 6, 9};
        }
    }

    public void testEqualsHashCodeLenient() {
        LocalDate test1 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS));
        LocalDate test2 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS));
        assertEquals(true, test1.equals(test2));
        assertEquals(true, test2.equals(test1));
        assertEquals(true, test1.equals(test1));
        assertEquals(true, test2.equals(test2));
        assertEquals(true, test1.hashCode() == test2.hashCode());
        assertEquals(true, test1.hashCode() == test1.hashCode());
        assertEquals(true, test2.hashCode() == test2.hashCode());
    }

    public void testEqualsHashCodeStrict() {
        LocalDate test1 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS));
        LocalDate test2 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS));
        assertEquals(true, test1.equals(test2));
        assertEquals(true, test2.equals(test1));
        assertEquals(true, test1.equals(test1));
        assertEquals(true, test2.equals(test2));
        assertEquals(true, test1.hashCode() == test2.hashCode());
        assertEquals(true, test1.hashCode() == test1.hashCode());
        assertEquals(true, test2.hashCode() == test2.hashCode());
    }

    public void testEqualsHashCodeAPI() {
        LocalDate test = new LocalDate(1970, 6, 9, COPTIC_PARIS);
        int expected = 157;
        expected = 23 * expected + 1970;
        expected = 23 * expected + COPTIC_UTC.year().getType().hashCode();
        expected = 23 * expected + 6;
        expected = 23 * expected + COPTIC_UTC.monthOfYear().getType().hashCode();
        expected = 23 * expected + 9;
        expected = 23 * expected + COPTIC_UTC.dayOfMonth().getType().hashCode();
        expected += COPTIC_UTC.hashCode();
        assertEquals(expected, test.hashCode());
    }

    //-----------------------------------------------------------------------
    @SuppressWarnings("deprecation")
    public void testCompareTo() {
        LocalDate test1 = new LocalDate(2005, 6, 2);
        LocalDate test1a = new LocalDate(2005, 6, 2);
        assertEquals(0, test1.compareTo(test1a));
        assertEquals(0, test1a.compareTo(test1));
        assertEquals(0, test1.compareTo(test1));
        assertEquals(0, test1a.compareTo(test1a));

        LocalDate test2 = new LocalDate(2005, 7, 2);
        assertEquals(-1, test1.compareTo(test2));
        assertEquals(+1, test2.compareTo(test1));

        LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
        assertEquals(-1, test1.compareTo(test3));
        assertEquals(+1, test3.compareTo(test1));
        assertEquals(0, test3.compareTo(test2));

        DateTimeFieldType[] types = new DateTimeFieldType[] {
            DateTimeFieldType.year(),
            DateTimeFieldType.monthOfYear(),
            DateTimeFieldType.dayOfMonth(),
        };
        int[] values = new int[] {2005, 6, 2};
        Partial p = new Partial(types, values);
        assertEquals(0, test1.compareTo(p));
        assertEquals(0, test1.compareTo(new YearMonthDay(2005, 6, 2)));
        try {
            test1.compareTo(null);
            fail();
        } catch (NullPointerException ex) {}
//        try {
//            test1.compareTo(new Date());
//            fail();
//        } catch (ClassCastException ex) {}
        try {
            test1.compareTo(new TimeOfDay());
            fail();
        } catch (ClassCastException ex) {}
        Partial partial = new Partial()
            .with(DateTimeFieldType.centuryOfEra(), 1)
            .with(DateTimeFieldType.halfdayOfDay(), 0)
            .with(DateTimeFieldType.dayOfMonth(), 9);
        try {
            new LocalDate(1970, 6, 9).compareTo(partial);
            fail();
        } catch (ClassCastException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testIsEqual_LocalDate() {
        LocalDate test1 = new LocalDate(2005, 6, 2);
        LocalDate test1a = new LocalDate(2005, 6, 2);
        assertEquals(true, test1.isEqual(test1a));
        assertEquals(true, test1a.isEqual(test1));
        assertEquals(true, test1.isEqual(test1));
        assertEquals(true, test1a.isEqual(test1a));

        LocalDate test2 = new LocalDate(2005, 7, 2);
        assertEquals(false, test1.isEqual(test2));
        assertEquals(false, test2.isEqual(test1));

        LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
        assertEquals(false, test1.isEqual(test3));
        assertEquals(false, test3.isEqual(test1));
        assertEquals(true, test3.isEqual(test2));

        try {
            new LocalDate(2005, 7, 2).isEqual(null);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testIsBefore_LocalDate() {
        LocalDate test1 = new LocalDate(2005, 6, 2);
        LocalDate test1a = new LocalDate(2005, 6, 2);
        assertEquals(false, test1.isBefore(test1a));
        assertEquals(false, test1a.isBefore(test1));
        assertEquals(false, test1.isBefore(test1));
        assertEquals(false, test1a.isBefore(test1a));

        LocalDate test2 = new LocalDate(2005, 7, 2);
        assertEquals(true, test1.isBefore(test2));
        assertEquals(false, test2.isBefore(test1));

        LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
        assertEquals(true, test1.isBefore(test3));
        assertEquals(false, test3.isBefore(test1));
        assertEquals(false, test3.isBefore(test2));

        try {
            new LocalDate(2005, 7, 2).isBefore(null);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testIsAfter_LocalDate() {
        LocalDate test1 = new LocalDate(2005, 6, 2);
        LocalDate test1a = new LocalDate(2005, 6, 2);
        assertEquals(false, test1.isAfter(test1a));
        assertEquals(false, test1a.isAfter(test1));
        assertEquals(false, test1.isAfter(test1));
        assertEquals(false, test1a.isAfter(test1a));

        LocalDate test2 = new LocalDate(2005, 7, 2);
        assertEquals(false, test1.isAfter(test2));
        assertEquals(true, test2.isAfter(test1));

        LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
        assertEquals(false, test1.isAfter(test3));
        assertEquals(true, test3.isAfter(test1));
        assertEquals(false, test3.isAfter(test2));

        try {
            new LocalDate(2005, 7, 2).isAfter(null);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testWithField_DateTimeFieldType_int_1() {
        LocalDate test = new LocalDate(2004, 6, 9);
        LocalDate result = test.withField(DateTimeFieldType.year(), 2006);

        assertEquals(new LocalDate(2004, 6, 9), test);
        assertEquals(new LocalDate(2006, 6, 9), result);
    }

    public void testWithField_DateTimeFieldType_int_2() {
        LocalDate test = new LocalDate(2004, 6, 9);
        try {
            test.withField(null, 6);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    public void testWithField_DateTimeFieldType_int_3() {
        LocalDate test = new LocalDate(2004, 6, 9);
        try {
            test.withField(DateTimeFieldType.hourOfDay(), 6);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    public void testWithField_DateTimeFieldType_int_4() {
        LocalDate test = new LocalDate(2004, 6, 9);
        LocalDate result = test.withField(DateTimeFieldType.year(), 2004);
        assertEquals(new LocalDate(2004, 6, 9), test);
        assertSame(test, result);
    }

    //-----------------------------------------------------------------------
    public void testWithFieldAdded_DurationFieldType_int_1() {
        LocalDate test = new LocalDate(2004, 6, 9);
        LocalDate result = test.withFieldAdded(DurationFieldType.years(), 6);

        assertEquals(new LocalDate(2004, 6, 9), test);
        assertEquals(new LocalDate(2010, 6, 9), result);
    }

    public void testWithFieldAdded_DurationFieldType_int_2() {
        LocalDate test = new LocalDate(2004, 6, 9);
        try {
            test.withFieldAdded(null, 0);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    public void testWithFieldAdded_DurationFieldType_int_3() {
        LocalDate test = new LocalDate(2004, 6, 9);
        try {
            test.withFieldAdded(null, 6);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    public void testWithFieldAdded_DurationFieldType_int_4() {
        LocalDate test = new LocalDate(2004, 6, 9);
        LocalDate result = test.withFieldAdded(DurationFieldType.years(), 0);
        assertSame(test, result);
    }

    public void testWithFieldAdded_DurationFieldType_int_5() {
        LocalDate test = new LocalDate(2004, 6, 9);
        try {
            test.withFieldAdded(DurationFieldType.hours(), 6);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testPlus_RP() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.plus(new Period(1, 2, 3, 4, 29, 6, 7, 8));
        LocalDate expected = new LocalDate(2003, 7, 28, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.plus((ReadablePeriod) null);
        assertSame(test, result);
    }

    public void testPlusYears_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.plusYears(1);
        LocalDate expected = new LocalDate(2003, 5, 3, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.plusYears(0);
        assertSame(test, result);
    }

    public void testPlusMonths_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.plusMonths(1);
        LocalDate expected = new LocalDate(2002, 6, 3, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.plusMonths(0);
        assertSame(test, result);
    }

    public void testPlusWeeks_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.plusWeeks(1);
        LocalDate expected = new LocalDate(2002, 5, 10, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.plusWeeks(0);
        assertSame(test, result);
    }

    public void testPlusDays_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.plusDays(1);
        LocalDate expected = new LocalDate(2002, 5, 4, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.plusDays(0);
        assertSame(test, result);
    }

    //-----------------------------------------------------------------------
    public void testMinus_RP() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1));

        // TODO breaks because it subtracts millis now, and thus goes
        // into the previous day

        LocalDate expected = new LocalDate(2001, 3, 26, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.minus((ReadablePeriod) null);
        assertSame(test, result);
    }

    public void testMinusYears_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.minusYears(1);
        LocalDate expected = new LocalDate(2001, 5, 3, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.minusYears(0);
        assertSame(test, result);
    }

    public void testMinusMonths_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.minusMonths(1);
        LocalDate expected = new LocalDate(2002, 4, 3, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.minusMonths(0);
        assertSame(test, result);
    }

    public void testMinusWeeks_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.minusWeeks(1);
        LocalDate expected = new LocalDate(2002, 4, 26, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.minusWeeks(0);
        assertSame(test, result);
    }

    public void testMinusDays_int() {
        LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
        LocalDate result = test.minusDays(1);
        LocalDate expected = new LocalDate(2002, 5, 2, BUDDHIST_LONDON);
        assertEquals(expected, result);

        result = test.minusDays(0);
        assertSame(test, result);
    }

    //-----------------------------------------------------------------------
    public void testGetters() {
        LocalDate test = new LocalDate(1970, 6, 9, GJ_UTC);
        assertEquals(1970, test.getYear());
        assertEquals(6, test.getMonthOfYear());
        assertEquals(9, test.getDayOfMonth());
        assertEquals(160, test.getDayOfYear());
        assertEquals(2, test.getDayOfWeek());
        assertEquals(24, test.getWeekOfWeekyear());
        assertEquals(1970, test.getWeekyear());
        assertEquals(70, test.getYearOfCentury());
        assertEquals(20, test.getCenturyOfEra());
        assertEquals(1970, test.getYearOfEra());
        assertEquals(DateTimeConstants.AD, test.getEra());
    }

    //-----------------------------------------------------------------------
    public void testWithers() {
        LocalDate test = new LocalDate(1970, 6, 9, GJ_UTC);
        check(test.withYear(2000), 2000, 6, 9);
        check(test.withMonthOfYear(2), 1970, 2, 9);
        check(test.withDayOfMonth(2), 1970, 6, 2);
        check(test.withDayOfYear(6), 1970, 1, 6);
        check(test.withDayOfWeek(6), 1970, 6, 13);
        check(test.withWeekOfWeekyear(6), 1970, 2, 3);
        check(test.withWeekyear(1971), 1971, 6, 15);
        check(test.withYearOfCentury(60), 1960, 6, 9);
        check(test.withCenturyOfEra(21), 2070, 6, 9);
        check(test.withYearOfEra(1066), 1066, 6, 9);
        check(test.withEra(DateTimeConstants.BC), -1970, 6, 9);
        try {
            test.withMonthOfYear(0);
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            test.withMonthOfYear(13);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testToDateTimeAtStartOfDay() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateTime test = base.toDateTimeAtStartOfDay();
        check(base, 2005, 6, 9);
        assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
    }

    public void testToDateTimeAtStartOfDay_avoidDST() {
        LocalDate base = new LocalDate(2007, 4, 1);

        DateTimeZone.setDefault(MOCK_GAZA);
        DateTime test = base.toDateTimeAtStartOfDay();
        check(base, 2007, 4, 1);
        assertEquals(new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA), test);
    }

    //-----------------------------------------------------------------------
    public void testToDateTimeAtStartOfDay_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateTime test = base.toDateTimeAtStartOfDay(TOKYO);
        check(base, 2005, 6, 9);
        assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_TOKYO), test);
    }

    public void testToDateTimeAtStartOfDay_Zone_avoidDST() {
        LocalDate base = new LocalDate(2007, 4, 1);

        DateTime test = base.toDateTimeAtStartOfDay(MOCK_GAZA);
        check(base, 2007, 4, 1);
        assertEquals(new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA), test);
    }

    public void testToDateTimeAtStartOfDay_nullZone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateTime test = base.toDateTimeAtStartOfDay((DateTimeZone) null);
        check(base, 2005, 6, 9);
        assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
    }

    //-----------------------------------------------------------------------
    @SuppressWarnings("deprecation")
    public void testToDateTimeAtMidnight() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateTime test = base.toDateTimeAtMidnight();
        check(base, 2005, 6, 9);
        assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
    }

    //-----------------------------------------------------------------------
    @SuppressWarnings("deprecation")
    public void testToDateTimeAtMidnight_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateTime test = base.toDateTimeAtMidnight(TOKYO);
        check(base, 2005, 6, 9);
        assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_TOKYO), test);
    }

    @SuppressWarnings("deprecation")
    public void testToDateTimeAtMidnight_nullZone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateTime test = base.toDateTimeAtMidnight((DateTimeZone) null);
        check(base, 2005, 6, 9);
        assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
    }

    //-----------------------------------------------------------------------
    public void testToDateTimeAtCurrentTime() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9);
        DateTimeUtils.setCurrentMillisFixed(dt.getMillis());

        DateTime test = base.toDateTimeAtCurrentTime();
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON);
        expected = expected.year().setCopy(2005);
        expected = expected.monthOfYear().setCopy(6);
        expected = expected.dayOfMonth().setCopy(9);
        assertEquals(expected, test);
    }

    //-----------------------------------------------------------------------
    public void testToDateTimeAtCurrentTime_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9);
        DateTimeUtils.setCurrentMillisFixed(dt.getMillis());

        DateTime test = base.toDateTimeAtCurrentTime(TOKYO);
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(dt.getMillis(), COPTIC_TOKYO);
        expected = expected.year().setCopy(2005);
        expected = expected.monthOfYear().setCopy(6);
        expected = expected.dayOfMonth().setCopy(9);
        assertEquals(expected, test);
    }

    public void testToDateTimeAtCurrentTime_nullZone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9);
        DateTimeUtils.setCurrentMillisFixed(dt.getMillis());

        DateTime test = base.toDateTimeAtCurrentTime((DateTimeZone) null);
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON);
        expected = expected.year().setCopy(2005);
        expected = expected.monthOfYear().setCopy(6);
        expected = expected.dayOfMonth().setCopy(9);
        assertEquals(expected, test);
    }

    //-----------------------------------------------------------------------
    public void testToLocalDateTime_LocalTime() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);

        LocalDateTime test = base.toLocalDateTime(tod);
        check(base, 2005, 6, 9);
        LocalDateTime expected = new LocalDateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_UTC);
        assertEquals(expected, test);
    }

    public void testToLocalDateTime_nullLocalTime() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant

        try {
            base.toLocalDateTime((LocalTime) null);
            fail();
        } catch (IllegalArgumentException ex) {
            // expected
        }
    }

    public void testToLocalDateTime_wrongChronologyLocalTime() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        LocalTime tod = new LocalTime(12, 13, 14, 15, BUDDHIST_PARIS); // PARIS irrelevant

        try {
            base.toLocalDateTime(tod);
            fail();
        } catch (IllegalArgumentException ex) {
            // expected
        }
    }

    //-----------------------------------------------------------------------
    public void testToDateTime_LocalTime() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);

        DateTime test = base.toDateTime(tod);
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON);
        assertEquals(expected, test);
    }

    public void testToDateTime_nullLocalTime() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_LONDON).getMillis();
        DateTimeUtils.setCurrentMillisFixed(now);

        DateTime test = base.toDateTime((LocalTime) null);
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON);
        assertEquals(expected, test);
    }

    //-----------------------------------------------------------------------
    public void testToDateTime_LocalTime_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);

        DateTime test = base.toDateTime(tod, TOKYO);
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO);
        assertEquals(expected, test);
    }

    public void testToDateTime_LocalTime_nullZone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);

        DateTime test = base.toDateTime(tod, null);
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON);
        assertEquals(expected, test);
    }

    public void testToDateTime_nullLocalTime_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_TOKYO).getMillis();
        DateTimeUtils.setCurrentMillisFixed(now);

        DateTime test = base.toDateTime((LocalTime) null, TOKYO);
        check(base, 2005, 6, 9);
        DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO);
        assertEquals(expected, test);
    }

    public void testToDateTime_LocalTime_Zone_dstGap() {
        LocalDate base = new LocalDate(2014, 3, 30, ISO_LONDON);
        LocalTime tod = new LocalTime(1, 30, 0, 0, ISO_LONDON);
        try {
            base.toDateTime(tod, LONDON);
            fail();
        } catch (IllegalInstantException ex) {}
    }

    public void testToDateTime_LocalTime_Zone_dstOverlap() {
        LocalDate base = new LocalDate(2014, 10, 26, ISO_LONDON);
        LocalTime tod = new LocalTime(1, 30, 0, 0, ISO_LONDON);
        DateTime test = base.toDateTime(tod, LONDON);
        DateTime expected = new DateTime(2014, 10, 26, 1, 30, ISO_LONDON).withEarlierOffsetAtOverlap();
        assertEquals(expected, test);
    }

    public void testToDateTime_LocalTime_Zone_dstOverlap_NewYork() {
        LocalDate base = new LocalDate(2007, 11, 4, ISO_NEW_YORK);
        LocalTime tod = new LocalTime(1, 30, 0, 0, ISO_NEW_YORK);
        DateTime test = base.toDateTime(tod, NEW_YORK);
        DateTime expected = new DateTime(2007, 11, 4, 1, 30, ISO_NEW_YORK).withEarlierOffsetAtOverlap();
        assertEquals(expected, test);
    }

    public void testToDateTime_wrongChronoLocalTime_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        LocalTime tod = new LocalTime(12, 13, 14, 15, BUDDHIST_TOKYO);

        try {
            base.toDateTime(tod, LONDON);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    @SuppressWarnings("deprecation")
    public void testToDateMidnight() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateMidnight test = base.toDateMidnight();
        check(base, 2005, 6, 9);
        assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test);
    }

    //-----------------------------------------------------------------------
    @SuppressWarnings("deprecation")
    public void testToDateMidnight_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateMidnight test = base.toDateMidnight(TOKYO);
        check(base, 2005, 6, 9);
        assertEquals(new DateMidnight(2005, 6, 9, COPTIC_TOKYO), test);
    }

    @SuppressWarnings("deprecation")
    public void testToDateMidnight_nullZone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);

        DateMidnight test = base.toDateMidnight((DateTimeZone) null);
        check(base, 2005, 6, 9);
        assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test);
    }

    //-----------------------------------------------------------------------
    public void testToDateTime_RI() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
        DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);

        DateTime test = base.toDateTime(dt);
        check(base, 2005, 6, 9);
        DateTime expected = dt;
        expected = expected.year().setCopy(2005);
        expected = expected.monthOfYear().setCopy(6);
        expected = expected.dayOfMonth().setCopy(9);
        assertEquals(expected, test);
    }

    public void testToDateTime_nullRI() {
        LocalDate base = new LocalDate(2005, 6, 9);
        DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);
        DateTimeUtils.setCurrentMillisFixed(dt.getMillis());

        DateTime test = base.toDateTime((ReadableInstant) null);
        check(base, 2005, 6, 9);
        DateTime expected = dt;
        expected = expected.year().setCopy(2005);
        expected = expected.monthOfYear().setCopy(6);
        expected = expected.dayOfMonth().setCopy(9);
        assertEquals(expected, test);
    }

    //-----------------------------------------------------------------------
    public void testToInterval() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        Interval test = base.toInterval();
        check(base, 2005, 6, 9);
        DateTime start = base.toDateTimeAtStartOfDay();
        DateTime end = start.plus(Period.days(1));
        Interval expected = new Interval(start, end);
        assertEquals(expected, test);
    }

    //-----------------------------------------------------------------------
    public void testToInterval_Zone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        Interval test = base.toInterval(TOKYO);
        check(base, 2005, 6, 9);
        DateTime start = base.toDateTimeAtStartOfDay(TOKYO);
        DateTime end = start.plus(Period.days(1));
        Interval expected = new Interval(start, end);
        assertEquals(expected, test);
    }

    public void testToInterval_Zone_noMidnight() {
        LocalDate base = new LocalDate(2006, 4, 1, ISO_LONDON);  // LONDON irrelevant
        DateTimeZone gaza = DateTimeZone.forID("Asia/Gaza");
        Interval test = base.toInterval(gaza);
        check(base, 2006, 4, 1);
        DateTime start = new DateTime(2006, 4, 1, 1, 0, 0, 0, gaza);
        DateTime end = new DateTime(2006, 4, 2, 0, 0, 0, 0, gaza);
        Interval expected = new Interval(start, end);
        assertEquals(expected, test);
    }

    public void testToInterval_nullZone() {
        LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
        Interval test = base.toInterval(null);
        check(base, 2005, 6, 9);
        DateTime start = base.toDateTimeAtStartOfDay(LONDON);
        DateTime end = start.plus(Period.days(1));
        Interval expected = new Interval(start, end);
        assertEquals(expected, test);
    }

    //-----------------------------------------------------------------------
    public void testToDate_summer() {
        LocalDate base = new LocalDate(2005, 7, 9, COPTIC_PARIS);

        Date test = base.toDate();
        check(base, 2005, 7, 9);

        GregorianCalendar gcal = new GregorianCalendar();
        gcal.clear();
        gcal.set(Calendar.YEAR, 2005);
        gcal.set(Calendar.MONTH, Calendar.JULY);
        gcal.set(Calendar.DAY_OF_MONTH, 9);
        assertEquals(gcal.getTime(), test);
    }

    public void testToDate_winter() {
        LocalDate base = new LocalDate(2005, 1, 9, COPTIC_PARIS);

        Date test = base.toDate();
        check(base, 2005, 1, 9);

        GregorianCalendar gcal = new GregorianCalendar();
        gcal.clear();
        gcal.set(Calendar.YEAR, 2005);
        gcal.set(Calendar.MONTH, Calendar.JANUARY);
        gcal.set(Calendar.DAY_OF_MONTH, 9);
        assertEquals(gcal.getTime(), test);
    }

    public void testToDate_springDST() {
        LocalDate base = new LocalDate(2007, 4, 2);

        SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight",
                Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000);
        TimeZone currentZone = TimeZone.getDefault();
        try {
            TimeZone.setDefault(testZone);
            Date test = base.toDate();
            check(base, 2007, 4, 2);
            assertEquals("Mon Apr 02 01:00:00 GMT+02:00 2007", test.toString());
        } finally {
            TimeZone.setDefault(currentZone);
        }
    }

    public void testToDate_springDST_2Hour40Savings() {
        LocalDate base = new LocalDate(2007, 4, 2);

        SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight",
                Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000, (3600000 / 6) * 16);
        TimeZone currentZone = TimeZone.getDefault();
        try {
            TimeZone.setDefault(testZone);
            Date test = base.toDate();
            check(base, 2007, 4, 2);
            assertEquals("Mon Apr 02 02:40:00 GMT+03:40 2007", test.toString());
        } finally {
            TimeZone.setDefault(currentZone);
        }
    }

    public void testToDate_autumnDST() {
        LocalDate base = new LocalDate(2007, 10, 2);

        SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight",
                Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000);
        TimeZone currentZone = TimeZone.getDefault();
        try {
            TimeZone.setDefault(testZone);
            Date test = base.toDate();
            check(base, 2007, 10, 2);
            assertEquals("Tue Oct 02 00:00:00 GMT+02:00 2007", test.toString());
        } finally {
            TimeZone.setDefault(currentZone);
        }
    }

    //-----------------------------------------------------------------------
    public void testProperty() {
        LocalDate test = new LocalDate(2005, 6, 9, GJ_UTC);
        assertEquals(test.year(), test.property(DateTimeFieldType.year()));
        assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear()));
        assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth()));
        assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek()));
        assertEquals(test.dayOfYear(), test.property(DateTimeFieldType.dayOfYear()));
        assertEquals(test.weekOfWeekyear(), test.property(DateTimeFieldType.weekOfWeekyear()));
        assertEquals(test.weekyear(), test.property(DateTimeFieldType.weekyear()));
        assertEquals(test.yearOfCentury(), test.property(DateTimeFieldType.yearOfCentury()));
        assertEquals(test.yearOfEra(), test.property(DateTimeFieldType.yearOfEra()));
        assertEquals(test.centuryOfEra(), test.property(DateTimeFieldType.centuryOfEra()));
        assertEquals(test.era(), test.property(DateTimeFieldType.era()));
        try {
            test.property(DateTimeFieldType.millisOfDay());
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            test.property(null);
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testSerialization() throws Exception {
        LocalDate test = new LocalDate(1972, 6, 9, COPTIC_PARIS);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(test);
        byte[] bytes = baos.toByteArray();
        oos.close();

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        LocalDate result = (LocalDate) ois.readObject();
        ois.close();

        assertEquals(test, result);
        assertTrue(Arrays.equals(test.getValues(), result.getValues()));
        assertTrue(Arrays.equals(test.getFields(), result.getFields()));
        assertEquals(test.getChronology(), result.getChronology());
    }

    //-----------------------------------------------------------------------
    public void testToString() {
        LocalDate test = new LocalDate(2002, 6, 9);
        assertEquals("2002-06-09", test.toString());
    }

    //-----------------------------------------------------------------------
    public void testToString_String() {
        LocalDate test = new LocalDate(2002, 6, 9);
        assertEquals("2002 \ufffd\ufffd", test.toString("yyyy HH"));
        assertEquals("2002-06-09", test.toString((String) null));
    }

    //-----------------------------------------------------------------------
    public void testToString_String_Locale() {
        LocalDate test = new LocalDate(1970, 6, 9);
        assertEquals("Tue 9/6", test.toString("EEE d/M", Locale.ENGLISH));
        assertEquals("mar. 9/6", test.toString("EEE d/M", Locale.FRENCH));
        assertEquals("1970-06-09", test.toString(null, Locale.ENGLISH));
        assertEquals("Tue 9/6", test.toString("EEE d/M", null));
        assertEquals("1970-06-09", test.toString(null, null));
    }

    //-----------------------------------------------------------------------
    public void testToString_DTFormatter() {
        LocalDate test = new LocalDate(2002, 6, 9);
        assertEquals("2002 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("yyyy HH")));
        assertEquals("2002-06-09", test.toString((DateTimeFormatter) null));
    }

    //-----------------------------------------------------------------------
    private void check(LocalDate test, int hour, int min, int sec) {
        assertEquals(hour, test.getYear());
        assertEquals(min, test.getMonthOfYear());
        assertEquals(sec, test.getDayOfMonth());
    }
}


text:
//
// Scaled - a scalable editor extensible via JVM languages
// http://github.com/scaled/scaled/blob/master/LICENSE

package scaled.code

import reactual.OptValue
import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scaled._
import scaled.major.EditingMode
import scaled.util.Chars

object CodeConfig extends Config.Defs {

  @Var("The number of characters to indent when in a nested scope.")
  val indentWidth = key(4)

  @Var("Whether to attempt to auto-detect indentWidth for buffers with existing code.")
  val autoDetectIndent = key(true)

  @Var("""When true, a } that immediately follows a { will be expanded into a properly indented
          block containing a single blank line, on which the point will be positioned.""")
  val electricBrace = key(true)

  @Var("Enables debug logging for indentation logic.")
  val debugIndent = key(false)

  /** The CSS style applied to `builtin` syntax. */
  val builtinStyle = "codeBuiltinFace"
  /** The CSS style applied to `preprocessor` syntax. */
  val preprocessorStyle = "codePreprocessorFace"
  /** The CSS style applied to `comment` syntax. */
  val commentStyle = "codeCommentFace"
  /** The CSS style applied to `constant` syntax. */
  val constantStyle = "codeConstantFace"
  /** The CSS style applied to `doc` syntax. */
  val docStyle = "codeDocFace"
  /** The CSS style applied to `keyword` syntax. */
  val keywordStyle = "codeKeywordFace"
  /** The CSS style applied to `string` syntax. */
  val stringStyle = "codeStringFace"
  /** The CSS style applied to `module` syntax. */
  val moduleStyle = "codeModuleFace"
  /** The CSS style applied to `type` syntax. */
  val typeStyle = "codeTypeFace"
  /** The CSS style applied to `function` syntax. */
  val functionStyle = "codeFunctionFace"
  /** The CSS style applied to `variable` syntax. */
  val variableStyle = "codeVariableFace"
  /** The CSS style applied to `invalid` syntax. */
  val invalidStyle = "codeInvalidFace"

  /** The CSS style applied to the current block delimiters. */
  val blockDelimStyle = "blockDelimFace"
  /** The CSS style applied to the current block delimiters when mismatched. */
  val blockErrorStyle = "blockErrorFace"
}

/** A base class for major modes which edit program code.
  */
abstract class CodeMode (env :Env) extends EditingMode(env) {
  import CodeConfig._
  import Chars._

  override def configDefs = CodeConfig :: super.configDefs
  override def stylesheets = stylesheetURL("/code.css") :: super.stylesheets
  override def keymap = super.keymap ++ Seq(
    "ENTER"   -> "newline-and-indent",
    "S-ENTER" -> "newline-and-indent",
    "TAB"     -> "reindent",
    "}"       -> "electric-close-brace",

    "S-C-," -> "previous-bracket",
    "S-C-." -> "next-bracket",
    "S-C-/" -> "bounce-bracket",

    "C-M-\\"  -> "indent-region",
    "C-c C-c" -> "comment-region",
    "C-c C-u" -> "uncomment-region", // TODO: prefix args?

    "M-A-s" -> "show-syntax"
  )

  /** A context provided to our indenters. */
  val indentCtx = new Indenter.Context {
    def buffer = CodeMode.this.buffer
    def blocker = CodeMode.this.blocker
    def debug = config(CodeConfig.debugIndent)
    def indentWidth = if (config(CodeConfig.autoDetectIndent) && detectedIndent > 0) detectedIndent
                      else config(CodeConfig.indentWidth)
    private lazy val detectedIndent = CodeMode.this.detectIndent
  }

  /** The list of indenters used to indent code for this mode. */
  val indenters :List[Indenter]

  /** A helper class for dealing with comments. */
  val commenter :Commenter

  /** Indicates the current block, if any. Updated when bracket is inserted or the point moves. */
  val curBlock = OptValue[Block]()
  /** A helper that tracks blocks throughout the buffer. */
  val blocker = new Blocker(buffer, openBrackets, closeBrackets)

  /** Enumerates the open brackets that will be matched when tracking blocks. */
  def openBrackets = "{(["
  /** Enumerates the close brackets that will be matched when tracking blocks.
    * These must match the order of [[openBrackets]] exactly. */
  def closeBrackets = "})]"

  // as the point moves around, track the active block
  view.point onValue { p => curBlock() = blocker(p) }
  // as the active block changes, highlight the delimiters
  curBlock onChange { (nb, ob) =>
    ob.map { b =>
      buffer.removeStyle(blockDelimStyle, b.start, b.start.nextC)
      if (b.isValid) buffer.removeStyle(blockDelimStyle, b.end, b.end.nextC)
      else buffer.removeStyle(blockErrorStyle, b.start, b.start.nextC)
    }
    nb.map { b =>
      buffer.addStyle(blockDelimStyle, b.start, b.start.nextC)
      if (b.isValid) buffer.addStyle(blockDelimStyle, b.end, b.end.nextC)
      else buffer.addStyle(blockErrorStyle, b.start, b.start.nextC)
    }
  }

  /** Computes the indentation for the line at `row`. */
  def computeIndent (row :Int) :Int = {
    // find the position of the first non-whitespace character on the line
    val line = buffer.line(row)
    val start = Loc(row, line.firstNonWS)
    val block = blocker.require(start, Syntax.Default)
    @tailrec @inline def loop (ins :List[Indenter]) :Int =
      if (ins.isEmpty) 0 else {
        val opt = ins.head(block, line, start)
        if (opt.isDefined) opt.get else loop(ins.tail)
      }
    loop(indenters)
  }

  /** Computes the indentation for the line at `pos` and adjusts its indentation to match. If the
    * point is in the whitespace at the start of the indented line, it will be moved to the first
    * non-whitespace character in the line, otherwise it will be shifted along with the line to
    * retain its relative position in the line.
    */
  def reindent (pos :Loc) {
    val indent = computeIndent(pos.row)
    // shift the line, if needed
    val delta = indent - Indenter.readIndent(buffer, pos)
    if (delta > 0) buffer.insert(pos.atCol(0), Line(" " * delta))
    else if (delta < 0) buffer.delete(pos.atCol(0), -delta)
    // if the point is now in the whitespace preceding the indent, move it to line-start
    val p = view.point()
    if (p.row == pos.row && p.col < indent) view.point() = Loc(p.row, indent)
  }

  /** Reindents the line at the point. */
  def reindentAtPoint () {
    reindent(view.point())
  }

  /** Requests that the indent-level of the buffer be auto-detected. Modes can implement this with
    * [[Indenter.Detecter]] in combination with their own language specific understanding. `0` (the
    * default) indicates that we should use the configured indentation value (i.e. auto-detection
    * is not supported or that a reliable indentation value could not be detected).
    */
  def detectIndent :Int = 0

  // when editing code, we only auto-fill comments; auto-filling code is too hairy
  override def shouldAutoFill (p :Loc) = super.shouldAutoFill(p) && commenter.inComment(buffer, p)

  override def mkParagrapher (syn :Syntax) =
    if (syn.isComment) commenter.mkParagrapher(syn, buffer)
    else super.mkParagrapher(syn)

  // in code mode, refills only happen inside comments
  override def fillParagraph () {
    // make sure we're "looking at" a comment on this line
    val p = view.point()
    val wp = buffer.line(p).indexOf(isNotWhitespace, p.col) match {
      case -1 => p
      case ii => p.atCol(ii)
    }
    if (commenter.inComment(buffer, wp)) super.fillParagraph()
    else editor.popStatus("Code modes only fill comments, not code.")
  }
  override def refillLinesIn (start :Loc, end :Loc) = {
    val cend = trimEnd(end)
    buffer.replace(start, cend, commenter.refilled(buffer, fillColumn, start, cend))
  }

  // when we break for auto-fill, insert the appropriate comment prefix
  override def autoBreak (at :Loc) {
    val pre = commenter.prefixFor(buffer.syntaxNear(at))
    super.autoBreak(at)
    if (pre != "") {
      buffer.insert(view.point().atCol(0), Line(pre))
      reindentAtPoint()
    }
  }

  //
  // FNs

  @Fn("Displays the syntax at the point.")
  def showSyntax () {
    val info = Seq(buffer.syntaxAt(view.point()).toString)
    view.popup() = Popup.text(info, Popup.UpRight(view.point()))
  }

  @Fn("Inserts a newline, then indents according to the code mode's indentation rules.")
  def newlineAndIndent () {
    newline()
    reindentAtPoint()
  }

  @Fn("""Recomputes the current line's indentation based on the code mode's indentation rules and
         adjusts its indentation accordingly.""")
  def reindent () {
    reindentAtPoint()
  }

  @Fn("""Inserts a brace, indenting it automatically to the proper position. If eletric-close-brace
         is true and the preceding character is '{', a blank line is inserted prior to the '}' and
         the point is left on the blank line, at the proper indentation.""")
  def electricCloseBrace () {
    val p = view.point()
    if (!config(electricBrace) || buffer.charAt(p.prevC) != '{') {
      selfInsertCommand("}")
      reindentAtPoint()
    } else {
      newline()
      newline()
      selfInsertCommand("}")
      reindent(view.point())
      view.point() = view.point().prevL
      reindentAtPoint()
    }
  }

  @Fn("""Moves the point onto the open bracket (paren, brace, etc.) of the enclosing block. This
         places the point into the block that encloses the current block, so a repeated invocation
         of this fn will move the point to the next outermost block start, and so forth until no
         enclosing block can be found.""")
  def previousBracket () {
    curBlock.getOption match {
      case None    => editor.popStatus("No enclosing block can be found.")
      case Some(b) => view.point() = b.start
    }
  }

  @Fn("""Moves the point just after the close bracket (parent, brace, etc.) of the enclosing block.
         If the point is already there, the point is moved just after the next-nearest enclosing
         block's close bracket.""")
  def nextBracket () {
    curBlock.getOption match {
      case None    => editor.popStatus("No enclosing block can be found.")
      case Some(b) => if (view.point() != b.end.nextC) view.point() = b.end.nextC
                      else blocker(buffer.forward(b.end, 2)) match {
                        case None => editor.popStatus("No enclosing block can be found.")
                        case Some(b) => view.point() = b.end.nextC
                      }
    }
  }

  @Fn("""Moves the point just after the open bracket (paren, brace, etc.) of the enclosing block.
         If the point is already there, the point is moved just after the block's close bracket.
         If the point is not at either end of the block when this fn is first invoked, the mark
         will be set to the current point (inside the block).

         If this fn is invoked with the point just after the block's close bracket, and the mark
         is inside the block, the point will be moved to the mark. This allows one to cycle from
         a point inside the block, to the block start, to the block end, and back to the starting
         point inside the block.""")
  def bounceBracket () {
    curBlock.getOption match {
      case None => editor.popStatus("No enclosing block can be found.")
      case Some(b) =>
        val p = view.point()
        // if we're at the start of the block, move to the end of the block
        if (p == b.start.nextC) view.point() = b.end.nextC
        // if we're at the end of the block, move either to the mark (if it's set and inside the
        // block), or to the start of the block
        else if (p == b.end.nextC) view.point() = buffer.mark match {
          case Some(m) => if (b.contains(m)) m else b.start.nextC
          case None => b.start.nextC
        }
        else {
          // otherwise we're somewhere inside the block, so set the mark and move to block start
          buffer.mark = p
          view.point() = b.start.nextC
        }
    }
  }

  @Fn("Indents each non-blank line in the region.")
  def indentRegion () {
    withRegion { (start, end) =>
      var pos = start ; while (pos < end) {
        if (buffer.line(pos).length > 0) reindent(pos)
        pos = pos.nextL
      }
    }
  }

  @Fn("""Comments out the active region. If the start and end of the region are in column zero,
         and line comments are supported by the mode, line comments are used, otherwise the region
         is wrapped in a block comment.""")
  def commentRegion () {
    withRegion { (start, end) =>
      if (start.col == 0 && end.col == 0 && commenter.linePrefix != "") {
        buffer.replace(start, end, commenter.lineCommented(buffer, start, end))
      }
      else if (commenter.blockOpen != "") {
        commenter.blockComment(buffer, start, end)
      }
      else editor.popStatus("This code mode does not define block comment delimiters.")
    }
  }

  @Fn("""Removes comments from the active region, assuming they were uniformly applied. If the
         region starts and ends with the block comment delimiters, they will be removed. Otherwise
         the line comment delimiters will be sought and removed from the start of each line.""")
  def uncommentRegion () {
    withRegion { (start, end) =>
      if (!commenter.unBlockComment(buffer, start, end)) {
        commenter.unLineComment(buffer, start, end)
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * Classe etendant la classe du FOSUserBundle
 */

namespace Palabre\UserBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CreateUserCommand extends ContainerAwareCommand
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('palabre:user:create')
            ->setDescription('Create a user.')
            ->setDefinition(array(
                new InputArgument('firstname', InputArgument::REQUIRED, 'The first name'),
                new InputArgument('lastname', InputArgument::REQUIRED, 'The last name'),
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
                new InputArgument('email', InputArgument::REQUIRED, 'The email'),
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
                new InputOption('super-admin', null, InputOption::VALUE_NONE, 'Set the user as super admin'),
                new InputOption('inactive', null, InputOption::VALUE_NONE, 'Set the user as inactive'),
            ))
            ->setHelp(<<<EOT
The <info>palabre:user:create</info> command creates a user:

  <info>php app/console palabre:user:create mdupond</info>

This interactive shell will ask you for an email and then a password.

You can alternatively specify the email and password as the second and third arguments:

  <info>php app/console palabre:user:create mathieu dupond mdupond matthieu@example.com mypassword</info>

You can create a super admin via the super-admin flag:

  <info>php app/console palabre:user:create admin --super-admin</info>

You can create an inactive user (will not be able to log in):

  <info>php app/console palabre:user:create mdupond --inactive</info>

EOT
            );

    }

    /**
     * @see Command
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $firstname  = $input->getArgument('firstname');
        $lastname   = $input->getArgument('lastname');
        $username   = $input->getArgument('username');
        $email      = $input->getArgument('email');
        $password   = $input->getArgument('password');
        $inactive   = $input->getOption('inactive');
        $superadmin = $input->getOption('super-admin');

        $manipulator = $this->getContainer()->get('palabre_user.util.user_manipulator');
        $manipulator->createPalabreUser($firstname, $lastname, $username, $password, $email, !$inactive, $superadmin);

        $output->writeln(sprintf('Created user <comment>%s</comment>', $username));
    }

    /**
     * @see Command
     */
    protected function interact(InputInterface $input, OutputInterface $output)
    {
        if (!$input->getArgument('firstname')) {
            $firstname = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose a firstname:',
                function($firstname) {
                    if (empty($firstname)) {
                        throw new \Exception('Firstname can not be empty');
                    }

                    return $firstname;
                }
            );
            $input->setArgument('firstname', $firstname);
        }
        if (!$input->getArgument('lastname')) {
            $lastname = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose a lastname:',
                function($lastname) {
                    if (empty($lastname)) {
                        throw new \Exception('Lastname can not be empty');
                    }

                    return $lastname;
                }
            );
            $input->setArgument('lastname', $lastname);
        }
        if (!$input->getArgument('username')) {
            $username = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose a username:',
                function($username) {
                    if (empty($username)) {
                        throw new \Exception('Username can not be empty');
                    }

                    return $username;
                }
            );
            $input->setArgument('username', $username);
        }

        if (!$input->getArgument('email')) {
            $email = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose an email:',
                function($email) {
                    if (empty($email)) {
                        throw new \Exception('Email can not be empty');
                    }

                    return $email;
                }
            );
            $input->setArgument('email', $email);
        }

        if (!$input->getArgument('password')) {
            $password = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose a password:',
                function($password) {
                    if (empty($password)) {
                        throw new \Exception('Password can not be empty');
                    }

                    return $password;
                }
            );
            $input->setArgument('password', $password);
        }
    }
}


text:
extern NSString *const ARUserIdentifierDefault;
extern NSString *const ARUseStagingDefault;

extern NSString *const AROAuthTokenDefault;
extern NSString *const AROAuthTokenExpiryDateDefault;

extern NSString *const ARXAppTokenDefault;
extern NSString *const ARXAppTokenExpiryDateDefault;

#pragma mark -
#pragma mark onboarding

extern NSString *const AROnboardingSkipPersonalizeDefault;
extern NSString *const AROnboardingSkipCollectorLevelDefault;
extern NSString *const AROnboardingSkipPriceRangeDefault;
extern NSString *const AROnboardingPromptThresholdDefault;

#pragma mark -
#pragma mark Things we wanna trigger server-side

extern NSString *const ARShowAuctionResultsButtonDefault;

@interface ARDefaults : NSObject
+ (void)setup;
+ (void)resetDefaults;
@end


text:
package com.smartdevicelink.proxy.rpc;

import java.util.Hashtable;
import java.util.List;

import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCRequest;

/**
 * Non periodic vehicle data read request. This is an RPC to get diagnostics
 * data from certain vehicle modules. DIDs of a certain module might differ from
 * vehicle type to vehicle type
 *

 * Function Group: ProprietaryData
 *

 * HMILevel needs to be FULL, LIMITED or BACKGROUND
 *

 *
 * @since SmartDeviceLink 2.0
 */
public class ReadDID extends RPCRequest {
	public static final String KEY_ECU_NAME = "ecuName";
	public static final String KEY_DID_LOCATION = "didLocation";

	/**
	 * Constructs a new ReadDID object
	 */
    public ReadDID() {
        super(FunctionID.READ_DID.toString());
    }

	/**
	 * Constructs a new ReadDID object indicated by the Hashtable parameter
	 *

	 *
	 * @param hash
	 *            The Hashtable to use
	 */
    public ReadDID(Hashtable<String, Object> hash) {
        super(hash);
    }

	/**
	 * Sets an ID of the vehicle module
	 *
	 * @param ecuName
	 *            an Integer value representing the ID of the vehicle module
	 *

	 *            Notes: Minvalue:0; Maxvalue:65535
	 */
    public void setEcuName(Integer ecuName) {
    	if (ecuName != null) {
    		parameters.put(KEY_ECU_NAME, ecuName);
    	} else {
    		parameters.remove(KEY_ECU_NAME);
    	}
    }

	/**
	 * Gets the ID of the vehicle module
	 *
	 * @return Integer -an Integer value representing the ID of the vehicle
	 *         module
	 */
    public Integer getEcuName() {
    	return (Integer) parameters.get(KEY_ECU_NAME);
    }

	/**
	 * Sets raw data from vehicle data DID location(s)
	 *
	 * @param didLocation
	 *            a List<Integer> value representing raw data from vehicle
	 *            data DID location(s)
	 *

	 *            Notes:
	 *

	 *
Minvalue:0; Maxvalue:65535

	 *
ArrayMin:0; ArrayMax:1000

	 *

	 */
    public void setDidLocation(List<Integer> didLocation) {

    	boolean valid = true;

    	for ( Integer item : didLocation ) {
    		if (item == null) {
    			valid = false;
    		}
    	}

    	if ( (didLocation != null) && (didLocation.size() > 0) && valid) {
    		parameters.put(KEY_DID_LOCATION, didLocation);
    	} else {
    		parameters.remove(KEY_DID_LOCATION);
    	}
    }

	/**
	 * Gets raw data from vehicle data DID location(s)
	 *
	 * @return List<Integer> -a List<Integer> value representing raw data
	 *         from vehicle data DID location(s)
	 */
    @SuppressWarnings("unchecked")
    public List<Integer> getDidLocation() {
        if (parameters.get(KEY_DID_LOCATION) instanceof List<?>) {
        	List<?> list = (List<?>)parameters.get(KEY_DID_LOCATION);
        	if (list != null && list.size() > 0) {
        		for( Object obj : list ) {
        			if (!(obj instanceof Integer)) {
        				return null;
        			}
        		}
        		return (List<Integer>) list;
        	}
        }
        return null;
    }
}


text:
require 'zip/zip'

module Downlow
  class Zip < Extractor

    handles(/\.zip$/, :file_only => true)

    def extract
      ::Zip::ZipFile.foreach(path) do |file|
        path = destination + file.name
        path.dirname.mkpath
        file.extract(path)
      end
      @final_path = destination
    end

  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; 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="">

    <title>Portfolio</title>

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

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

    <link href="css/agency.css" rel="stylesheet">

    <link rel="icon" type="image/png" href="img/imac-g4-icon.png">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Eric Benzenhoefer

                        services

                        Portfolio

                        Journey

                        about

                        Contact

Front-end Web Developer - HTML, CSS, JS

portfolio

                Tell Me More

Services

DIY to Enterprise Solutions

You Build

                        DIY systems have come along way.  For a blend of use simplicity, design excellent, and functionality,
                        SquareSpace.com is my suggestion. For more technical users, check out WordPress.

I Build

Built with SquareSpace.com to leverage the design, stability, and support of a NYC or Silicon Valley Website Development Agency, but at the local freelancer price of $50/hr. Hand this off and get back to your business.

They Build

Partner with an Silicon Valley company who can take your business to the next level in measurable results marketing, tracked SEO/SEM, and custom WordPress sites and web applications.

                    To Contact

Portfolio

WordPress, JavaScript, API, jQuery, Templates, CSS, HTML, Python, SQL, Google Docs, Excel, SquareSpace, Wix, Weebly

WordPress Onepage

                            Unicon Theme

New Home Builders

SquareSpace.com

Podcast Website

SquareSpace.com

Proverbs Daily

JS - jQuery - API

JS Calculator

JS - jQuery

Wiki API

JS - jQuery - API

Local Weather

JS-jQuery-API

Random Quotes

JS - jQuery - API

Business Website

Wix.com

Real Estate Tools

Google Docs - Excel

The Journey from Now

Walk back in time to see How my career began and how that experience may bring value to you today.

Be Part

Of The

Story!

2017

Post Course Projects

With course work under my belt, I am completing some of my own projects to show what value is ready for hire.  Check out the work in the portfolio section.

2017

FreeCodeCamp.com

While attending a hackathon, the consensus was that Javascript was the language to learn, so I joined FreeCodeCamp.com. FCC is both a great learning tool and community of those learning to code beginning with Front-End Development in Javascript. Course projects can be seen in the portfolio above.

2017

Udacity - Intro to Code Nanodegree

Looking for a more structured route to the first job, I tried Udacity. The first Python section was in my opinion a perfect online class. Check out my GitHub profile to see the work.

2016

Data Analytics

After a positive experience with SQL, Python, and a ton of spreadsheets in the past, I completed a course on data analytics, which left me hungry for something more tangible.

2016

Back to Coding? Yes!

Where to go now? What I knew is I was an analytical problem solver and great with Excel. Reddit and Google pointed me to coding and Codecademy to test the fit. There I completed SQL and Python.

2015-2016

My Business Needs a Website

I hired myself and loved it.  Customer service is good, but making something is why I started down the engineering path to begin with. Check out my wix.com site for the business right here. And by the way, do you need a business loan?

2013-2015

Real Estate Investment

Moved to real estate investment with great help from BiggerPockets.com, an investor forum community. That project has funded this career switch.

2009-2013

Engineer In Training

Wanting to do more tangible work, led me to a road including four roles in training including tutoring, a start up (minus the start) and a leadership role overhauling adult learning programs at a chemical plant.

2008-2009

Project Engineer

First job out of college taught me that I have much to learn, including that I would like to do more tangible work. It took a while, but I am there now.

Texas A&M University

Mechanical Engineer

Looking back, the courses that stood out were Excel and programming related. That plus internships with GE and Caterpillar told me that engineering may not be the best fit.

about

Github repositories, social media profiles, and podcasts.

Eric Benzenhoefer

Front End Web Developer

Podcast Co-Host

The Idea Tank Podcast

Contact

Click below to email, or right click to copy the email address.

Station Houston

1301 Fannin St #2440

Houston, TX 77002

                                <button type="button" class="btn btn-primary" style="color: black;">Email</button>

                    Copyright © 2017

Proverbs Daily

Christian scripture daily reading uses an API to make an easy quiz for the Proverb of the day.

                                <button type="button" class="btn btn-primary">Go To Project</button>

This project solves a problem in the Christian community for people who want add the discipline of daily scripture reading into their lives. The quiz like structure takes the reader verse by verse through the chapter of the day to add a level of mental interaction just above reading. If you can take this project to the next level, I am open to proposals, as this solution is a major need in the Christian market.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Expression Calculator w/ JS

JS based calculator, with a simple feature that the graphing calculators brought us.

                                <button type="button" class="btn btn-primary">Go To Project</button>

Missed a key using a simple calculator? Sorry, got to start over. I never liked this about simple calculators so in my FCC JavaScript calculator project, the expression stays up and editable even after the = is clicked.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Wikipedia API

How to get Wikipedia's search functionality embedded into a website.

                                <button type="button" class="btn btn-primary">Go To Project</button>

A great FCC project to teach API and jQuery. Simply type what you want and the top 10 search results are generated to your site.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Local Weather

Get your local weather based upon your device location.

                                <button type="button" class="btn btn-primary">Go To Project</button>

My first experience importing info into my website where the site pulls the users location and then uses that to pull local weather info.  Another great FCC project.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Random Quotes

Get your local weather based upon your device location.

                                <button type="button" class="btn btn-primary">Go To Project</button>

Simple FCC project to learn how to use JavaScript functionality and jQuery. Oh yeah, and so asynchronous is a thing, I learned. Update: project has since been updated with an API to get broader base of quotes.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Business Website

Informational Wix site for my personal business.

                                <button type="button" class="btn btn-primary">Go To Project</button>

Needing a website for my personal business, I hired myself and used Wix.com. It is fun to look back at where my itch for web development started.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Spreadsheet Tools - Real Estate

Tools built with Google Docs to make my work easier in REI.

                                <button type="button" class="btn btn-primary">Go To Project</button>

Here are some examples of tools that I build for my time in real estate investing.  Now I want to add functionality to websites using JavaScript.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>


text:
package com.virtualpairprogrammers.controllers;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FirstController {

	@RequestMapping("/home.html")
	public ModelAndView firstPage()
	{
		Date dateAndTime = new Date();

		// TODO We will use a proper view resolver very quickly
		return new ModelAndView("welcome", "dateAndTime", dateAndTime);
	}

}


text:
package radium.arg4j;

import adrien.common.Pair;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

public class Arg4j {

    private Class<?> mainClass;
    private Map<Object, Optional<Object>> map;

    private Arg4j(Class<?> mainClass) {
        super();
        this.mainClass = mainClass;
    }

    public static Arg4j forClass(Class<?> mainClass) {
        return new Arg4j(mainClass);
    }

    public Arg4j parseArguments(String... texts) throws CmdLineException {
        map = Maps.newHashMap();
        CmdLineParser parser = new CmdLineParser(null);
        for (Field field : mainClass.getDeclaredFields()) {
            Option option = field.getAnnotation(Option.class);
            if (option != null) {
                parser.addOption(MapSetters.create(map, field, option), option);
            }

            Argument argument = field.getAnnotation(Argument.class);
            if (argument != null) {
                parser.addArgument(MapSetters.create(map, field, argument), argument);
            }
        }
        parser.parseArgument(texts);
        return this;
    }

    public static Pair<List<Option>, List<Argument>> parseOptionsAndArguments(Class<?> mainClass) {
        List<Option> options = Lists.newArrayList();
        List<Argument> arguments = Lists.newArrayList();
        for (Field field : mainClass.getDeclaredFields()) {
            Option option = field.getAnnotation(Option.class);
            if (option != null) {
                options.add(option);
            }

            Argument argument = field.getAnnotation(Argument.class);
            if (argument != null) {
                arguments.add(argument);
            }
        }
        return Pair.of(options, arguments);
    }

    public <I> void setFields(I instance) {
    	Class<?> instanceClass = instance.getClass();
    	for (Field field : instanceClass.getDeclaredFields()) {
    		Inject inject = field.getAnnotation(Inject.class);
    		if (inject != null) {
	    		Option option = field.getAnnotation(Option.class);
	    		if (option != null) {
	    			Optional<Object> value = map.get(option);
	    			if (value != null && value.isPresent()) {
	    				boolean accessible = field.isAccessible();
	    				field.setAccessible(true);
	    				try {
							field.set(instance, value.get());
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
	    				field.setAccessible(accessible);
	    			}
	    		}
    		}

    		Argument argument = field.getAnnotation(Argument.class);
    		if (argument != null) {
    			Optional<Object> value = map.get(argument);
    			if (value != null && value.isPresent()) {
    				boolean accessible = field.isAccessible();
    				field.setAccessible(true);
    				try {
						field.set(instance, value.get());
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
    				field.setAccessible(accessible);
    			}
    		}
    	}
    }

}


text:
package com.twitter.finagle.naming

import com.twitter.finagle._
import com.twitter.finagle.factory.ServiceFactoryCache
import com.twitter.finagle.util.{Drv, Rng}
import com.twitter.util.{Future, Time}

/**
 * Builds a factory from a [[com.twitter.finagle.NameTree]]. Leaves
 * are taken from the given
 * [[com.twitter.finagle.factory.ServiceFactoryCache]]; Unions become
 * random weighted distributors.
 */
private object NameTreeFactory {

  def apply[Key, Req, Rep](
    path: Path,
    tree: NameTree[Key],
    factoryCache: ServiceFactoryCache[Key, Req, Rep],
    rng: Rng = Rng.threadLocal
  ): ServiceFactory[Req, Rep] = {

    lazy val noBrokersAvailableFactory = Failed(new NoBrokersAvailableException(path.show))

    case class Failed(exn: Throwable) extends ServiceFactory[Req, Rep] {
      val service: Future[Service[Req, Rep]] = Future.exception(exn)

      def apply(conn: ClientConnection) = service
      override def status = Status.Closed
      def close(deadline: Time) = Future.Done
    }

    case class Leaf(key: Key) extends ServiceFactory[Req, Rep] {
      def apply(conn: ClientConnection) = factoryCache.apply(key, conn)
      override def status = factoryCache.status(key)
      def close(deadline: Time) = Future.Done
    }

    case class Weighted(
      drv: Drv,
      factories: Seq[ServiceFactory[Req, Rep]]
    ) extends ServiceFactory[Req, Rep] {
      def apply(conn: ClientConnection) = factories(drv(rng)).apply(conn)

      override def status = Status.worstOf[ServiceFactory[Req, Rep]](factories, _.status)
      def close(deadline: Time) = Future.Done
    }

    def factoryOfTree(tree: NameTree[Key]): ServiceFactory[Req, Rep] =
      tree match {
        case NameTree.Neg | NameTree.Fail | NameTree.Empty => noBrokersAvailableFactory
        case NameTree.Leaf(key) => Leaf(key)

        // it's an invariant of Namer.bind that it returns no Alts
        case NameTree.Alt(_*) => Failed(new IllegalArgumentException("NameTreeFactory"))

        case NameTree.Union(weightedTrees @ _*) =>
          val (weights, trees) = weightedTrees.unzip { case NameTree.Weighted(w, t) => (w, t) }
          Weighted(Drv.fromWeights(weights), trees.map(factoryOfTree))
      }

    factoryOfTree(tree)
  }
}


text:
require 'spec_helper'

describe Turnstile::Adapter do

  subject { Turnstile::Adapter.new }

  let(:redis) { subject.send(:redis) }

  let(:uid) { 1238438 }
  let(:other_uid) { 1238439 }
  let(:another_uid) { 1238440 }

  let(:ip) { '1.2.3.4' }
  let(:another_ip) { '4.3.2.1' }

  let(:platform) { :ios }
  let(:another_platform) { :android }

  describe '#add' do
    it 'calls redis with the correct params' do
      key = "t:#{uid}:#{platform}:#{ip}"
      expect(redis).to receive(:setex).once.with(key, Turnstile.config.activity_interval, 1)
      subject.add(uid, platform, ip)
    end
  end

  describe '#fetch' do
    let(:sort_lambda) { ->(a, b) { a[:uid] <=> b[:uid] }  }
    let(:expected_hash) do
      [
        { uid: uid.to_s, platform: platform.to_s, ip: ip },
        { uid: other_uid.to_s, platform: platform.to_s, ip: ip },
        { uid: another_uid.to_s, platform: another_platform.to_s, ip: another_ip },
      ]
    end

    before do
      subject.add(uid, platform, ip)
      subject.add(other_uid, platform, ip)
      subject.add(another_uid, another_platform, another_ip)
    end

    it 'pulls the platform specific stats from redis' do
      expect(subject.fetch.sort(&sort_lambda)).to eq(expected_hash.sort(&sort_lambda))
    end
  end

  describe '#aggregate' do
    let(:expected_hash) do
      {
        'android' => 3,
        'ios'     => 2,
        'total'   => 5
      }
    end

    before do
      subject.add(123, :android, ip)
      subject.add(124, :android, ip)
      subject.add(125, :android, ip)

      subject.add(200, :ios, ip)
      subject.add(201, :ios, ip)
    end

    it 'should calculated proper aggregation' do
      expect(subject.aggregate).to eql expected_hash
    end
  end

end


text:
// Imported with tests from https://www.github.com/hmrc/node-git-versioning (now deprecated)
const formatVersion = require('./format-version')
const gitDescribe = require('./git-describe')

const NodeGitVersion = (gitDir) => {
  const commit = gitDescribe(gitDir)
  const version = formatVersion(commit)
  return version
}

module.exports = NodeGitVersion


text:
<?xml version="1.0" encoding="UTF-8"?>
<ares>
	<pub nodeName="jres_hanyin" nodeNo="0" />

	<!-- 插件配置信息 -->
	<plugins>
		<plugin service-id="jres.logFactory" load-level="1"></plugin>
		<plugin service-id="jres.configurationHelper" load-level="1"></plugin>

		<!-- CEP核心插件 -->
		<plugin service-id="jres.cepcore" load-level="3">
			<plugin-configuration>
				<args threadCount="3" queueSize="30" debug="false">
					<monitor port="8012" enable="true" />
				</args>
				<bizservices>
					<bizservice id="jres.mockBizService" debug="true" />
					<bizservice id="jres.bizkernel_plugin" debug="true" />
					<bizservice id="jres.mproxy" debug="true" />
				</bizservices>
				<routetables>
					<routetable serviceId="com.hundsun.jres.manage" functionId="8" pluginId="jres.mproxy" />
					<routetable serviceId="jres_mock.*" functionId="8?;9?;1??" pluginId="jres.mockBizService" />
					<routetable serviceId="*" functionId="*" pluginId="jres.bizkernel_plugin" />
				</routetables>
				<eventchains>
					<chain>jres.mproxy;jres.cepcore</chain>
					<chain>jres.bizkernel_plugin;jres.cepcore</chain>
					<chain>jres.mockBizService;jres.cepcore</chain>
					<chain>jres.localService;jres.cepcore</chain>
					<chain>jres.t2channel;jres.cepcore</chain>
				</eventchains>
			</plugin-configuration>
		</plugin>

		<!-- 本地通道插件 -->
		<plugin service-id="jres.localService" load-level="3">
			<plugin-configuration>
				<args debug="false" />
				<time timeout="1000" />
			</plugin-configuration>
		</plugin>

		<!-- 模拟本地业务处理插件 -->
		<plugin service-id="jres.mockBizService" load-level="3" />

		<!-- t2通道插件-->
		<plugin service-id="jres.t2channel" load-level="3">
			<plugin-configuration>
				<performance debug="false"  />
				<server address="" port="8020" enable="false"/>
			</plugin-configuration>
		</plugin>

		<!-- bizkernel插件 -->
		<plugin service-id="jres.bizkernel_plugin" load-level="3">
			<plugin-configuration>
				<!--
					业务资源的动态刷新 open:是否开启动态刷新。可用值true|false。true,表示开户,false或者不填写则不开户
					interval:动态刷新的时间间隔,单位为毫秒。如果不填写 默认值为1000
					searchAll:搜索所有的classpath以及jar包中的资源
				-->
				<refresh open="false" interval="10000" />
			</plugin-configuration>
		</plugin>

	</plugins>

</ares>


text:
const debug = require('debug')('livegen')
const inquirer = require('inquirer-promise')
const _ = require('lodash')
const c = require('chalk')
const {Environment} = require('../app/Environment')
const yargsModule = require('yargs')
//endregion

//process.on('unhandledRejection', e => {throw e})

// envOpts - for testing purposes to set cwd.
export async function cli(args:Array<string>, opts = {}) {
  if (!args) args = process.argv

  const yargs = yargsModule
    .usage('Usage: $0 <generator-name> [options]')
    .describe('cwd', 'Run in a different current working directory')
    .help()

  const argv = yargs.parse(args)

  console.log('Welcome to Drum - the project generator')

  debug({argv})

  // Environment

  const envOpts = {
    cwd: argv.cwd,
    argv: argv._.slice(3),
    ...opts.env,
  }
  const env = new Environment(envOpts)
  await env.loadGenerators()

  // Generator

  const generatorName = argv._[2]
  if (!generatorName) {
    console.error('Error: Missing generator name.\n')
    yargs.showHelp()
    process.exit()
  }
  const runOpts = {
    writeToDisk: true,
    props: {main: true},
    ...opts,
  }
  await env.run(generatorName, runOpts)
  const files = env.outputFiles()

  return {files}

  //const runner = Runner.create(generatorName, {})
  //await runner.parseArgs()
  //await runner.run()
  //process.exit()

}


text:
"""Standard RDFValues."""

import re
import urlparse

from grr.lib import config_lib
from grr.lib import rdfvalue
from grr.lib import type_info
from grr.lib.rdfvalues import structs as rdf_structs
from grr.proto import jobs_pb2
from grr.proto import sysinfo_pb2

class RegularExpression(rdfvalue.RDFString):
  """A semantic regular expression."""

  context_help_url = "user_manual.html#_regex_matches"

  def ParseFromString(self, value):
    super(RegularExpression, self).ParseFromString(value)

    # Check that this is a valid regex.
    try:
      self._regex = re.compile(self._value, flags=re.I | re.S | re.M)
    except re.error:
      raise type_info.TypeValueError("Not a valid regular expression.")

  def Search(self, text):
    """Search the text for our value."""
    if isinstance(text, rdfvalue.RDFString):
      text = str(text)

    return self._regex.search(text)

  def Match(self, text):
    if isinstance(text, rdfvalue.RDFString):
      text = str(text)

    return self._regex.match(text)

  def FindIter(self, text):
    if isinstance(text, rdfvalue.RDFString):
      text = str(text)

    return self._regex.finditer(text)

  def __str__(self):
    return "<RegularExpression: %r/>" % self._value

class LiteralExpression(rdfvalue.RDFBytes):
  """A RDFBytes literal for use in GrepSpec."""

  context_help_url = "user_manual.html#_literal_matches"

class EmailAddress(rdfvalue.RDFString):
  """An email address must be well formed."""

  _EMAIL_REGEX = re.compile(r"[^@]+@([^@]+)$")

  def ParseFromString(self, value):
    super(EmailAddress, self).ParseFromString(value)

    self._match = self._EMAIL_REGEX.match(self._value)
    if not self._match:
      raise ValueError("Email address %r not well formed." % self._value)

class DomainEmailAddress(EmailAddress):
  """A more restricted email address may only address the domain."""

  def ParseFromString(self, value):
    super(DomainEmailAddress, self).ParseFromString(value)

    domain = config_lib.CONFIG["Logging.domain"]
    if domain and self._match.group(1) != domain:
      raise ValueError("Email address '%s' does not belong to the configured "
                       "domain '%s'" % (self._match.group(1), domain))

class AuthenticodeSignedData(rdf_structs.RDFProtoStruct):
  protobuf = jobs_pb2.AuthenticodeSignedData

class PersistenceFile(rdf_structs.RDFProtoStruct):
  protobuf = jobs_pb2.PersistenceFile

class URI(rdf_structs.RDFProtoStruct):
  """Represets a URI with its individual components seperated."""
  protobuf = sysinfo_pb2.URI

  def ParseFromString(self, value):
    url = urlparse.urlparse(value)

    if url.scheme:
      self.transport = url.scheme
    if url.netloc:
      self.host = url.netloc
    if url.path:
      self.path = url.path
    if url.query:
      self.query = url.query
    if url.fragment:
      self.fragment = url.fragment

  def SerializeToString(self):
    url = (self.transport, self.host, self.path, self.query, self.fragment)
    return str(urlparse.urlunsplit(url))