text:
package org.apache.hadoop.hive.ql.udf.generic;

import java.sql.Date;
import java.sql.Timestamp;

import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredJavaObject;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredObject;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.hive.serde2.io.TimestampWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;

import junit.framework.TestCase;

public class TestGenericUDFTrunc extends TestCase {

  public void testStringToDateWithMonthFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("MONTH"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new Text("2014-01-01"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-14"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-31"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-02"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-28"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-03"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-28"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-29"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    // test timestamp string
    valueObj0 = new DeferredJavaObject(new Text("2014-01-01 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-14 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-31 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-02 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-28 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-03 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-28 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-29 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);
  }

  public void testStringToDateWithQuarterFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("QUARTER"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new Text("2014-01-01"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-14"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-31"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-02"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-28"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-03"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-28"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-29"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-05-11"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-04-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-07-01"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-07-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-12-31"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-10-01", udf, initArgs, evalArgs);

    // test timestamp string
    valueObj0 = new DeferredJavaObject(new Text("2014-01-01 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-14 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-31 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-02 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-28 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-03 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-28 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-29 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-05-11 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-04-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-07-01 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-07-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-12-31 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-10-01", udf, initArgs, evalArgs);
  }

  public void testStringToDateWithYearFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("YEAR"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new Text("2014-01-01"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-14"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-31"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-02"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-28"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-03"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-28"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-29"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    // test timestamp string
    valueObj0 = new DeferredJavaObject(new Text("2014-01-01 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-14 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-01-31 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-02 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2014-02-28 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-03 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-28 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new Text("2016-02-29 10:30:45"));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);
  }

  public void testTimestampToDateWithMonthFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableTimestampObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("MON"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-01 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-14 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-31 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-02 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-28 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-03 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-28 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-29 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    // test timestamp string
    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-01 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-14 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-31 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-02 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-28 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-03 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-28 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-29 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);
  }

  public void testTimestampToDateWithQuarterFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableTimestampObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("Q"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-01 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-14 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-31 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-02 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-28 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-03 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-28 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-29 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-05-11 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-04-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-07-01 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-07-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-12-31 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-10-01", udf, initArgs, evalArgs);

    // test timestamp string
    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-01 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-14 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-31 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-02 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-28 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-03 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-28 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-29 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-05-11 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-04-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-07-01 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-07-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-12-31 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-10-01", udf, initArgs, evalArgs);
  }

  public void testTimestampToDateWithYearFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableTimestampObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("YYYY"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-01 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-14 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-31 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-02 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-28 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-03 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-28 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-29 00:00:00")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    // test timestamp string
    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-01 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-14 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-01-31 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-02 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2014-02-28 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-03 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-28 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new TimestampWritable(
        Timestamp.valueOf("2016-02-29 10:30:45")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);
  }

  public void testDateWritableToDateWithMonthFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableDateObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("MM"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-01")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-14")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-31")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-02-02")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-02-28")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-03")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-28")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-29")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-02-01", udf, initArgs, evalArgs);
  }

  public void testDateWritableToDateWithQuarterFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableDateObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("Q"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-01")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-14")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-31")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-02-02")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-02-28")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-03")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-28")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-29")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-05-11")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-04-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-07-01")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-07-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-12-31")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-10-01", udf, initArgs, evalArgs);
  }

  public void testDateWritableToDateWithYearFormat() throws HiveException {
    GenericUDFTrunc udf = new GenericUDFTrunc();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableDateObjectInspector;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    ObjectInspector[] initArgs = { valueOI0, valueOI1};

    DeferredObject valueObjFmt = new DeferredJavaObject(new Text("YY"));

    DeferredObject valueObj0;
    DeferredObject[] evalArgs;

    // test date string
    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-01")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-14")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-01-31")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-02-02")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2014-02-28")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2014-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-03")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-28")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);

    valueObj0 = new DeferredJavaObject(new DateWritable(Date.valueOf("2016-02-29")));
    evalArgs = new DeferredObject[] { valueObj0, valueObjFmt };
    runAndVerify("2016-01-01", udf, initArgs, evalArgs);
  }

  private void runAndVerify(String expResult, GenericUDF udf, ObjectInspector[] initArgs,
      DeferredObject[] evalArgs) throws HiveException {
    udf.initialize(initArgs);
    Text output = (Text) udf.evaluate(evalArgs);
    assertEquals("frist_day() test ", expResult, output.toString());
  }
}


text:
extern "Java"
{
  namespace java
  {
    namespace awt
    {
        class Rectangle;
        class Shape;
      namespace geom
      {
          class AffineTransform;
          class Area;
          class Area$CubicSegment;
          class Area$Intersection;
          class Area$LineSegment;
          class Area$QuadSegment;
          class Area$Segment;
          class CubicCurve2D;
          class PathIterator;
          class Point2D;
          class Rectangle2D;
      }
    }
  }
}

class java::awt::geom::Area : public ::java::lang::Object
{

public:
  Area();
  Area(::java::awt::Shape *);
  virtual void add(::java::awt::geom::Area *);
  virtual void subtract(::java::awt::geom::Area *);
  virtual void intersect(::java::awt::geom::Area *);
  virtual void exclusiveOr(::java::awt::geom::Area *);
  virtual void reset();
  virtual jboolean isEmpty();
  virtual jboolean isPolygonal();
  virtual jboolean isRectangular();
  virtual jboolean isSingular();
  virtual ::java::awt::geom::Rectangle2D * getBounds2D();
  virtual ::java::awt::Rectangle * getBounds();
  virtual ::java::lang::Object * clone();
  virtual jboolean equals(::java::awt::geom::Area *);
  virtual void transform(::java::awt::geom::AffineTransform *);
  virtual ::java::awt::geom::Area * createTransformedArea(::java::awt::geom::AffineTransform *);
  virtual jboolean contains(jdouble, jdouble);
  virtual jboolean contains(::java::awt::geom::Point2D *);
  virtual jboolean contains(jdouble, jdouble, jdouble, jdouble);
  virtual jboolean contains(::java::awt::geom::Rectangle2D *);
  virtual jboolean intersects(jdouble, jdouble, jdouble, jdouble);
  virtual jboolean intersects(::java::awt::geom::Rectangle2D *);
  virtual ::java::awt::geom::PathIterator * getPathIterator(::java::awt::geom::AffineTransform *);
  virtual ::java::awt::geom::PathIterator * getPathIterator(::java::awt::geom::AffineTransform *, jdouble);
private:
  ::java::util::Vector * weilerAtherton(::java::util::Vector *);
  jint getRecursionDepth(::java::awt::geom::Area$CubicSegment *);
  void recursiveSubdivide(::java::awt::geom::CubicCurve2D *, ::java::awt::geom::CubicCurve2D *, jint, jint, jdouble, jdouble, jdouble, jdouble);
public: // actually package-private
  virtual JArray< ::java::awt::geom::Area$Intersection * > * cubicCubicIntersect(::java::awt::geom::Area$CubicSegment *, ::java::awt::geom::Area$CubicSegment *);
  virtual JArray< ::java::awt::geom::Area$Intersection * > * lineQuadIntersect(::java::awt::geom::Area$LineSegment *, ::java::awt::geom::Area$QuadSegment *);
  virtual JArray< ::java::awt::geom::Area$Intersection * > * lineCubicIntersect(::java::awt::geom::Area$LineSegment *, ::java::awt::geom::Area$CubicSegment *);
  virtual ::java::awt::geom::Area$Intersection * linesIntersect(::java::awt::geom::Area$LineSegment *, ::java::awt::geom::Area$LineSegment *);
  virtual jboolean pointEquals(::java::awt::geom::Point2D *, ::java::awt::geom::Point2D *);
private:
  ::java::util::Vector * makeSegment(::java::awt::Shape *);
  jint createNodes(::java::awt::geom::Area$Segment *, ::java::awt::geom::Area$Segment *);
  jint createNodesSelf(::java::awt::geom::Area$Segment *);
  void deleteRedundantPaths(::java::util::Vector *);
  void setDirection(::java::util::Vector *, jboolean);
  static jdouble EPSILON;
  static jdouble RS_EPSILON;
  static jdouble PE_EPSILON;
public: // actually package-private
  ::java::util::Vector * __attribute__((aligned(__alignof__( ::java::lang::Object)))) solids;
  ::java::util::Vector * holes;
private:
  ::java::util::Vector * cc_intersections;
  jint windingRule;
public:
  static ::java::lang::Class class$;
};

#endif // __java_awt_geom_Area__

redpajama_set_name: RedPajamaGithub


text:
NSString *const XMPPProcessOneSessionID = @"XMPPProcessOneSessionID";
NSString *const XMPPProcessOneSessionJID = @"XMPPProcessOneSessionJID";
NSString *const XMPPProcessOneSessionDate = @"XMPPProcessOneSessionDate";

@interface XMPPProcessOne ()
{
	NSXMLElement *pushConfiguration;
	BOOL pushConfigurationSent;
	BOOL pushConfigurationConfirmed;
	NSString *pushIQID;
}

- (void)sendPushConfiguration;

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation XMPPProcessOne

- (id)initWithDispatchQueue:(dispatch_queue_t)queue
{
	if ((self = [super initWithDispatchQueue:NULL]))
	{
		pushConfiguration = nil;
		pushConfigurationSent = YES;
		pushConfigurationConfirmed = YES;
	}
	return self;
}

- (NSString *)savedSessionID
{
	return [[NSUserDefaults standardUserDefaults] stringForKey:XMPPProcessOneSessionID];
}

- (void)setSavedSessionID:(NSString *)savedSessionID
{
	if (savedSessionID)
		[[NSUserDefaults standardUserDefaults] setObject:savedSessionID forKey:XMPPProcessOneSessionID];
	else
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:XMPPProcessOneSessionID];
}

- (XMPPJID *)savedSessionJID
{
	NSString *sessionJidStr = [[NSUserDefaults standardUserDefaults] stringForKey:XMPPProcessOneSessionJID];

	return [XMPPJID jidWithString:sessionJidStr];
}

- (void)setSavedSessionJID:(XMPPJID *)savedSessionJID
{
	NSString *sessionJidStr = [savedSessionJID full];

	if (sessionJidStr)
		[[NSUserDefaults standardUserDefaults] setObject:sessionJidStr forKey:XMPPProcessOneSessionJID];
	else
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:XMPPProcessOneSessionJID];
}

- (NSDate *)savedSessionDate
{
	return [[NSUserDefaults standardUserDefaults] objectForKey:XMPPProcessOneSessionDate];
}

- (void)setSavedSessionDate:(NSDate *)savedSessionDate
{
	if (savedSessionDate)
		[[NSUserDefaults standardUserDefaults] setObject:savedSessionDate forKey:XMPPProcessOneSessionDate];
	else
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:XMPPProcessOneSessionDate];
}

- (NSXMLElement *)pushConfiguration
{
	if (dispatch_get_specific(moduleQueueTag))
	{
		return pushConfiguration;
	}
	else
	{
		__block NSXMLElement *result = nil;

		dispatch_sync(moduleQueue, ^{
			result = [pushConfiguration copy];
		});

		return result;
	}
}

- (void)setPushConfiguration:(NSXMLElement *)pushConfig
{
	NSXMLElement *newPushConfiguration = [pushConfig copy];

	dispatch_block_t block = ^{

		if (pushConfiguration == nil && newPushConfiguration == nil)
		{
			return;
		}

		pushConfiguration = newPushConfiguration;
		pushConfigurationSent = NO;
		pushConfigurationConfirmed = NO;

		if ([xmppStream isAuthenticated])
		{
			[self sendPushConfiguration];
		}
	};

	if (dispatch_get_specific(moduleQueueTag))
		block();
	else
		dispatch_async(moduleQueue, block);
}

- (void)sendPushConfiguration
{
	if (pushConfiguration)
	{
		pushIQID = [XMPPStream generateUUID];
		NSXMLElement *push = [pushConfiguration copy];

		XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:nil elementID:pushIQID child:push];

		[xmppStream sendElement:iq];
		pushConfigurationSent = YES;
	}
	else
	{
		// <iq type='set'>
		//   <disable xmlns='p1:push'>
		// </iq>

		NSXMLElement *disable = [NSXMLElement elementWithName:@"disable" xmlns:@"p1:push"];

		XMPPIQ *iq = [XMPPIQ iqWithType:@"set" child:disable];

		[xmppStream sendElement:iq];
		pushConfigurationSent = YES;
	}
}

- (XMPPElementReceipt *)goOnStandby
{
	// <standby>true</standby>

	NSXMLElement *standby = [NSXMLElement elementWithName:@"standby" stringValue:@"true"];

	XMPPElementReceipt *receipt = nil;
	[xmppStream sendElement:standby andGetReceipt:&receipt];

	return receipt;
}

- (XMPPElementReceipt *)goOffStandby
{
	// <standby>false</standby>

	NSXMLElement *standby = [NSXMLElement elementWithName:@"standby" stringValue:@"false"];

	XMPPElementReceipt *receipt = nil;
	[xmppStream sendElement:standby andGetReceipt:&receipt];

	return receipt;
}

- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
	if (!pushConfigurationSent)
	{
		[self sendPushConfiguration];
	}
}

- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
	if (pushConfigurationConfirmed)
	{
		self.savedSessionDate = [[NSDate alloc] init];
	}
	else
	{
		// The pushConfiguration was sent to the server, but we never received a confirmation.
		// So either the pushConfiguration never made it to the server,
		// or we got disconnected before we received the confirmation from the server.
		//
		// To be sure, we need to resent the pushConfiguration next time we authenticate.

		pushConfigurationSent = NO;
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration Elements
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

+ (NSXMLElement *)pushConfigurationContainer
{
	return [NSXMLElement elementWithName:@"push" xmlns:@"p1:push"];
}

+ (NSXMLElement *)keepaliveWithMax:(NSTimeInterval)max
{
	// keepalive is the max interval between keepalive events received by server
	// before going out of reception (in seconds)

	NSString *maxStr = [NSString stringWithFormat:@"%.0f", max];

	NSXMLElement *keepalive = [NSXMLElement elementWithName:@"keepalive"];
	[keepalive addAttributeWithName:@"max" stringValue:maxStr];

	return keepalive;
}

+ (NSXMLElement *)sessionWithDuration:(NSTimeInterval)durationInSeconds
{
	// session is the max time the session is kept before automatically
	// closing the session while in push mode (in minutes).
	//
	// Max session is 24 hours.
	// Server can decide to force the session close anyway, if the message queue is getting large.

	double durationInMinutes = durationInSeconds / 60.0;

	NSString *durationStr = [NSString stringWithFormat:@"%.0f", durationInMinutes];

	NSXMLElement *session = [NSXMLElement elementWithName:@"session"];
	[session addAttributeWithName:@"duration" stringValue:durationStr];

	return session;
}

+ (NSXMLElement *)statusWithType:(NSString *)type message:(NSString *)message
{
	// status (optional) is the XMPP status the user should appear in,
	// and the message when the XMPP session is not linked to a TCP connection.
	//
	// If omittted, the presence and status is not change when going into disconnected opened session.

	NSXMLElement *status = [NSXMLElement elementWithName:@"status"];

	if (type)
		[status addAttributeWithName:@"type" stringValue:type];

	if (message)
		[status setStringValue:message];

	return status;
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation XMPPRebindAuthentication
{
  #if __has_feature(objc_arc_weak)
	__weak XMPPStream *xmppStream;
  #else
	__unsafe_unretained XMPPStream *xmppStream;
  #endif

	NSString *sessionID;
	XMPPJID *sessionJID;
}

+ (NSString *)mechanismName
{
	return nil;
}

- (id)initWithStream:(XMPPStream *)stream password:(NSString *)password
{
	if ((self = [super init]))
	{
		xmppStream = stream;
	}
	return self;
}

- (id)initWithStream:(XMPPStream *)stream sessionID:(NSString *)aSessionID sessionJID:(XMPPJID *)aSessionJID
{
	if ((self = [super init]))
	{
		xmppStream = stream;
		sessionID = aSessionID;
		sessionJID = aSessionJID;
	}
	return self;
}

- (BOOL)start:(NSError **)errPtr
{
	if (!sessionID || !sessionJID)
	{
		NSString *errMsg = @"Missing sessionID and/or sessionJID.";
		NSDictionary *info = @{NSLocalizedDescriptionKey : errMsg};

		NSError *err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];

		if (errPtr) *errPtr = err;
		return NO;
	}

	// <rebind xmlns="p1:rebind">
	//   <jid>user@domain/resource</jid>
	//   <sid>123456789</sid>
	// </rebind>

	NSXMLElement *jid = [NSXMLElement elementWithName:@"jid" stringValue:[sessionJID full]];
	NSXMLElement *sid = [NSXMLElement elementWithName:@"sid" stringValue:sessionID];

	NSXMLElement *rebind = [NSXMLElement elementWithName:@"rebind" xmlns:@"p1:rebind"];
	[rebind addChild:jid];
	[rebind addChild:sid];

	[xmppStream sendAuthElement:rebind];
	return YES;
}

- (XMPPHandleAuthResponse)handleAuth:(NSXMLElement *)response
{
	if ([[response name] isEqualToString:@"rebind"])
	{
		return XMPP_AUTH_SUCCESS;
	}
	else
	{
		return XMPP_AUTH_FAIL;
	}
}

- (BOOL)shouldResendOpeningNegotiationAfterSuccessfulAuthentication
{
	return NO;
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation XMPPStream (XMPPProcessOne)

- (BOOL)supportsPush
{
	__block BOOL result = NO;

	dispatch_block_t block = ^{ @autoreleasepool {

		// The root element can be properly queried anytime after the
		// stream:features are received, and TLS has been setup (if required)
		if (self.state >= STATE_XMPP_POST_NEGOTIATION)
		{
			NSXMLElement *features = [self.rootElement elementForName:@"stream:features"];
			NSXMLElement *push = [features elementForName:@"push" xmlns:@"p1:push"];

			result = (push != nil);
		}
	}};

	if (dispatch_get_specific(self.xmppQueueTag))
		block();
	else
		dispatch_sync(self.xmppQueue, block);

	return result;
}

- (BOOL)supportsRebind
{
	__block BOOL result = NO;

	dispatch_block_t block = ^{ @autoreleasepool {

		// The root element can be properly queried anytime after the
		// stream:features are received, and TLS has been setup (if required)
		if (self.state >= STATE_XMPP_POST_NEGOTIATION)
		{
			NSXMLElement *features = [self.rootElement elementForName:@"stream:features"];
			NSXMLElement *rebind = [features elementForName:@"rebind" xmlns:@"p1:rebind"];

			result = (rebind != nil);
		}
	}};

	if (dispatch_get_specific(self.xmppQueueTag))
		block();
	else
		dispatch_sync(self.xmppQueue, block);

	return result;
}

- (NSString *)rebindSessionID
{
	return [[self rootElement] attributeStringValueForName:@"id"];
}

@end


text:
class turbidityClass{
  public:
    turbidityClass();
    void SETUP();
    void TURBIDITY();
    void PRINT();
    // variable
    int turbidityAnalogPin;
    float turbidityVoltageOutput;

};

extern turbidityClass turbidity;

#endif


text:
from itertools import combinations

import numpy as np

from pyparsing import alphas, Combine, Literal, Optional, nums, Word

from pgmpy.models import BayesianModel, MarkovModel
from pgmpy.factors import TabularCPD, Factor
from pgmpy.extern.six.moves import map, range

class UAIReader(object):
    """
    Class for reading UAI file format from files or strings.
    """
    def __init__(self, path=None, string=None):
        """
        Initialize an instance of UAI reader class

        Parameters
        ----------
        path : file or str
            Path of the file containing UAI information.

        string : str
            String containing UAI information.

        Example
        -------
        >>> reader = UAIReader('TestUai.uai')

        Reference
        ---------
        http://graphmod.ics.uci.edu/uai08/FileFormat
        """
        if path:
            data = open(path)
            self.network = data.read()
        elif string:
            self.network = string
        else:
            raise ValueError("Must specify either path or string.")
        self.grammar = self.get_grammar()
        self.network_type = self.get_network_type()
        self.variables = self.get_variables()
        self.domain = self.get_domain()
        self.edges = self.get_edges()
        self.tables = self.get_tables()

    def get_grammar(self):
        """
        Returns the grammar of the UAI file.
        """
        network_name = Word(alphas).setResultsName('network_name')
        no_variables = Word(nums).setResultsName('no_variables')
        grammar = network_name + no_variables
        self.no_variables = int(grammar.parseString(self.network)['no_variables'])
        domain_variables = (Word(nums)*self.no_variables).setResultsName('domain_variables')
        grammar += domain_variables
        no_functions = Word(nums).setResultsName('no_functions')
        grammar += no_functions
        self.no_functions = int(grammar.parseString(self.network)['no_functions'])
        integer = Word(nums).setParseAction(lambda t: int(t[0]))
        for function in range(0, self.no_functions):
            scope_grammar = Word(nums).setResultsName('fun_scope_' + str(function))
            grammar += scope_grammar
            function_scope = grammar.parseString(self.network)['fun_scope_' + str(function)]
            function_grammar = ((integer)*int(function_scope)).setResultsName('fun_' + str(function))
            grammar += function_grammar

        floatnumber = Combine(Word(nums) + Optional(Literal(".") + Optional(Word(nums))))
        for function in range(0, self.no_functions):
            no_values_grammar = Word(nums).setResultsName('fun_no_values_' + str(function))
            grammar += no_values_grammar
            no_values = grammar.parseString(self.network)['fun_no_values_' + str(function)]
            values_grammar = ((floatnumber)*int(no_values)).setResultsName('fun_values_' + str(function))
            grammar += values_grammar
        return grammar

    def get_network_type(self):
        """
        Returns the type of network defined by the file.

        Returns
        -------
        string : str
            String containing network type.

        Example
        -------
        >>> reader = UAIReader('TestUAI.uai')
        >>> reader.get_network_type()
        'MARKOV'
        """
        network_type = self.grammar.parseString(self.network)
        return network_type['network_name']

    def get_variables(self):
        """
        Returns a list of variables.
        Each variable is represented by an index of list.
        For example if the no of variables are 4 then the list will be
        [var_0, var_1, var_2, var_3]

        Returns
        -------
        list: list of variables

        Example
        -------
        >>> reader = UAIReader('TestUAI.uai')
        >>> reader.get_variables()
        ['var_0', 'var_1', 'var_2']
        """
        variables = []
        for var in range(0, self.no_variables):
            var_name = "var_" + str(var)
            variables.append(var_name)
        return variables

    def get_domain(self):
        """
        Returns the dictionary of variables with keys as variable name
        and values as domain of the variables.

        Returns
        -------
        dict: dictionary containing variables and their domains

        Example
        -------
        >>> reader = UAIReader('TestUAI.uai')
        >>> reader.get_domain()
        {'var_0': '2', 'var_1': '2', 'var_2': '3'}
        """
        domain = {}
        var_domain = self.grammar.parseString(self.network)['domain_variables']
        for var in range(0, len(var_domain)):
            domain["var_" + str(var)] = var_domain[var]
        return domain

    def get_edges(self):
        """
        Returns the edges of the network.

        Returns
        -------
        set: set containing the edges of the network

        Example
        -------
        >>> reader = UAIReader('TestUAI.uai')
        >>> reader.get_edges()
        {('var_0', 'var_1'), ('var_0', 'var_2'), ('var_1', 'var_2')}
        """
        edges = []
        for function in range(0, self.no_functions):
            function_variables = self.grammar.parseString(self.network)['fun_' + str(function)]
            if isinstance(function_variables, int):
                function_variables = [function_variables]
            if self.network_type == 'BAYES':
                child_var = "var_" + str(function_variables[-1])
                function_variables = function_variables[:-1]
                for var in function_variables:
                    edges.append((child_var, "var_" + str(var)))
            elif self.network_type == "MARKOV":
                function_variables = ["var_" + str(var) for var in function_variables]
                edges.extend(list(combinations(function_variables, 2)))
        return set(edges)

    def get_tables(self):
        """
        Returns list of tuple of child variable and CPD in case of Bayesian
        and list of tuple of scope of variables and values in case of Markov.

        Returns
        -------
        list : list of tuples of child variable and values in Bayesian
            list of tuples of scope of variables and values in case of Markov.

        Example
        -------
        >>> reader = UAIReader('TestUAI.uai')
        >>> reader.get_tables()
        [(['var_0', 'var_1'], ['4.000', '2.400', '1.000', '0.000']),
         (['var_0', 'var_1', 'var_2'],
          ['2.2500', '3.2500', '3.7500', '0.0000', '0.0000', '10.0000',
           '1.8750', '4.0000', '3.3330', '2.0000', '2.0000', '3.4000'])]
        """
        tables = []
        for function in range(0, self.no_functions):
            function_variables = self.grammar.parseString(self.network)['fun_' + str(function)]
            if isinstance(function_variables, int):
                function_variables = [function_variables]
            if self.network_type == 'BAYES':
                child_var = "var_" + str(function_variables[-1])
                values = self.grammar.parseString(self.network)['fun_values_' + str(function)]
                tables.append((child_var, list(values)))
            elif self.network_type == "MARKOV":
                function_variables = ["var_" + str(var) for var in function_variables]
                values = self.grammar.parseString(self.network)['fun_values_' + str(function)]
                tables.append((function_variables, list(values)))
        return tables

    def get_model(self):
        """
        Returns an instance of Bayesian Model or Markov Model.
        Varibles are in the pattern var_0, var_1, var_2 where var_0 is
        0th index variable, var_1 is 1st index variable.

        Return
        ------
        model: an instance of Bayesian or Markov Model.

        Examples
        --------
        >>> reader = UAIReader('TestUAI.uai')
        >>> reader.get_model()
        """
        if self.network_type == 'BAYES':
            model = BayesianModel(self.edges)

            tabular_cpds = []
            for cpd in self.tables:
                child_var = cpd[0]
                states = int(self.domain[child_var])
                arr = list(map(float, cpd[1]))
                values = np.array(arr)
                values = values.reshape(states, values.size // states)
                tabular_cpds.append(TabularCPD(child_var, states, values))

            model.add_cpds(*tabular_cpds)
            return model

        elif self.network_type == 'MARKOV':
            model = MarkovModel(self.edges)

            factors = []
            for table in self.tables:
                variables = table[0]
                cardinality = [int(self.domain[var]) for var in variables]
                value = list(map(float, table[1]))
                factor = Factor(variables=variables, cardinality=cardinality, values=value)
                factors.append(factor)

            model.add_factors(*factors)
            return model

class UAIWriter(object):
    """
    Class for writing models in UAI.
    """
    def __init__(self, model):
        """
        Initialize an instance of UAI writer class

        Parameters
        ----------
        model: A Bayesian or Markov model
            The model to write
        """
        if isinstance(model, BayesianModel):
            self.network = "BAYES\n"
        elif isinstance(model, MarkovModel):
            self.network = "MARKOV\n"
        else:
            raise TypeError("Model must be an instance of Bayesian or Markov model.")

        self.model = model
        self.no_nodes = self.get_nodes()
        self.domain = self.get_domain()
        self.functions = self.get_functions()
        self.tables = self.get_tables()

    def __str__(self):
        """
        Returns the UAI file as a string.
        """
        self.network += self.no_nodes + "\n"
        domain = sorted(self.domain.items(), key=lambda x: (x[1], x[0]))
        self.network += " ".join([var[1] for var in domain]) + "\n"
        self.network += str(len(self.functions)) + "\n"
        for fun in self.functions:
            self.network += str(len(fun)) + " "
            self.network += " ".join(fun) + "\n"
        self.network += "\n"
        for table in self.tables:
            self.network += str(len(table)) + "\n"
            self.network += " ".join(table) + "\n"
        return self.network[:-1]

    def get_nodes(self):
        """
        Adds variables to the network.

        Example
        -------
        >>> writer = UAIWriter(model)
        >>> writer.get_nodes()
        """
        no_nodes = len(self.model.nodes())
        return str(no_nodes)

    def get_domain(self):
        """
        Adds domain of each variable to the network.

        Example
        -------
        >>> writer = UAIWriter(model)
        >>> writer.get_domain()
        """
        if isinstance(self.model, BayesianModel):
            cpds = self.model.get_cpds()
            cpds.sort(key=lambda x: x.variable)
            domain = {}
            for cpd in cpds:
                domain[cpd.variable] = str(cpd.variable_card)
            return domain
        elif isinstance(self.model, MarkovModel):
            factors = self.model.get_factors()
            domain = {}
            for factor in factors:
                variables = factor.variables
                for var in variables:
                    if var not in domain:
                        domain[var] = str(factor.get_cardinality([var])[var])
            return domain
        else:
            raise TypeError("Model must be an instance of Markov or Bayesian model.")

    def get_functions(self):
        """
        Adds functions to the network.

        Example
        -------
        >>> writer = UAIWriter(model)
        >>> writer.get_functions()
        """
        if isinstance(self.model, BayesianModel):
            cpds = self.model.get_cpds()
            cpds.sort(key=lambda x: x.variable)
            variables = sorted(self.domain.items(), key=lambda x: (x[1], x[0]))
            functions = []
            for cpd in cpds:
                child_var = cpd.variable
                evidence = cpd.evidence
                function = [str(variables.index((var, self.domain[var]))) for var in evidence]
                function.append(str(variables.index((child_var, self.domain[child_var]))))
                functions.append(function)
            return functions
        elif isinstance(self.model, MarkovModel):
            factors = self.model.get_factors()
            functions = []
            variables = sorted(self.domain.items(), key=lambda x: (x[1], x[0]))
            for factor in factors:
                scope = factor.scope()
                function = [str(variables.index((var, self.domain[var]))) for var in scope]
                functions.append(function)
            return functions
        else:
            raise TypeError("Model must be an instance of Markov or Bayesian model.")

    def get_tables(self):
        """
        Adds tables to the network.

        Example
        -------
        >>> writer = UAIWriter(model)
        >>> writer.get_tables()
        """
        if isinstance(self.model, BayesianModel):
            cpds = self.model.get_cpds()
            cpds.sort(key=lambda x: x.variable)
            tables = []
            for cpd in cpds:
                values = list(map(str, cpd.values.ravel()))
                tables.append(values)
            return tables
        elif isinstance(self.model, MarkovModel):
            factors = self.model.get_factors()
            tables = []
            for factor in factors:
                values = list(map(str, factor.values.ravel()))
                tables.append(values)
            return tables
        else:
            raise TypeError("Model must be an instance of Markov or Bayesian model.")

    def write_uai(self, filename):
        """
        Write the xml data into the file.

        Parameters
        ----------
        filename: Name of the file.

        Examples
        -------
        >>> writer = UAIWriter(model)
        >>> writer.write_xmlbif(test_file)
        """
        writer = self.__str__()
        with open(filename, 'w') as fout:
            fout.write(writer)


text:
class SimpleKitError(Exception):
    pass

class MailException(SimpleKitError):
    pass

class GeneralError(SimpleKitError):
    """

    """

class ContainerNotFound(SimpleKitError):
    """Container Not Found Exception

    """

class ImageNotFound(SimpleKitError):
    """Image Not Found

    """

class ImageConflict(SimpleKitError):
    """Image Conflict

    """


text:
title: Setting Up Python Web Framework Django and Flask
---
In this article, we shall be discussing how to install Django and Flask - two popular web frameworks written in Python.

Perhaps you are already familiar with the widespread usage and community support for Python; in web-development. You might as well be aware as to what a web framework is; and the options available for Python.

In case these assumptions are untrue, you might want to take a look at this wiki article. If you are all caught up, let's go ahread with setting up Python web frameworks in your local development machine.

But it would be unfair if we completely ignore the Python 2 vs Python 3 debate.

If you do not have Python already installed check out our Python Installation Guide

## Virtual environment

Before we install Django we will get you to install an extremely useful tool to help keep your coding environment tidy on your computer. It's possible to skip this step, but it's highly recommended. Starting with the best possible setup will save you a lot of trouble in the future!

So, let's create a virtual environment (also called a virtualenv). Virtualenv will isolate your Python/Django setup on a per-project basis. This means that any changes you make to one website won't affect any others you're also developing. Neat, right?

For more information on virtual environments see the relevent section here.

## Wrapping Up

If you have already installed `pip` then simply:
```
$ pip install django
```
After installation it's complete we can create a new project:
```
$ django-admin startproject myproject
$ cd myproject
$ python manage.py runserver
```
Go to `http://localhost:8000`! :rocket:

We have successfully installed the web-framework of our need. However, it's not yet complete. Most web applications are content and data driven - so we need a data storage. Or, a Database, if you will.

In next article, we would be discussing how to install PostgreSQL and use it with our Python web application.

A point to ponder - we have been using `pip` heavily, but we have barely said anything about it. Well, for now, it's just a package manager like `npm`. It has some differences with `npm`; but, you don't need to worry about that now. If you are interested, do check out the official `pip` documentation.

_If you have suggestions or questions, come join us on gitter_.


text:
html, body,
.container {
	position: relative;
	width: 100%;
	height: 100%;
}

body {
	overflow-y: scroll;
	background: #333;
}

.splitlayout {
	position: relative;
	overflow-x: hidden;
	min-height: 100%;
	width: 100%;
}

/* Intro sides */
.side {
	position: fixed;
	top: 0;
	z-index: 100;
	width: 50%;
	height: 100%;
	text-align: center;
	-webkit-backface-visibility: hidden;
}

.open-left .side,
.open-right .side {
	cursor: default;
}

.overlay {
	position: absolute;
	top: 0;
	left: 0;
	z-index: 499;
	visibility: hidden;
	width: 100%;
	height: 100%;
	opacity: 0;
}

.side-left .overlay {
	background: rgba(0,0,0,0.7);
}

.side-right .overlay {
	background: rgba(0,0,0,0.3);
}

.side-left {
	left: 0;
	background: #47a3da;
	color: #fff;
	outline: 1px solid #47a3da; /* avoid gap */
}

.side-right {
	right: 0;
	background: #fff;
	color: #47a3da;
	outline: 1px solid #fff; /* avoid gap */
}

/* Intro content, profile image and name, back button */
.intro-content {
	position: absolute;
	top: 50%;
	left: 50%;
	padding: 0 1em;
	width: 50%;
	cursor: pointer;
	-webkit-transform: translateY(-50%) translateX(-50%);
	transform: translateY(-50%) translateX(-50%);
}

.profile {
	margin: 0 auto;
	width: 220px;
	height: 22 0px;
	border-radius: 50%;
	background: #47a3da;
}

.profile img {
	max-width: 100%;
	border-radius: 50%;
	opacity: 0.6;
}

.intro-content h1 > span {
	display: block;
	white-space: nowrap;
}

.intro-content h1 > span:first-child {
	font-weight: 300;
	font-size: 2em;
}

.intro-content h1 > span:nth-child(2) {
	position: relative;
	margin-top: 0.5em;
	padding: 0.8em;
	text-transform: uppercase;
	letter-spacing: 1px;
	font-size: 0.8em;
}

.intro-content h1 > span:nth-child(2):before {
	position: absolute;
	top: 0;
	left: 25%;
	width: 50%;
	height: 2px;
	background: #fff;
	content: '';
}

.side-right .intro-content h1 > span:nth-child(2):before {
	background: #47a3da;
}

.back {
	position: fixed;
	top: 2.6em;
	z-index: 500;
	display: block;
	visibility: hidden;
	width: 50px;
	height: 50px;
	border-radius: 50%;
	color: #47a3da;
	text-align: center;
	font-size: 22px;
	line-height: 44px;
	opacity: 0;
	pointer-events: none;
}

.mobile-layout .back { /* fixed positioning will make this not clickable after scrolling on some mobile devices */
	position: absolute;
}

.back-left {
	left: 12.5%;
	-webkit-transform: translateX(-50%);
	transform: translateX(-50%);
}

.back-right {
	right: 12.5%;
	-webkit-transform: translateX(50%);
	transform: translateX(50%);
	color: #fff;
}

.open-right .back-left,
.open-left .back-right {
	visibility: visible;
	opacity: 1;
	-webkit-transition-delay: 0.3s;
	transition-delay: 0.3s;
	pointer-events: auto;
}

.back:hover {
	color: #ddd;
}

/* Pages */
.page {
	position: relative;
	top: 0;
	overflow: auto;
	min-height: 100%;
	width: 75%;
	height: auto;
	font-size: 1.4em;
	-webkit-backface-visibility: hidden;
}

.page-right {
	left: 25%;
	outline: 5px solid #ecf0f1; /* avoid rounding gaps */
	background: #ecf0f1;
	color: #97a8b2;
	-webkit-transform: translateX(100%);
	transform: translateX(100%);
}

.splitlayout.open-right {
	background: #ecf0f1;
}

.page-left {
	left: 0;
	outline: 5px solid #34495e; /* avoid rounding gaps */
	background: #34495e;
	color: #fff;
	text-align: right;
	-webkit-transform: translateX(-100%);
	transform: translateX(-100%);
}

.splitlayout.open-left {
	background: #34495e;
}

/* Inner page content */
.page-inner {
	padding: 2em;
}

.page-inner section {
	padding-bottom: 1em;
}

.page-inner h2 {
	margin: 0 0 1em 0;
	font-weight: 300;
	font-size: 2.4em;
}

.page-inner p {
	font-weight: 300;
	font-size: 1.2em;
}

/* All transitions */
.side,
.page {
	-webkit-transition: -webkit-transform 0.6s;
	transition: transform 0.6s;
}

.overlay {
	-webkit-transition: opacity 0.6s, visibility 0.1s 0.6s;
	transition: opacity 0.6s, visibility 0.1s 0.6s;
}

.intro-content {
	-webkit-transition: -webkit-transform 0.6s, top 0.6s;
	transition: transform 0.6s, top 0.6s;
}

.intro-content h1,
.back {
	-webkit-transition: opacity 0.3s;
	transition: opacity 0.3s;
}

/* Open and close */

/* We need to set the position and overflow for the respective page scroll */
.reset-layout .page,
.splitlayout.open-right .page-left,
.splitlayout.open-left .page-right,
.splitlayout.close-right .page-left,
.splitlayout.close-left .page-right {
	position: absolute;
	overflow: hidden;
	height: 100%;
}

.splitlayout.open-right .page-right,
.splitlayout.open-left .page-left {
	position: relative;
	overflow: auto;
	height: auto;
}

.open-right .side-left .overlay,
.open-left .side-right .overlay {
	visibility: visible;
	opacity: 1;
	-webkit-transition: opacity 0.6s;
	transition: opacity 0.6s;
}

/* Right side open */
.open-right .side-left {
	-webkit-transform: translateX(-60%);
	transform: translateX(-60%);
}

.open-right .side-right {
	z-index: 200;
	-webkit-transform: translateX(-150%);
	transform: translateX(-150%);
}

.close-right .side-right {
	z-index: 200;
}

.open-right .side-right .intro-content {
	-webkit-transform: translateY(-50%) translateX(0%) scale(0.6);
	transform: translateY(-50%) translateX(0%) scale(0.6);
}

.open-right .page-right {
	-webkit-transform: translateX(0%);
	transform: translateX(0%);
}

/* Left side open */
.open-left .side-right {
	-webkit-transform: translateX(60%);
	transform: translateX(60%);
}

.open-left .side-left {
	z-index: 200;
	-webkit-transform: translateX(150%);
	transform: translateX(150%);
}

.close-left .side-left {
	z-index: 200;
}

.open-left .side-left .intro-content {
	-webkit-transform: translateY(-50%) translateX(-100%) scale(0.6);
	transform: translateY(-50%) translateX(-100%) scale(0.6);
}

.open-left .codropsheader {
	opacity: 0;
	visibility: hidden;
	-webkit-transition: opacity 0.3s, visibility 0.1s 0.3s;
	transition: opacity 0.3s, visibility 0.1s 0.3s;
}

.open-left .page-left {
	-webkit-transform: translateX(0%);
	transform: translateX(0%);
}

/* Media Queries */
@media screen and (max-width: 83em) {
	.intro-content { font-size: 60%; }
}

@media screen and (max-width: 58em) {
	body { font-size: 90%; }
}

@media screen and (max-width: 49.4375em) {
	.open-right .side-right {
		-webkit-transform: translateX(-175%);
		transform: translateX(-175%);
	}

	.open-right .side-left {
		-webkit-transform: translateX(-100%);
		transform: translateX(-100%);
	}

	.open-left .side-right {
		-webkit-transform: translateX(100%);
		transform: translateX(100%);
	}

	.open-left .side-left {
		-webkit-transform: translateX(175%);
		transform: translateX(175%);
	}

	.page {
		width: 100%;
	}

	.page-right {
		left: 0;
		padding-left: 15%;
	}

	.page-left {
		padding-right: 15%;
	}

	.intro-content {
		width: 100%;
	}

	.open-right .side-right .intro-content {
		top: 100%;
		-webkit-transform: translateY(-150px) translateX(-12.5%) scale(0.5);
		transform: translateY(-150px) translateX(-12.5%) scale(0.5);
	}

	.open-left .side-left .intro-content {
		top: 100%;
		-webkit-transform: translateY(-150px) translateX(-87.5%) scale(0.5);
		transform: translateY(-150px) translateX(-87.5%) scale(0.5);
	}

	.open-right .intro-content h1,
	.open-left .intro-content h1 {
		opacity: 0;
	}

	.back-left {
		left: 6.25%;
	}

	.back-right {
		right: 6.25%;
	}
}

@media screen and (max-width: 42.5em) {
	body { font-size: 80%; }
	.intro-content { font-size: 50%; }
}

@media screen and (max-height: 41.125em) {
	.intro-content {
		-webkit-transform: translateY(-25%) translateX(-50%);
		transform: translateY(-25%) translateX(-50%);
	}
}

@media screen and (max-width: 39.375em) {
	.intro-content .profile { -webkit-transform: scale(0.5); transform: scale(0.5); }
}

@media screen and (max-width: 320px) {
	body { font-size: 70%; }
}


text:
<?php
declare(strict_types=1);

namespace App\Dto\User;

use App\Validator\Constraints as AppAssert;
use Symfony\Component\Validator\Constraints as Assert;

final class RequestPasswordResetRequest
{
    #[Assert\NotBlank]
    #[AppAssert\NotAnUser]
    #[AppAssert\NotAnEnabledUser]
    public string $username;

    /**
     * Used as honeypot. No need to validate.
     * Handler will silently fail if it is not an empty string.
     */
    public string $email = '';
}


text:
SpreeRetailops
==============

This extension provides API access points for use by the RetailOps direct Spree integration.

Installation
------------

Add spree_retailops to your Gemfile:

```ruby
gem 'spree_retailops', git: 'https://github.com/GudTech/spree_retailops.git'
```

Bundle your dependencies and run the installation generator:

```shell
bundle
bundle exec rails g spree_retailops:install
```

Extensibility
-------------

Spree is extensible, and the Spree RetailOps extension tries to accomodate your other and custom extensions.
Several explicit and implicit extension points are provided for your use.
I'm a hard-liner about namespace pollution, so all global names created or interrogated by this extension will include "retailops" in them somewhere.

* Catalog feeds have "Extensions" sections in the images, product details, and variants sections.  If you have added columns to the `spree_assets`, `spree_products`, or `spree_variants` tables (respectively), you can use the column names to set the columns.  Any validations you provide will be checked, and failures will be expressed in RetailOps as system alerts.  The values will be set as strings; ActiveRecord seems to be able to coerce numeric and boolean columns, but foreign keys could be problematic.

* If you have product data extensions which are NOT new columns in one of those three tables, or if you have more involved data such as foreign keys, you can define a method named `retailops_extend_#{name}=` on one of those three tables to catch and reroute or reparse extended values.  For instance, a definition like `def retailops_extend_foo=(value); end` will catch a setting of the extension field "foo".

* Any column which you add to the `Order`, `LineItem`, `Shipment`, `Adjustment`, `Address`, `Payment`, or `CreditCard` models will be expressed in the order import data automatically.  Beware that the RetailOps order importer will ignore any unrecognized data until custom development is done within RetailOps itself to use it.

* For products that RetailOps should never attempt to ship, such as gift cards, add a method `retailops_is_advisory?` on `Spree::Product` or `Spree::LineItem`.  The `spree_gift_card` extension is handled automatically if present.

* The handling of tracking data can be overridden by defining a method named `retailops_set_tracking` on `Spree::Shipment`.

* To do something interesting with detailed inventory data such as JIT counts, define a method `def retailops_notify_inventory(details); end` on `Spree::Variant`.  The details argument is a hash, which currently resembles `{ "all" => 12, "by_type" => { "internal" => 5, "jit" => 12, "dropship" => 0 } }` although more keys may be defined in the future.  Internal means inventory units available without using any JIT or Dropship provididers; JIT is the increment inventory permitted by allowing JIT, and Dropship likewise.

Copyright (c) 2014 Gud Technologies, Inc, released under the New BSD License


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Response\GetConversationItemsResponseMessageType.
 */

namespace jamesiarmes\PhpEws\Response;

/**
 * Defines the response message for a GetConversationItems request.
 *
 * @package php-ews\Response
 */
class GetConversationItemsResponseMessageType extends ResponseMessageType
{
    /**
     * Represents a single conversation.
     *
     * @since Exchange 2013
     *
     * @var \jamesiarmes\PhpEws\Type\ConversationResponseType
     */
    public $Conversation;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UrbanSketchers;
using UWP.Renderers;
using Windows.Foundation.Metadata;
using Windows.UI.Xaml;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;

[assembly: ExportRenderer(typeof(ListView), typeof(ConnectedAnimationSourceListViewRenderer))]

namespace UWP.Renderers
{
    /// <summary>
    /// Connected animation source list view renderer
    /// </summary>
    public class ConnectedAnimationSourceListViewRenderer : ListViewRenderer
    {
        /// <summary>
        /// Element property changed
        /// </summary>
        /// <param name="sender">the sender</param>
        /// <param name="e">the property chagned event arguments</param>
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == "PrepareConnectedAnimation")
            {
                var data = ConnectedAnimations.GetPrepareConnectedAnimation(Element);

                if (data != null && ApiInformation.IsMethodPresent("Windows.UI.Xaml.Controls.ListViewBase", "PrepareConnectedAnimation"))
                {
                    List.PrepareConnectedAnimation(data.Key, data.Item, data.ElementName);
                }
            }
        }
    }
}


text:
function count([input]) {
    let words = input.split(/[^A-Za-z\d_]/).filter(w => w!="");
    let wordsCount = {};
    for (let i = 0; i < words.length; i++) {
        let word = words[i];
        if(!wordsCount[word]){
            wordsCount[word] = 0;
        }
        wordsCount[word]++;
    }
    let jsonFormat = JSON.stringify(wordsCount);
    console.log(jsonFormat);
}

count(`Far too slow, you're far too slow.`);


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="es.shyri.longtaskservice" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name="es.shyri.longtaskservice.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="es.shyri.longtaskservice.LongTaskService"/>
    </application>

</manifest>


text:
namespace OrleansTemplate.Abstractions.Grains.HealthChecks;

using Orleans;

public interface ILocalHealthCheckGrain : IGrainWithGuidKey
{
    ValueTask CheckAsync();
}


text:
virtualenv --always-copy -p $(which python3.5) env
pip install flask
pip install youtube-dl


text:
layout:
permalink: /
title: Home
---
{% include layouts/header.html %}

  {% include layouts/navbar.html %}

Caption Text

Caption Text

JOIN NOW!

Latest News

        {% for post in site.posts limit:5 %}

            {{ post.date | date_to_string }} »
            {{ post.title }}

        {% endfor %}

  {% include layouts/footer.html %}


text:
'''
analyze_gsimg.py - analyze G Suite image processing workflow

Download image from Google Drive, archive to Google Cloud Storage, send
to Google Cloud Vision for processing, add results row to Google Sheet.
'''

from __future__ import print_function
import argparse
import webbrowser

from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
from google.cloud import storage, vision

k_ize = lambda b: '%6.2fK' % (b/1000.) # bytes to kBs
FILE = 'YOUR_IMG_ON_DRIVE'
BUCKET = 'YOUR_BUCKET_NAME'
PARENT = ''     # YOUR IMG FILE PREFIX
SHEET = 'YOUR_SHEET_ID'
TOP = 5       # TOP # of VISION LABELS TO SAVE
DEBUG = False

# process credentials for OAuth2 tokens
SCOPES = (
    'https://www.googleapis.com/auth/drive.readonly',
    'https://www.googleapis.com/auth/devstorage.full_control',
    'https://www.googleapis.com/auth/cloud-vision',
    'https://www.googleapis.com/auth/spreadsheets',
)
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)

# create API service endpoints
HTTP = creds.authorize(Http())
DRIVE  = discovery.build('drive',   'v3', http=HTTP)
GCS    = storage.Client()
VISION = vision.ImageAnnotatorClient()
SHEETS = discovery.build('sheets',  'v4', http=HTTP)

def drive_get_img(fname):
    'download file from Drive and return file info & binary if found'

    # search for file on Google Drive
    rsp = DRIVE.files().list(q="name='%s'" % fname,
            fields='files(id,name,mimeType,modifiedTime)'
    ).execute().get('files', [])

    # download binary & return file info if found, else return None
    if rsp:
        target = rsp[0]  # use first matching file
        fileId = target['id']
        fname = target['name']
        mtype = target['mimeType']
        binary = DRIVE.files().get_media(fileId=fileId).execute()
        return fname, mtype, target['modifiedTime'], binary

def gcs_blob_upload(fname, bucket, media, mimetype):
    'upload an object to a Google Cloud Storage bucket'

    # build blob metadata and upload via GCS API
    blob = GCS.bucket(bucket).blob(fname)
    blob.upload_from_string(media, mimetype)
    return {'bucket': bucket, 'name': fname}

def vision_label_img(img, top):
    'send image to Vision API for label annotation'

    # call Vision API to process
    image = vision.types.Image(content=img)
    labels = VISION.label_detection(image=image, max_results=top).label_annotations

    # return top labels for image as CSV for Sheet (row)
    return ', '.join('(%.2f%%) %s' % (
            label.score*100., label.description) for label in labels)

def sheet_append_row(sheet, row):
    'append row to a Google Sheet, return #cells added'

    # call Sheets API to write row to Sheet (via its ID)
    rsp = SHEETS.spreadsheets().values().append(
            spreadsheetId=sheet, range='Sheet1',
            valueInputOption='USER_ENTERED', body={'values': [row]}
    ).execute()
    if rsp:
        return rsp.get('updates').get('updatedCells')

def main(fname, bucket, sheet_id, folder, top, debug):
    '"main()" drives process from image download through report generation'

    # download img file & info from Drive
    rsp = drive_get_img(fname)
    if not rsp:
        return
    fname, mtype, ftime, data = rsp
    if debug:
        print('Downloaded %r (%s, %s, size: %d)' % (fname, mtype, ftime, len(data)))

    # upload file to GCS
    gcsname = '%s/%s'% (folder, fname)
    rsp = gcs_blob_upload(gcsname, bucket, data, mtype)
    if not rsp:
        return
    if debug:
        print('Uploaded %r to GCS bucket %r' % (rsp['name'], rsp['bucket']))

    # process w/Vision
    rsp = vision_label_img(data, top)
    if not rsp:
        return
    if debug:
        print('Top %d labels from Vision API: %s' % (top, rsp))

    # push results to Sheet, get cells-saved count
    fsize = k_ize(len(data))
    row = [folder,
            '=HYPERLINK("storage.cloud.google.com/%s/%s", "%s")' % (
            bucket, gcsname, fname), mtype, ftime, fsize, rsp
    ]
    rsp = sheet_append_row(sheet_id, row)
    if not rsp:
        return
    if debug:
        print('Added %d cells to Google Sheet' % rsp)
    return True

if __name__ == '__main__':
    # args: [-hv] [-i imgfile] [-b bucket] [-f folder] [-s Sheet ID] [-t top labels]
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--imgfile", action="store_true",
            default=FILE, help="image file filename")
    parser.add_argument("-b", "--bucket_id", action="store_true",
            default=BUCKET, help="Google Cloud Storage bucket name")
    parser.add_argument("-f", "--folder", action="store_true",
            default=PARENT, help="Google Cloud Storage image folder")
    parser.add_argument("-s", "--sheet_id", action="store_true",
            default=SHEET, help="Google Sheet Drive file ID (44-char str)")
    parser.add_argument("-t", "--viz_top", action="store_true",
            default=TOP, help="return top N (default %d) Vision API labels" % TOP)
    parser.add_argument("-v", "--verbose", action="store_true",
            default=DEBUG, help="verbose display output")
    args = parser.parse_args()

    print('Processing file %r... please wait' % args.imgfile)
    rsp = main(args.imgfile, args.bucket_id,
            args.sheet_id, args.folder, args.viz_top, args.verbose)
    if rsp:
        sheet_url = 'https://docs.google.com/spreadsheets/d/%s/edit' % args.sheet_id
        print('DONE: opening web browser to it, or see %s' % sheet_url)
        webbrowser.open(sheet_url, new=1, autoraise=True)
    else:
        print('ERROR: could not process %r' % args.imgfile)


text:
import {} from 'jest';
import * as supertest from "supertest";
const request = supertest("http://localhost:8000");

describe("GET /login", () => {
  it("should return 200 OK", (done) => {
    request.get("/login")
      .expect(200, done);
  });
});

describe("GET /signup", () => {
  it("should return 200 OK", (done) => {
    request.get("/signup")
      .expect(200, done);
  });
});


text:
"use strict";
var re = /abc/;
// RegExps are not concat-spreadable by default
assertEquals([re], [].concat(re));

// RegExps may be individually concat-spreadable
re[Symbol.isConcatSpreadable] = true;
re[0] = 1, re[1] = 2, re[2] = 3, re.length = 3;
assertEquals([1, 2, 3], [].concat(re));

// RegExps may be concat-spreadable
RegExp.prototype[Symbol.isConcatSpreadable] = true;
RegExp.prototype.length = 3;

assertEquals([void 0, void 0, void 0], [].concat(/abc/));
RegExp.prototype[0] = 1;
RegExp.prototype[1] = 2;
RegExp.prototype[2] = 3;
assertEquals([1,2,3], [].concat(/abc/));