text:
package org.kuali.rice.krad.service;

import org.junit.Test;
import org.kuali.rice.core.api.CoreApiServiceLocator;
import org.kuali.rice.krad.test.KRADTestCase;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static org.junit.Assert.*;

/**
 * DateTimeServiceTest tests {@link org.kuali.rice.core.api.datetime.DateTimeService}
 */
public class DateTimeServiceTest extends KRADTestCase {

    /**
     * tests that DateTimeService returns a correct current date
     *
     * @see org.kuali.rice.core.api.datetime.DateTimeService#getCurrentDate()
     */
    @Test public void testGetCurrentDate() {
        Date beforeServiceDate = new Date();
        Date serviceDate = CoreApiServiceLocator.getDateTimeService().getCurrentDate();
        Date afterServiceDate = new Date();

        assertTrue("beforeServiceDate not <= serviceDate", beforeServiceDate.before(serviceDate) || beforeServiceDate.equals(serviceDate));
        assertTrue("afterServiceDate not >= serviceDate", afterServiceDate.after(serviceDate) || afterServiceDate.equals(serviceDate));
    }

    /**
     * tests that DateTimeService returns a correct current SQL date
     *
     * @see org.kuali.rice.core.api.datetime.DateTimeService#getCurrentSqlDate()
     */
    @Test public void testGetCurrentSqlDate() {
        java.sql.Date serviceDate = CoreApiServiceLocator.getDateTimeService().getCurrentSqlDate();

        java.sql.Date beforeServiceDate = new java.sql.Date(serviceDate.getTime() - 100);
        java.sql.Date afterServiceDate = new java.sql.Date(serviceDate.getTime() + 100);

        assertTrue("beforeServiceDate not <= serviceDate", beforeServiceDate.before(serviceDate) || beforeServiceDate.equals(serviceDate));
        assertTrue("afterServiceDate not >= serviceDate", afterServiceDate.after(serviceDate) || afterServiceDate.equals(serviceDate));
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#getCurrentSqlDateMidnight()}
     * @throws InterruptedException
     */
    @SuppressWarnings("deprecation")
    @Test public void testGetCurrentSqlDateMidnight() throws InterruptedException {
        // this test is invalid within 1 second of midnight, so wait for it
        waitForMidnightIfWithinOneSecond();
        java.sql.Date before = CoreApiServiceLocator.getDateTimeService().getCurrentSqlDateMidnight();
        java.util.Date checkBefore = new java.util.Date();
        Thread.sleep(500); // makes sure the clock has time to tick
        java.util.Date checkAfter = new java.util.Date();
        java.sql.Date after = CoreApiServiceLocator.getDateTimeService().getCurrentSqlDateMidnight();
        assertTrue(checkBefore.before(checkAfter)); // make sure the clock did tick
        assertEquals(before.getTime(), after.getTime());
        java.util.Date afterUtil = new java.util.Date(after.getTime());
        // these methods in java.sql.Date are not just deprecated; they throw IllegalArgumentException.
        assertEquals(0, afterUtil.getHours());
        assertEquals(0, afterUtil.getMinutes());
        assertEquals(0, afterUtil.getSeconds());
    }

    /**
     * {@link #testGetCurrentSqlDateMidnight()} is invalid within 1 second of midnight, so wait for it
     *
     * @throws InterruptedException
     */
    @SuppressWarnings("deprecation")
    private static void waitForMidnightIfWithinOneSecond() throws InterruptedException {
        java.util.Date now = new java.util.Date();
        java.util.Date then = new java.util.Date(now.getTime() + 1000);
        if (now.getDay() != then.getDay()) {
            Thread.sleep(1000);
        }
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#getCurrentCalendar()}
     */
    @Test public void testGetCurrentCalendar() {
        Date beforeServiceDate = new Date();
        Calendar serviceCalendar = CoreApiServiceLocator.getDateTimeService().getCurrentCalendar();
        Date afterServiceDate = new Date();

        // extract the calendar's Date, for easier testing
        Date serviceDate = serviceCalendar.getTime();

        assertTrue("beforeServiceDate not <= serviceDate", beforeServiceDate.before(serviceDate) || beforeServiceDate.equals(serviceDate));
        assertTrue("afterServiceDate not >= serviceDate", afterServiceDate.after(serviceDate) || afterServiceDate.equals(serviceDate));
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlTimestamp(String)} with a null value
     *
     * @throws ParseException
     */
    @Test public void testConvertToSqlTimestamp_blankTimeString() throws ParseException {
        assertNull(CoreApiServiceLocator.getDateTimeService().convertToSqlTimestamp(null));
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlTimestamp(String)} with an invalid time value
     */
    @Test public void testConvertToSqlTimestamp_invalidTimeString() {
        boolean failedAsExpected = false;
        try {
            CoreApiServiceLocator.getDateTimeService().convertToSqlTimestamp("foo");
        }
        catch (ParseException e) {
            failedAsExpected = true;
        }
        assertTrue("invalid timeString failed to fail", failedAsExpected);
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlTimestamp(String)} with a valid time string
     *
     * @throws ParseException
     */
    @Test public void testConvertToSqlTimestamp_validTimeString() throws ParseException {
        java.sql.Timestamp serviceTimestamp = CoreApiServiceLocator.getDateTimeService().convertToSqlTimestamp("05/01/1966 02:41 PM");
        Calendar serviceCalendar = Calendar.getInstance();
        serviceCalendar.setTime(serviceTimestamp);
        assertEquals("unexpected year", 1966, serviceCalendar.get(Calendar.YEAR));
        assertEquals("unexpected month", 5, serviceCalendar.get(Calendar.MONTH) + 1);
        assertEquals("unexpected day", 1, serviceCalendar.get(Calendar.DAY_OF_MONTH));
        assertEquals("unexpected hours", 14, serviceCalendar.get(Calendar.HOUR_OF_DAY));
        assertEquals("unexpected minutes", 41, serviceCalendar.get(Calendar.MINUTE));
        assertEquals("unexpected seconds", 0, serviceCalendar.get(Calendar.SECOND));
        assertEquals("unexpected milliseconds", serviceTimestamp.getNanos(), 0);
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlDate(String)} with a blank value
     *
     * @throws ParseException
     */
    @Test public void testConvertToSqlDate_blankDateString() throws ParseException {
        boolean failedAsExpected = false;

        try {
            CoreApiServiceLocator.getDateTimeService().convertToSqlDate("");
        }
        catch (IllegalArgumentException e) {
            failedAsExpected = true;
        }

        assertTrue("blank dateString failed to fail", failedAsExpected);
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlDate(String)} with an invalid date string
     */
    @Test public void testConvertToSqlDate_invalidDateString() {
        boolean failedAsExpected = false;

        try {
            CoreApiServiceLocator.getDateTimeService().convertToSqlDate("foo");
        }
        catch (ParseException e) {
            failedAsExpected = true;
        }

        assertTrue("invalid dateString failed to fail", failedAsExpected);
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlDate(String)} with a valid date string
     */
    @Test public void testConvertToSqlDate_validDateString() throws ParseException {
        java.sql.Date serviceDate = CoreApiServiceLocator.getDateTimeService().convertToSqlDate("05/01/1966");

        Calendar serviceCalendar = Calendar.getInstance();
        serviceCalendar.setTime(serviceDate);

        assertEquals("unexpected year", 1966, serviceCalendar.get(Calendar.YEAR));
        assertEquals("unexpected month", 5, serviceCalendar.get(Calendar.MONTH) + 1);
        assertEquals("unexpected day", 1, serviceCalendar.get(Calendar.DAY_OF_MONTH));
        assertEquals("unexpected hours", 0, serviceCalendar.get(Calendar.HOUR_OF_DAY));
        assertEquals("unexpected minutes", 0, serviceCalendar.get(Calendar.MINUTE));
        assertEquals("unexpected seconds", 0, serviceCalendar.get(Calendar.SECOND));
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlTime(String)} with a blank value
     *
     * @throws ParseException
     */
    @Test public void testConvertToSqlTime_blankTimeString() throws ParseException {
        boolean failedAsExpected = false;

        try {
            CoreApiServiceLocator.getDateTimeService().convertToSqlTime("");
        }
        catch (IllegalArgumentException e) {
            failedAsExpected = true;
        }

        assertTrue("blank timeString failed to fail", failedAsExpected);
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlTime(String)} with an invalid time string
     */
    @Test public void testConvertToSqlTime_invalidTimeString() {
        boolean failedAsExpected = false;

        try {
            CoreApiServiceLocator.getDateTimeService().convertToSqlTime("foo");
        }
        catch (ParseException e) {
            failedAsExpected = true;
        }

        assertTrue("invalid timeString failed to fail", failedAsExpected);
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#convertToSqlTime(String)} with a valid date string
     */
    @Test public void testConvertToSqlTime_validTimeString() throws ParseException {
        java.sql.Time serviceTime = CoreApiServiceLocator.getDateTimeService().convertToSqlTime("10:28 am");

        Calendar serviceCalendar = Calendar.getInstance();
        serviceCalendar.setTime(serviceTime);

        assertEquals("unexpected hours", 10, serviceCalendar.get(Calendar.HOUR_OF_DAY));
        assertEquals("unexpected minutes", 28, serviceCalendar.get(Calendar.MINUTE));
        assertEquals("unexpected seconds", 0, serviceCalendar.get(Calendar.SECOND));
    }

    /**
     * tests {@link org.kuali.rice.core.api.datetime.DateTimeService#dateDiff(java.util.Date, java.util.Date, boolean)}
     *
     * @throws ParseException
     */
    @Test public void testDateDiff() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        // regular 1 year period
        Date date1 = sdf.parse("01/01/2006");
        Date date2 = sdf.parse("12/31/2006");

        assertEquals("365", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("364", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // one year period w/ leap year
        date1 = sdf.parse("01/01/2008");
        date2 = sdf.parse("12/31/2008");

        assertEquals("366", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("365", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        assertEquals("366", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("365", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // one year period w/ leap year, beginning in the middle of the year
        date1 = sdf.parse("07/01/2007");
        date2 = sdf.parse("06/30/2008");

        assertEquals("366", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("365", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // one year period, start and end in middle of the year
        date1 = sdf.parse("07/01/2006");
        date2 = sdf.parse("06/30/2007");

        assertEquals("365", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("364", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // one month period
        date1 = sdf.parse("01/01/2006");
        date2 = sdf.parse("01/31/2006");

        assertEquals("31", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("30", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // another one month period
        date1 = sdf.parse("04/14/2006");
        date2 = sdf.parse("05/13/2006");

        assertEquals("30", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("29", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // one day period
        date1 = sdf.parse("01/01/2006");
        date2 = sdf.parse("01/02/2006");

        assertEquals("2", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));
        assertEquals("1", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // arbitrary dates
        date1 = sdf.parse("01/01/2006");
        date2 = sdf.parse("06/30/2006");

        assertEquals("181", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));

        date1 = sdf.parse("07/01/2006");
        date2 = sdf.parse("12/31/2006");

        assertEquals("184", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, true)));

        // within same month
        date1 = sdf.parse("07/01/2006");
        date2 = sdf.parse("07/20/2006");

        assertEquals("19", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // same day
        date1 = sdf.parse("07/20/2006");
        date2 = sdf.parse("07/20/2006");

        assertEquals("0", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));

        // end date is prior to start date
        date1 = sdf.parse("07/25/2006");
        date2 = sdf.parse("07/20/2006");

        assertEquals("-5", Integer.toString(CoreApiServiceLocator.getDateTimeService().dateDiff(date1, date2, false)));
    }
}


text:
package com.evolveum.midpoint.util.logging;

import org.slf4j.MDC;
import org.slf4j.Marker;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;

/**
 * This class allow output for given MDC value and given level
 * implments logback turbofilter feature
 *

 * If given value of MDC is found and also level of message reach given level
 * then onMatch action is done
 * else onMissmatch actionis done
 *
 *

 * Action values:
 * ACCEPT - bypass basic selection rule and follow processing
 * NEUTRAL - follow processing
 * DENY - stop processing
 *

 * Level values:OFF,ERROR,WARN,INFO,DEBUG,TRACE
 *
 * @author mamut
 *
 */
public class MDCLevelTurboFilter extends TurboFilter {

	private FilterReply onMatch = FilterReply.ACCEPT;
	private FilterReply onMismatch = FilterReply.NEUTRAL;
	private String mdcKey;
	private String mdcValue;
	private Level level = Level.OFF;

	@Override
	public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {

		if (null == mdcKey || null == mdcValue) {
			return FilterReply.NEUTRAL;
		}
		//First compare levels
		if (level.isGreaterOrEqual(borderLevel())) {
			//Second test MDCvalue match current MDC->key => value
			if (mdcValue.equals(MDC.get(mdcKey))) {
				//if midpoint clas then process
				if (logger.getName().contains("com.evolveum.midpoint")) {
					return onMatch;
				// if PROFILING then skip
				} else if ("PROFILING".equals(logger.getName())) {
					return FilterReply.NEUTRAL;
				// if external class then move to TRACE
				} else {
					if (level.isGreaterOrEqual(Level.DEBUG)) {
						level = Level.TRACE;
					}
				}

			} else {
				return onMismatch;
			}
		}
		return FilterReply.NEUTRAL;
	}

	/**
	 * @param onMatch action to set on success
	 */
	public void setOnMatch(String action) {
		if ("NEUTRAL".equals(action)) {
			this.onMatch = FilterReply.NEUTRAL;
		} else if ("ACCEPT".equals(action)) {
			this.onMatch = FilterReply.ACCEPT;
		} else {
			this.onMatch = FilterReply.DENY;
		}
	}

	/**
	 * @param onMismatch the onMismatch to set on failure
	 */
	public void setOnMismatch(String action) {
		if ("NEUTRAL".equals(action)) {
			this.onMismatch = FilterReply.NEUTRAL;
		} else if ("ACCEPT".equals(action)) {
			this.onMismatch = FilterReply.ACCEPT;
		} else {
			this.onMismatch = FilterReply.DENY;
		}
	}

	/**
	 * @param mdcKey the mdcKey to watch
	 */
	public void setMDCKey(String mdcKey) {
		System.out.println("MDCkey = " + mdcKey);
		this.mdcKey = mdcKey;
	}

	/**
	 * @param mdcValue the mdcValue to match with MDCkey
	 */
	public void setMDCValue(String mdcValue) {
		System.out.println("MDCvalue = " + mdcValue);
		this.mdcValue = mdcValue;
	}

	/**
	 * @param level the level to breach
	 */
	public void setLevel(String loggingLevel) {
		String level = loggingLevel.toUpperCase();
		if ("OFF".equals(level)) {
			this.level = Level.OFF;
		} else if ("ERROR".equals(level)) {
			this.level = Level.ERROR;
		} else if ("WARN".equals(level)) {
			this.level = Level.WARN;
		} else if ("INFO".equals(level)) {
			this.level = Level.INFO;
		} else if ("DEBUG".equals(level)) {
			this.level = Level.DEBUG;
		} else if ("TRACE".equals(level)) {
			this.level = Level.TRACE;
		} else {
			this.level = Level.ALL;
		}
	}

	/**
	 * @return the level
	 */
	private Level borderLevel() {
		return level;
	}

	@Override
	public void start() {
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @xmlNamespace http://schema.intuit.com/finance/v3
 * @xmlType string
 * @xmlName IPPTaxTypeApplicablityEnum
 * @var IPPTaxTypeApplicablityEnum
 * @xmlDefinition
				Product: ALL
				Description: TaxTypeApplicability enumeration

 */
class IPPTaxTypeApplicablityEnum
	{

		/**
		* Initializes this object, optionally with pre-defined property values
		*
		* Initializes this object and it's property members, using the dictionary
		* of key/value pairs passed as an optional argument.
		*
		* @param dictionary $keyValInitializers key/value pairs to be populated into object's properties
		* @param boolean $verbose specifies whether object should echo warnings
		*/
		public function __construct($keyValInitializers=array(), $verbose=FALSE)
		{
			foreach($keyValInitializers as $initPropName => $initPropVal)
			{
				if (property_exists('IPPTaxTypeApplicablityEnum',$initPropName))
				{
					$this->{$initPropName} = $initPropVal;
				}
				else
				{
					if ($verbose)
						echo "Property does not exist ($initPropName) in class (".get_class($this).")";
				}
			}
		}

		/**
		 * @xmlType value
		 * @var string
		 */
		public $value;

} // end class IPPTaxTypeApplicablityEnum


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/kafka.iml" filepath="$PROJECT_DIR$/.idea/modules/kafka.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/kafka-build.iml" filepath="$PROJECT_DIR$/.idea/modules/kafka-build.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/root.iml" filepath="$PROJECT_DIR$/.idea/modules/root.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/root-build.iml" filepath="$PROJECT_DIR$/.idea/modules/root-build.iml" />
    </modules>
  </component>
</project>


text:
package alluxio.cli.fs;

import alluxio.AlluxioURI;
import alluxio.client.file.FileSystemContext;
import alluxio.conf.AlluxioConfiguration;
import alluxio.Constants;
import alluxio.conf.PropertyKey;
import alluxio.cli.Command;
import alluxio.cli.CommandUtils;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.exception.AlluxioException;
import alluxio.exception.ExceptionMessage;
import alluxio.util.FormatUtils;
import alluxio.util.io.PathUtils;
import alluxio.util.network.NetworkAddressUtils;
import alluxio.util.network.NetworkAddressUtils.ServiceType;

import com.google.common.collect.Lists;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Class for convenience methods used by {@link FileSystemShell}.
 */
@ThreadSafe
public final class FileSystemShellUtils {

  private FileSystemShellUtils() {} // prevent instantiation

  /**
   * Removes {@link Constants#HEADER} / {@link Constants#HEADER_FT} and hostname:port information
   * from a path, leaving only the local file path.
   *
   * @param path the path to obtain the local path from
   * @param alluxioConf Alluxio configuration
   * @return the local path in string format
   */
  public static String getFilePath(String path, AlluxioConfiguration alluxioConf)
      throws IOException {
    path = validatePath(path, alluxioConf);
    if (path.startsWith(Constants.HEADER)) {
      path = path.substring(Constants.HEADER.length());
    } else if (path.startsWith(Constants.HEADER_FT)) {
      path = path.substring(Constants.HEADER_FT.length());
    }
    return path.substring(path.indexOf(AlluxioURI.SEPARATOR));
  }

  /**
   * Validates the path, verifying that it contains the {@link Constants#HEADER} or
   * {@link Constants#HEADER_FT} and a hostname:port specified.
   *
   * @param path the path to be verified
   * @param alluxioConf Alluxio configuration
   * @return the verified path in a form like alluxio://host:port/dir. If only the "/dir" or "dir"
   *         part is provided, the host and port are retrieved from property,
   *         alluxio.master.hostname and alluxio.master.rpc.port, respectively.
   */
  public static String validatePath(String path, AlluxioConfiguration alluxioConf)
      throws IOException {
    if (path.startsWith(Constants.HEADER) || path.startsWith(Constants.HEADER_FT)) {
      if (!path.contains(":")) {
        throw new IOException("Invalid Path: " + path + ". Use " + Constants.HEADER
            + "host:port/ ," + Constants.HEADER_FT + "host:port/" + " , or /file");
      } else {
        return path;
      }
    } else {
      String hostname = NetworkAddressUtils.getConnectHost(ServiceType.MASTER_RPC, alluxioConf);
      int port =  alluxioConf.getInt(PropertyKey.MASTER_RPC_PORT);
      if (alluxioConf.getBoolean(PropertyKey.ZOOKEEPER_ENABLED)) {
        return PathUtils.concatPath(Constants.HEADER_FT + hostname + ":" + port, path);
      }
      return PathUtils.concatPath(Constants.HEADER + hostname + ":" + port, path);
    }
  }

  /**
   * Gets all the {@link AlluxioURI}s that match inputURI. If the path is a regular path, the
   * returned list only contains the corresponding URI; Else if the path contains wildcards, the
   * returned list contains all the matched URIs It supports any number of wildcards in inputURI
   *
   * @param alluxioClient the client used to fetch information of Alluxio files
   * @param inputURI the input URI (could contain wildcards)
   * @return a list of {@link AlluxioURI}s that matches the inputURI
   */
  public static List<AlluxioURI> getAlluxioURIs(FileSystem alluxioClient, AlluxioURI inputURI)
      throws IOException {
    if (!inputURI.getPath().contains(AlluxioURI.WILDCARD)) {
      return Lists.newArrayList(inputURI);
    } else {
      String inputPath = inputURI.getPath();
      AlluxioURI parentURI = new AlluxioURI(inputURI.getScheme(), inputURI.getAuthority(),
          inputPath.substring(0, inputPath.indexOf(AlluxioURI.WILDCARD) + 1),
          inputURI.getQueryMap()).getParent();
      return getAlluxioURIs(alluxioClient, inputURI, parentURI);
    }
  }

  /**
   * The utility function used to implement getAlluxioURIs.
   *
   * Basically, it recursively iterates through the directory from the parent directory of inputURI
   * (e.g., for input "/a/b/*", it will start from "/a/b") until it finds all the matches;
   * It does not go into a directory if the prefix mismatches
   * (e.g., for input "/a/b/*", it won't go inside directory "/a/c")
   *
   * @param alluxioClient the client used to fetch metadata of Alluxio files
   * @param inputURI the input URI (could contain wildcards)
   * @param parentDir the {@link AlluxioURI} of the directory in which we are searching matched
   *                  files
   * @return a list of {@link AlluxioURI}s of the files that match the inputURI in parentDir
   */
  private static List<AlluxioURI> getAlluxioURIs(FileSystem alluxioClient, AlluxioURI inputURI,
      AlluxioURI parentDir) throws IOException {
    List<AlluxioURI> res = new ArrayList<>();
    List<URIStatus> statuses;
    try {
      statuses = alluxioClient.listStatus(parentDir);
    } catch (AlluxioException e) {
      throw new IOException(e);
    }
    for (URIStatus status : statuses) {
      AlluxioURI fileURI =
          new AlluxioURI(inputURI.getScheme(), inputURI.getAuthority(), status.getPath());
      if (match(fileURI, inputURI)) { // if it matches
        res.add(fileURI);
      } else {
        if (status.isFolder()) { // if it is a folder, we do it recursively
          AlluxioURI dirURI =
              new AlluxioURI(inputURI.getScheme(), inputURI.getAuthority(), status.getPath());
          String prefix = inputURI.getLeadingPath(dirURI.getDepth());
          if (prefix != null && match(dirURI, new AlluxioURI(prefix))) {
            res.addAll(getAlluxioURIs(alluxioClient, inputURI, dirURI));
          }
        }
      }
    }
    return res;
  }

  /**
   * Gets the files (on the local filesystem) that match the given input path.
   * If the path is a regular path, the returned list only contains the corresponding file;
   * Else if the path contains wildcards, the returned list contains all the matched Files.
   *
   * @param inputPath The input file path (could contain wildcards)
   * @return a list of files that matches inputPath
   */
  public static List<File> getFiles(String inputPath) {
    File file = new File(inputPath);
    if (!inputPath.contains("*")) {
      List<File> res = new ArrayList<>();
      if (file.exists()) {
        res.add(file);
      }
      return res;
    } else {
      String prefix = inputPath.substring(0, inputPath.indexOf(AlluxioURI.WILDCARD) + 1);
      String parent = new File(prefix).getParent();
      return getFiles(inputPath, parent);
    }
  }

  /**
   * The utility function used to implement getFiles.
   *
   * It follows the same algorithm as {@link #getAlluxioURIs}.
   *
   * @param inputPath the input file path (could contain wildcards)
   * @param parent the directory in which we are searching matched files
   * @return a list of files that matches the input path in the parent directory
   */
  private static List<File> getFiles(String inputPath, String parent) {
    List<File> res = new ArrayList<>();
    File pFile = new File(parent);
    if (!pFile.exists() || !pFile.isDirectory()) {
      return res;
    }
    if (pFile.isDirectory() && pFile.canRead()) {
      File[] fileList = pFile.listFiles();
      if (fileList == null) {
        return res;
      }
      for (File file : fileList) {
        if (match(file.getPath(), inputPath)) { // if it matches
          res.add(file);
        } else {
          if (file.isDirectory()) { // if it is a folder, we do it recursively
            AlluxioURI dirURI = new AlluxioURI(file.getPath());
            String prefix = new AlluxioURI(inputPath).getLeadingPath(dirURI.getDepth());
            if (prefix != null && match(dirURI, new AlluxioURI(prefix))) {
              res.addAll(getFiles(inputPath, dirURI.getPath()));
            }
          }
        }
      }
    }
    return res;
  }

  /**
   * Gets the value of an option from the command line.
   *
   * @param cl command line object
   * @param option the option to check for in the command line
   * @param defaultValue default value for the option
   * @return argument from command line or default if not present
   */
  public static int getIntArg(CommandLine cl, Option option, int defaultValue) {
    int arg = defaultValue;
    if (cl.hasOption(option.getLongOpt())) {
      String argOption = cl.getOptionValue(option.getLongOpt());
      arg = Integer.parseInt(argOption);
    }
    return arg;
  }

  /**
   * Gets the value of an option from the command line.
   *
   * @param cl command line object
   * @param option the option to check for in the command line
   * @param defaultValue default value for the option
   * @return argument from command line or default if not present
   */
  public static long getMsArg(CommandLine cl, Option option, long defaultValue) {
    long arg = defaultValue;
    if (cl.hasOption(option.getLongOpt())) {
      String argOption = cl.getOptionValue(option.getLongOpt());
      arg = FormatUtils.parseTimeSize(argOption);
    }
    return arg;
  }

  /**
   * Gets all {@link Command} instances in the same package as {@link FileSystemShell} and load them
   * into a map. Provides a way to gain these commands information by their CommandName.
   *
   * @param fsContext the {@link FileSystemContext} instance to construct the command
   * @return a mapping from command name to command instance
   */
  public static Map<String, Command> loadCommands(FileSystemContext fsContext) {
    return CommandUtils.loadCommands(FileSystemShell.class.getPackage().getName(),
        new Class[] {FileSystemContext.class}, new Object[] {fsContext});
  }

  /**
   * Converts the input time into millisecond unit.
   *
   * @param time the time to be converted into milliseconds
   * @return the time in millisecond unit
   */
  public static long getMs(String time) {
    try {
      return FormatUtils.parseTimeSize(time);
    } catch (Exception e) {
      throw new RuntimeException(ExceptionMessage.INVALID_TIME.getMessage(time));
    }
  }

  /**
   * The characters that have special regex semantics.
   */
  private static final Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

  /**
   * Escapes the special characters in a given string.
   *
   * @param str input string
   * @return the string with special characters escaped
   */
  private static String escape(String str) {
    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
  }

  /**
   * Replaces the wildcards with Java's regex semantics.
   */
  private static String replaceWildcards(String text) {
    return escape(text).replace("\\*", ".*");
  }

  /**
   * Returns whether or not fileURI matches the patternURI.
   *
   * @param fileURI the {@link AlluxioURI} of a particular file
   * @param patternURI the URI that can contain wildcards
   * @return true if matches; false if not
   */
  private static boolean match(AlluxioURI fileURI, AlluxioURI patternURI) {
    return escape(fileURI.getPath()).matches(replaceWildcards(patternURI.getPath()));
  }

  /**
   * Returns whether or not filePath matches patternPath.
   *
   * @param filePath path of a given file
   * @param patternPath path that can contain wildcards
   * @return true if matches; false if not
   */
  public static boolean match(String filePath, String patternPath) {
    return match(new AlluxioURI(filePath), new AlluxioURI(patternPath));
  }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class ReturPenjualanRetail extends MX_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->acl->auth('retail');
        $this->load->model('ModReturPenjualanRetail');
        $this->load->model('retail_return/ModelRetailReturn');
        $this->id_store = $this->config->item('id_store');
    }
    public function index()
    {
        if ($this->input->post('date_from') && $this->input->post('date_to')) {
            $data['from'] = $this->input->post('date_from');
            $data['to'] = $this->input->post('date_to');
        } else {
            $data['from'] =  date('Y-m-01');
            $data['to'] = date('Y-m-t');
        }
        $return = $this->ModReturPenjualanRetail->getReturPenjualan($data['from'], $data['to']);
        $items = array();
        if($return){
            foreach ($return as $key) {
                $items[] = [
                    'id_retail_return' =>$key->id_retail_return,
                    'id_retail' =>$key->id_retail,
                    'date' =>$key->date,
                    'name' =>$key->name,
                    'value' =>$this->ModelRetailReturn->getReturnReplacedDetailItem($key->id_retail_return)
                ];
            }
        }
        $data['product_storage'] = $this->storageProduct();
        $data['items'] = $items;
        $this->parser->parse('return/retail.tpl', $data);
    }

    // public function index()
    // {
    //     if ($this->input->post('date_from') && $this->input->post('date_to')) {
    //         $data['retur_penjualan'] = $this->ModReturPenjualanRetail->getReturPenjualan($this->input->post('date_from'), $this->input->post('date_to'));
    //         $data['from'] = $this->input->post('date_from');
    //         $data['to'] = $this->input->post('date_to');
    //     } else {
    //         $data['retur_penjualan'] = $this->ModReturPenjualanRetail->getReturPenjualan();
    //     }

    //     $data['total_retur_penjualan'] = $this->ModReturPenjualanRetail->getTotalReturPenjualan();

    //     $this->parser->parse('retur-penjualan-retail.tpl', $data);
    // }

    // public function detail($id_retail_return = null)
    // {
    //     if (empty($id_retail_return) || !$this->ModReturPenjualanRetail->checkReturRetail($id_retail_return)) {
    //         redirect('report/retur-penjualan-retail', 'refresh');
    //     }

    //     $this->load->model('retail_return/ModelRetailReturn');
    //     $data['items'] = $this->ModelRetailReturn->getReturnReplacedDetailItem($id_retail_return);

    //     $data['id_retail_return'] = $id_retail_return;
    //     $data['product_storage'] = $this->storageProduct();
    //     $this->parser->parse('detail-retur-penjualan-retail.tpl', $data);
    // }

    private function storageProduct(){
        $return = array();
        $product = $this->ModelRetailReturn->getProductStore($this->id_store);
        foreach ($product as $row) {
            $return[$row['id_product_store']] = $row;
        }
        return $return;
    }
}


text:
"""
Copyright (c) 2016 Keith Sterling

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

import logging
from programy.config.base import BaseConfigurationData

class BrainFileConfiguration(object):

    def __init__(self, file=None, files=None, extension=".aiml", directories=False, errors=None, duplicates=None):
        self._file = None
        self._files = None
        self._extension = None
        self._directories = None
        self._errors = None
        self._duplicates = None

        if file is not None:
            self._file = file
        else:
            self._files = files
            self._extension = extension
            self._directories = directories

        self._errors = errors
        self._duplicates = duplicates

    @property
    def file(self):
        return self._file

    def is_single_file(self):
        return bool(self._file is not None)

    @property
    def files(self):
        return self._files

    @property
    def extension(self):
        return self._extension

    @property
    def directories(self):
        return self._directories

    @property
    def errors(self):
        return self._errors

    @property
    def duplicates(self):
        return self._duplicates

class BrainServiceConfiguration(object):

    def __init__(self, name, data=None):
        self._name = name.upper()
        self._params = {}
        if data is not None:
            for key in data.keys():
                self._params[key.upper()] = data[key]

    @property
    def name(self):
        return self._name

    @property
    def path(self):
        return self._params['PATH']

    def parameters(self):
        return self._params.keys()

    def set_parameter(self, key, value):
        self._params[key.upper()] = value

    def parameter(self, name):
        if name in self._params:
            return self._params[name]
        else:
            return None

class BrainConfiguration(BaseConfigurationData):

    DEFAULT_SUPRESS_WARNINGS    = False
    DEFAULT_ALLOW_SYSTEM_AIML   = True
    DEFAULT_ALLOW_LEARN_AIML    = True
    DEFAULT_ALLOW_LEARNF_AIML   = True

    def __init__(self):
        self._supress_warnings  = BrainConfiguration.DEFAULT_SUPRESS_WARNINGS
        self._allow_system_aiml = BrainConfiguration.DEFAULT_ALLOW_SYSTEM_AIML
        self._allow_learn_aiml  = BrainConfiguration.DEFAULT_ALLOW_LEARN_AIML
        self._allow_learnf_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML
        self._dump_to_file      = None
        self._aiml_files        = None
        self._set_files         = None
        self._map_files         = None
        self._denormal          = None
        self._normal            = None
        self._gender            = None
        self._person            = None
        self._person2           = None
        self._predicates        = None
        self._pronouns          = None
        self._properties        = None
        self._triples           = None
        self._preprocessors     = None
        self._postprocessors    = None
        self._services = []
        BaseConfigurationData.__init__(self, "brain")

    def _get_brain_file_configuration(self, config_file, section, bot_root):
        errors = config_file.get_option(section, "errors", missing_value=None)
        duplicates = config_file.get_option(section, "duplicates", missing_value=None)

        files = config_file.get_option(section, "files")
        if files is not None:
            files = self.sub_bot_root(files, bot_root)
            extension = config_file.get_option(section, "extension")
            directories = config_file.get_option(section, "directories")
            return BrainFileConfiguration(files=files, extension=extension, directories=directories, errors=errors, duplicates=duplicates)
        else:
            file = config_file.get_option(section, "file")
            file = self.sub_bot_root(file, bot_root)
            return BrainFileConfiguration(file=file, errors=errors, duplicates=duplicates)

    def load_config_section(self, config_file, bot_root):

        brain = config_file.get_section(self.section_name)
        if brain is not None:
            self._supress_warnings = config_file.get_option(brain, "supress_warnings", BrainConfiguration.DEFAULT_SUPRESS_WARNINGS)
            self._allow_system_aiml = config_file.get_option(brain, "allow_system_aiml", BrainConfiguration.DEFAULT_ALLOW_SYSTEM_AIML)
            self._allow_learn_aiml = config_file.get_option(brain, "allow_learn_aiml", BrainConfiguration.DEFAULT_ALLOW_LEARN_AIML)
            self._allow_learnf_aiml = config_file.get_option(brain, "allow_learnf_aiml", BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML)
            self._allow_learnf_aiml = config_file.get_option(brain, "allow_learnf_aiml", BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML)
            self._dump_to_file = config_file.get_option(brain, "dump_to_file", missing_value=None)

            files = config_file.get_section("files", brain)
            if files is not None:
                aiml = config_file.get_section("aiml", files)
                self._aiml_files = self._get_brain_file_configuration(config_file, aiml, bot_root)

                sets = config_file.get_section("sets", files)
                self._set_files = self._get_brain_file_configuration(config_file, sets, bot_root)

                maps = config_file.get_section("maps", files)
                self._map_files = self._get_brain_file_configuration(config_file, maps, bot_root)

                self._denormal = self._get_file_option(config_file, "denormal", files, bot_root)
                self._normal = self._get_file_option(config_file, "normal", files, bot_root)
                self._gender = self._get_file_option(config_file, "gender", files, bot_root)
                self._person = self._get_file_option(config_file, "person", files, bot_root)
                self._person2 = self._get_file_option(config_file, "person2", files, bot_root)
                self._predicates = self._get_file_option(config_file, "predicates", files, bot_root)
                self._pronouns = self._get_file_option(config_file, "pronouns", files, bot_root)
                self._properties = self._get_file_option(config_file, "properties", files, bot_root)
                self._triples = self._get_file_option(config_file, "triples", files, bot_root)
                self._preprocessors = self._get_file_option(config_file, "preprocessors", files, bot_root)
                self._postprocessors = self._get_file_option(config_file, "postprocessors", files, bot_root)
            else:
                logging.warning("Config section [files] missing from Brain, default values not appropriate")
                raise Exception ("Config section [files] missing from Brain")

            services = config_file.get_section("services", brain)
            if services is not None:
                service_keys = config_file.get_child_section_keys("services", brain)

                for name in service_keys:
                    service_data = config_file.get_section_data(name, services)
                    self._services.append(BrainServiceConfiguration(name, service_data))

            else:
                logging.warning("Config section [services] missing from Brain, no services loaded")
        else:
            logging.warning("Config section [%s] missing, using default values", self.section_name)
            self._supress_warnings  = BrainConfiguration.DEFAULT_SUPRESS_WARNINGS
            self._allow_system_aiml = BrainConfiguration.DEFAULT_ALLOW_SYSTEM_AIML
            self._allow_learn_aiml  = BrainConfiguration.DEFAULT_ALLOW_LEARN_AIML
            self._allow_learnf_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML
            self._allow_learnf_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML
            self._dump_to_file      = None

    @property
    def supress_warnings(self):
        return self._supress_warnings

    @property
    def allow_system_aiml(self):
        return self._allow_system_aiml

    @property
    def allow_learn_aiml(self):
        return self._allow_learn_aiml

    @property
    def allow_learnf_aiml(self):
        return self._allow_learnf_aiml

    @property
    def dump_to_file(self):
        return self._dump_to_file

    @property
    def aiml_files(self):
        return self._aiml_files

    @property
    def set_files(self):
        return self._set_files

    @property
    def map_files(self):
        return self._map_files

    @property
    def denormal(self):
        return self._denormal

    @property
    def normal(self):
        return self._normal

    @property
    def gender(self):
        return self._gender

    @property
    def person(self):
        return self._person

    @property
    def person2(self):
        return self._person2

    @property
    def predicates(self):
        return self._predicates

    @property
    def pronouns(self):
        return self._pronouns

    @property
    def properties(self):
        return self._properties

    @property
    def triples(self):
        return self._triples

    @property
    def preprocessors(self):
        return self._preprocessors

    @property
    def postprocessors(self):
        return self._postprocessors

    @property
    def services(self):
        return self._services


text:
import urllib.request
import os.path
import codecs
import difflib
from escape_sequence import *

class WebPage:
    def __init__(self,name,url):
        self.name = name
        self.url  = url

    def get_html(self):
        try:
            response = urllib.request.urlopen(self.url)
        except:
            return None
        charset = 'utf-8'   #TODO : detection
        byte_html = response.read()
        try:
            #codecs.lookup(charset)
            html = byte_html.decode(charset,'replace')
        except:
            print(em('Failed to Detect Encoding at ') + self.url)
            html = None
        return html

    def parse(self,html):
        raise NotImplementedError

    def beautify(self,parsed):
        raise NotImplementedError

class Logger:
    def __init__(self,name,log_dir = './log'):
        self.name = name
        self.log_dir = log_dir

    def __load_log(self):
        path = self.log_dir + '/' + self.name
        return  open(path,'r').read() if os.path.exists(path) else ""

    def write_log(self,new_data):
        if not os.path.exists(self.log_dir):
            os.mkdir(self.log_dir)
            print(em('Log Directory : '+ self.log_dir +' not found.Created directory.'))
        path = self.log_dir + '/' + self.name
        open(path,'w').write(new_data)

    def get_updated(self,new_data):
        old_data = self.__load_log()
        ret =''
        if old_data != new_data :
            d = difflib.Differ()
            diff = list(d.compare(old_data.splitlines(),new_data.splitlines()))
            new_diff = []
            for line in diff:
                if line.startswith('+ '):
                    new_diff.append(line[2:])
            ret =  '\n'.join(new_diff)
            if ret == None:
                ret = ''

        is_updated = True if len(ret)>0 else False
        return is_updated , ret

class UpdateChecker(WebPage,Logger):
    def __init__(self,name,url):
        WebPage.__init__(self,name,url)
        Logger.__init__(self,name)
        self.name = name
        self.url = url

    def check_update(self,save_log = True):
        html = self.get_html()
        if html == None:
            print(em("Failed to get html")+" at "+self.url)
            return False , ''

        parsed = self.parse(html)
        is_updated,updates = self.get_updated(parsed)
        ret =''
        if is_updated :
            if save_log: self.write_log(parsed)
            ret  = 'サイト:\r\n %s \r\n' % self.name
            ret += 'URL   :\r\n %s \r\n' % self.url
            ret += '更新情報  :\r\n'
            ret += self.beautify(updates)

        return is_updated , ret


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Indian Phytopath. 54(3): 355 (2001)

#### Original name
Cercospora tephrosiicola Narayan, Kharwar & R.K. Singh

### Remarks
null


text:
Ext.define('Ext.rtl.chart.Legend', {
    override: 'Ext.chart.Legend',

    init: function() {
        var me = this;

        me.callParent(arguments);
        me.position = me.chart.invertPosition(me.position);
        me.rtl = me.chart.getHierarchyState().rtl;
    },

    updateItemDimensions: function() {
        var me = this,
            result = me.callParent(),
            padding = me.padding,
            spacing = me.itemSpacing,
            items = me.items,
            len = items.length,
            mfloor = Math.floor,
            width = result.totalWidth,
            usedWidth = 0,
            i, item, itemWidth;

        if (me.rtl && !me.isVertical) {
            for (i = 0; i < len; ++i) {
                item = items[i];

                // Set the item's position relative to the legend box
                itemWidth = mfloor(item.getBBox().width + spacing);
                item.x = -usedWidth + padding;
                usedWidth += itemWidth;
            }
        }
        return result;
    }
})


text:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import DocumentMeta from 'react-document-meta';

const meta = {
  title: 'Rook Starter'
};

const mapStateToProps = (state) => ({
  loading: state.apiRequest.get('loading'),
  loadError: state.apiRequest.get('loadError')
});

class App extends Component {
  static propTypes = {
    children: PropTypes.object,
    loading: PropTypes.bool,
    loadError: PropTypes.object
  };

  render() {
    require('./App.pcss');

    return (

        <DocumentMeta {...meta} />

          Loading: {`${this.props.loading}`}

          Load Error: {`${this.props.loadError}`}

        { this.props.children }

    );
  }
}

export default connect(mapStateToProps)(App);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SpaceTraffic.Engine
{
    public interface IRunnableScript
    {
        object Run(IGameServer gameServer, params object[] args);
    }
}


text:
var args = arguments[0] || {};
var moment = require('alloy/moment');

function changeTF(e) {
	value = e.source.text;
	if (e.value == e.source.text) {
		this.value = "";
	}
}

function validatedTF(e) {
	if (e.value.length == 0) {
		this.value = value;
	}
}

function cancel() {
	args.win.remove($.nuevoRecordatorio);
}

function agregar() {
	if ($.nombre.value == "Nombre recordatorio") {
		alert("Es necesario introducir un nombre");
	} else if ($.fecha.text == "Fecha") {
		alert("Es necesario introduir una fecha");
	} else {
		var recordatoriosCollection = Alloy.Collections.recordatorios;

		var creado = moment().format();
		var dataSave = {
			nombre : $.nombre.value,
			fecha : $.fecha.text
		};
		Ti.API.info("data:" + JSON.stringify(dataSave));
		var model = Alloy.createModel('recordatorios', dataSave);
		recordatoriosCollection.add(model);
		model.save();
		//args.setData();
		Alloy.Globals.setDataRecord();
		args.win.remove($.nuevoRecordatorio);
	}
}

function showDate() {
	var top = Titanium.UI.createAnimation({
		top : -250,
		//visible : true,
		duration : 700
	});
	var top2 = Titanium.UI.createAnimation({
		bottom : 0,
		//visible : true,
		duration : 700
	});
	$.agregarView.animate(top);
	$.pickerView.animate(top2);
}

// $.picker.minDate = moment("1990-01-01");
// $.picker.maxDate = moment("2050-11-31");
// $.picker.value = moment();

function aceptarP() {
	var bottom = Titanium.UI.createAnimation({
		bottom : -280,
		//visible : true,
		duration : 700
	});
	var top2 = Titanium.UI.createAnimation({
		top : Alloy.Globals.windowHeight / 4,
		//visible : true,
		duration : 700
	});
	$.fecha.text = moment($.picker.value).format("DD-MM-YY");
	Ti.API.info($.picker.value);
	$.agregarView.animate(top2);
	$.pickerView.animate(bottom);
}

function cancelP() {
	var bottom = Titanium.UI.createAnimation({
		bottom : -280,
		//visible : true,
		duration : 700
	});
	var top2 = Titanium.UI.createAnimation({
		top : Alloy.Globals.windowHeight / 4,
		//visible : true,
		duration : 700
	});

	Ti.API.info(Alloy.Globals.windowHeight / 4);
	$.agregarView.animate(top2);
	$.pickerView.animate(bottom);
}

// var view = Ti.UI.createView({
// width : Ti.UI.FILL,
// backgroundColor : 'transparent',
// bottom : 0,
// zIndex : 3,
// visible : false
// });
// var viewOpacty = Ti.UI.createView({
// width : Ti.UI.FILL,
// backgroundColor : 'black',
// opacity : 0.8
// });
// var pickerDate = Ti.UI.createPicker({
// top : 15,
// type : Ti.UI.PICKER_TYPE_DATE,
// minDate : new Date(1990, 01, 01),
// maxDate : new Date(2050, 11, 31),
// value : new Date(),
// });
// var btn = Ti.UI.createButton({
// width : Ti.UI.FILL,
// title : 'Aceptar',
// width : '50%',
// bottom : 10
// });


text:
import copy
import unittest

import config
import thread_cert
from pktverify.consts import MLE_CHILD_ID_RESPONSE, MGMT_ED_SCAN, MGMT_ED_REPORT, NM_CHANNEL_MASK_TLV, NM_ENERGY_LIST_TLV
from pktverify.packet_verifier import PacketVerifier

COMMISSIONER = 1
LEADER = 2
ROUTER1 = 3
ED = 4

class Cert_9_2_13_EnergyScan_Base(thread_cert.TestCase):
    SUPPORT_NCP = False

    TOPOLOGY = {
        COMMISSIONER: {
            'name': 'COMMISSIONER',
            'mode': 'rdn',
            'allowlist': [LEADER]
        },
        LEADER: {
            'name': 'LEADER',
            'mode': 'rdn',
            'allowlist': [COMMISSIONER, ROUTER1]
        },
        ROUTER1: {
            'name': 'ROUTER',
            'mode': 'rdn',
            'allowlist': [LEADER, ED]
        },
        ED: {
            'allowlist': [ROUTER1]
        },
    }

    def test(self):
        self.nodes[LEADER].start()
        self.simulator.go(config.LEADER_STARTUP_DELAY)
        self.assertEqual(self.nodes[LEADER].get_state(), 'leader')

        self.nodes[COMMISSIONER].start()
        self.simulator.go(config.ROUTER_STARTUP_DELAY)
        self.assertEqual(self.nodes[COMMISSIONER].get_state(), 'router')
        self.nodes[COMMISSIONER].commissioner_start()
        self.simulator.go(5)

        self.nodes[ROUTER1].start()
        self.simulator.go(config.ROUTER_STARTUP_DELAY)
        self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')

        self.nodes[ED].start()
        self.simulator.go(5)
        self.assertEqual(self.nodes[ED].get_state(), 'child')
        self.collect_rlocs()

        if self.TOPOLOGY[ED]['name'] == 'DUT':
            ipaddrs = self.nodes[ED].get_addrs()
        else:
            ipaddrs = self.nodes[ROUTER1].get_addrs()

        for ipaddr in ipaddrs:
            if ipaddr[0:4] != 'fe80':
                break

        self.nodes[COMMISSIONER].energy_scan(0x50000, 0x02, 0x20, 0xc8, ipaddr)
        self.simulator.go(3)
        self.nodes[COMMISSIONER].energy_scan(0x50000, 0x02, 0x20, 0xc8, 'ff33:0040:fd00:db8:0:0:0:1')
        self.simulator.go(3)

        self.assertTrue(self.nodes[COMMISSIONER].ping(ipaddr))

    def verify(self, pv):
        pkts = pv.pkts
        pv.summary.show()

        DUT = pv.vars['DUT']
        DUT_RLOC = pv.vars['DUT_RLOC']
        COMMISSIONER_RLOC = pv.vars['COMMISSIONER_RLOC']
        _pkts = pkts.filter_wpan_src64(DUT)

        # Step 3: The DUT MUST send MGMT_ED_REPORT.ans to the Commissioner and report energy measurements
        _pkts.filter_ipv6_dst(COMMISSIONER_RLOC).filter_coap_request(MGMT_ED_REPORT).must_next().must_verify(
            lambda p: {NM_CHANNEL_MASK_TLV, NM_ENERGY_LIST_TLV} == set(p.thread_meshcop.tlv.type) and p.thread_meshcop.
            tlv.chan_mask_mask == '0000a000' and len(p.thread_meshcop.tlv.energy_list) == 2)

        # Step 5: The DUT MUST send MGMT_ED_REPORT.ans to the Commissioner and report energy measurements
        _pkts.filter_ipv6_dst(COMMISSIONER_RLOC).filter_coap_request(MGMT_ED_REPORT).must_next().must_verify(
            lambda p: {NM_CHANNEL_MASK_TLV, NM_ENERGY_LIST_TLV} == set(p.thread_meshcop.tlv.type) and p.thread_meshcop.
            tlv.chan_mask_mask == '0000a000' and len(p.thread_meshcop.tlv.energy_list) == 2)

        # Step 6: The DUT MUST respond with ICMPv6 Echo Reply
        _pkts.filter_ping_reply().filter_ipv6_src_dst(DUT_RLOC, COMMISSIONER_RLOC).must_next()

class Cert_9_2_13_EnergyScan_FED(Cert_9_2_13_EnergyScan_Base):
    TOPOLOGY = copy.deepcopy(Cert_9_2_13_EnergyScan_Base.TOPOLOGY)
    TOPOLOGY[ROUTER1]['name'] = 'ROUTER'
    TOPOLOGY[ED]['name'] = 'DUT'
    TOPOLOGY[ED]['router_upgrade_threshold'] = 0

class Cert_9_2_13_EnergyScan_MED(Cert_9_2_13_EnergyScan_Base):
    TOPOLOGY = copy.deepcopy(Cert_9_2_13_EnergyScan_Base.TOPOLOGY)
    TOPOLOGY[ROUTER1]['name'] = 'ROUTER'
    TOPOLOGY[ED]['name'] = 'DUT'
    TOPOLOGY[ED]['mode'] = 'rn'
    TOPOLOGY[ED]['is_mtd'] = True

class Cert_9_2_13_EnergyScan_ROUTER(Cert_9_2_13_EnergyScan_Base):
    TOPOLOGY = copy.deepcopy(Cert_9_2_13_EnergyScan_Base.TOPOLOGY)
    TOPOLOGY[ROUTER1]['name'] = 'DUT'
    TOPOLOGY[ED]['name'] = 'ED'
    TOPOLOGY[ED]['mode'] = 'rn'
    TOPOLOGY[ED]['is_mtd'] = True

class Cert_9_2_13_EnergyScan_SED(Cert_9_2_13_EnergyScan_Base):
    TOPOLOGY = copy.deepcopy(Cert_9_2_13_EnergyScan_Base.TOPOLOGY)
    TOPOLOGY[ROUTER1]['name'] = 'ROUTER'
    TOPOLOGY[ED]['name'] = 'DUT'
    TOPOLOGY[ED]['mode'] = '-'
    TOPOLOGY[ED]['is_mtd'] = True
    TOPOLOGY[ED]['timeout'] = config.DEFAULT_CHILD_TIMEOUT

del (Cert_9_2_13_EnergyScan_Base)

if __name__ == '__main__':
    unittest.main()


text:
package dot.junit.opcodes.iget_boolean.d;

public class T_iget_boolean_21 {

    public boolean run(){
        return false;
    }
}


text:
require File.expand_path('../shared/rectangular', __FILE__)

ruby_version_is "1.9" do
  describe "Matrix#rectangular" do
    it_behaves_like(:matrix_rectangular, :rectangular)
  end
end


text:
require 'net/http'
require 'uri'

require 'bildchen/version'
require 'bildchen/resolver'

module Bildchen

  USER_AGENT = "Bildchen v#{VERSION} (github.com/glaszig/bildchen)"
  ICON_NAMES = %w(favicon.ico favicon.png favicon.gif favicon.svg)

  # Default timeout for Net::HTTP interactions
  @timeout = 5

  class << self
    attr_accessor :timeout
  end

  def self.[] url
    @registry ||= {}
    @registry[url] ||= begin
      Resolver.new(url).resolve
    end
  end

end


text:
package thereisnospon.acclient.modules.problem.list;

import java.io.IOException;
import java.util.List;

import okhttp3.Response;
import thereisnospon.acclient.api.HdojApi;
import thereisnospon.acclient.data.HdojProblem;
import thereisnospon.acclient.utils.net.HttpUtil;

/**
 * @author threeisnospon
 * 首页题目 Model
 * Created by yzr on 16/6/5.
 */
public class HdojProbelemModeImpl implements HdojContact.Model {

    int currentPage=1;
    int mloadPge=-1;

    public HdojProbelemModeImpl(int page){
        this.mloadPge=page;
    }

    @Override
    public List<HdojProblem> loadPage(int page) {
        String html=getHtml(page);
        List<HdojProblem>list= HdojProblem.Builder.buildProblems(html);
        if(list!=null&&list.size()>0){
            this.currentPage=page;
        }
        return list;
    }

    private String getHtml(int page){
        try{
            Response response= HttpUtil.getInstance()
                    .get(HdojApi.PROBLEM_LIST)
                    .addParameter("vol",""+page)
                    .execute();
            String html=  new String(response.body().bytes(),"gb2312");
            return html;
        }catch (IOException e){
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public List<HdojProblem> requestRefresh() {
        if(mloadPge!=-1){
            return loadPage(mloadPge);
        }else{
            return loadPage(1);
        }
    }

    @Override
    public List<HdojProblem> requestMore() {
        if(mloadPge!=-1)
            return null;
        String html=getHtml(currentPage+1);
        List<HdojProblem>list= HdojProblem.Builder.buildProblems(html);
        if(list!=null&&list.size()>0){
            currentPage++;
        }
        return list;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter PUBLIC "urn:pubid:dita4publishers.org:doctypes:dita:chapter" "chapter.dtd">
<chapter
  id="chapter-id">
  <title>D4P Vocabulary tests</title>

<indexterm>DITA for
      Publishers<indexterm>vocabulary</indexterm></indexterm>Tests of D4P
      vocabulary elements.

  <subsection
    id="subsection_vvn_jvk_x2">
    <title>Simple Enumeration Domain</title>

<indexterm>enumeration domain</indexterm><indexterm>DITA for
        Publisherss<indexterm>enumeration
        domain</indexterm></indexterm><indexterm>domains<indexterm>enumeration</indexterm></indexterm>Here
        is a simple enumerator with the value "4" (between the quotes):
        "<d4pSimpleEnumerator>4</d4pSimpleEnumerator>".

  </subsection>
  <subsection
    id="subsection_oyp_gtd_sn">
    <title>D4P XML Domain</title>

Element: <xmlelem>elementName</xmlelem>

  </subsection>
</chapter>


text:
import expect from 'expect.js';

import {
  bdd,
  scenarioManager,
  esClient
} from '../../../support';

import PageObjects from '../../../support/page_objects';

bdd.describe('initial state', function () {
  bdd.before(function () {
    // delete .kibana index and then wait for Kibana to re-create it
    return esClient.deleteAndUpdateConfigDoc()
    .then(function () {
      return PageObjects.settings.navigateTo();
    })
    .then(function () {
      return PageObjects.settings.clickKibanaIndicies();
    });
  });

  bdd.it('should load with time pattern checked', function () {
    return PageObjects.settings.getTimeBasedEventsCheckbox().isSelected()
    .then(function (selected) {
      PageObjects.common.saveScreenshot('Settings-initial-state');
      expect(selected).to.be.ok();
    });
  });

  bdd.it('should load with name pattern unchecked', function () {
    return PageObjects.settings.getTimeBasedIndexPatternCheckbox().isSelected()
    .then(function (selected) {
      expect(selected).to.not.be.ok();
    });
  });

  bdd.it('should contain default index pattern', function () {
    const defaultPattern = 'logstash-*';

    return PageObjects.settings.getIndexPatternField().getProperty('value')
    .then(function (pattern) {
      expect(pattern).to.be(defaultPattern);
    });
  });

  bdd.it('should not select the time field', function () {
    return PageObjects.settings.getTimeFieldNameField().isSelected()
    .then(function (timeFieldIsSelected) {
      PageObjects.common.debug('timeField isSelected = ' + timeFieldIsSelected);
      expect(timeFieldIsSelected).to.not.be.ok();
    });
  });

  bdd.it('should not be enable creation', function () {
    return PageObjects.settings.getCreateButton().isEnabled()
    .then(function (enabled) {
      expect(enabled).to.not.be.ok();
    });
  });
});


text:
package com.thoughtworks.go.plugin.access.common.models;

import com.thoughtworks.go.plugin.domain.common.Metadata;
import com.thoughtworks.go.plugin.domain.common.PluginConfiguration;
import org.junit.Test;

import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;

public class PluginProfileMetadataKeysTest {

    @Test
    public void shouldUnJSONizeProfileMetadata() throws Exception {
        PluginProfileMetadataKeys metadata = PluginProfileMetadataKeys.fromJSON("[{\n" +
                "  \"key\": \"foo\",\n" +
                "  \"metadata\": {\n" +
                "    \"secure\": true,\n" +
                "    \"required\": false\n" +
                "  }\n" +
                "}, {\n" +
                "  \"key\": \"bar\"\n" +
                "}]");
        assertThat(metadata.size(), is(2));
        PluginProfileMetadataKey foo = metadata.get("foo");
        assertThat(foo.getMetadata().isRequired(), is(false));
        assertThat(foo.getMetadata().isSecure(), is(true));

        PluginProfileMetadataKey bar = metadata.get("bar");
        assertThat(bar.getMetadata().isRequired(), is(false));
        assertThat(bar.getMetadata().isSecure(), is(false));
    }

    @Test
    public void shouldGetPluginConfigurations() throws Exception {
        PluginProfileMetadataKeys metadata = PluginProfileMetadataKeys.fromJSON("[{\n" +
                "  \"key\": \"username\",\n" +
                "  \"metadata\": {\n" +
                "    \"secure\": true,\n" +
                "    \"required\": false\n" +
                "  }\n" +
                "}, {\n" +
                "  \"key\": \"password\",\n" +
                "  \"metadata\": {\n" +
                "    \"secure\": true,\n" +
                "    \"required\": true\n" +
                "  }\n" +
                "}]");

        List<PluginConfiguration> pluginConfigurations = metadata.toPluginConfigurations();

        assertThat(pluginConfigurations, containsInAnyOrder(
                new PluginConfiguration("username", new Metadata(false, true)),
                new PluginConfiguration("password", new Metadata(true, true))));
    }

    @Test
    public void shouldGetPluginConfigurationsWithMetadataDefaultedToFalseInAbsenceOfPluginMetadata() throws Exception {
        PluginProfileMetadataKeys metadata = PluginProfileMetadataKeys.fromJSON("[{\n" +
                "  \"key\": \"username\"\n" +
                "}, {\n" +
                "  \"key\": \"password\",\n" +
                "  \"metadata\": {\n" +
                "    \"secure\": true,\n" +
                "    \"required\": true\n" +
                "  }\n" +
                "}]");

        List<PluginConfiguration> pluginConfigurations = metadata.toPluginConfigurations();

        assertThat(pluginConfigurations, containsInAnyOrder(
                new PluginConfiguration("username", new Metadata(false, false)),
                new PluginConfiguration("password", new Metadata(true, true))));
    }
}


text:
/*
 * Login Messages
 *
 * This contains all the text for the Login component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  header: {
    id: 'app.containers.login_page.header',
    defaultMessage: 'LOG IN',
  },
});


text:
package org.sagebionetworks.web.client.widget.team;

import org.sagebionetworks.repo.model.Team;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.SynapseJSNIUtils;
import org.sagebionetworks.web.client.SynapseJavascriptClient;
import org.sagebionetworks.web.client.SynapseProperties;
import org.sagebionetworks.web.client.widget.HasNotificationUI;
import org.sagebionetworks.web.client.widget.SynapseWidgetPresenter;
import org.sagebionetworks.web.client.widget.asynch.TeamAsyncHandler;
import org.sagebionetworks.web.shared.WebConstants;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class TeamBadge implements SynapseWidgetPresenter, HasNotificationUI, IsWidget {

	private TeamBadgeView view;
	TeamAsyncHandler teamAsyncHandler;
	private Integer maxNameLength;
	private String teamName;
	private ClickHandler customClickHandler = null;
	String publicAclPrincipalId, authenticatedAclPrincipalId;
	public static final String PUBLIC_GROUP_NAME = "Anyone on the web";
	public static final String AUTHENTICATED_USERS_GROUP_NAME = "All registered Synapse users";
	SynapseJavascriptClient jsClient;
	SynapseJSNIUtils synapseJsniUtils;

	@Inject
	public TeamBadge(TeamBadgeView view, TeamAsyncHandler teamAsyncHandler, SynapseProperties synapseProperties, SynapseJSNIUtils synapseJsniUtils, SynapseJavascriptClient jsClient) {
		this.view = view;
		this.teamAsyncHandler = teamAsyncHandler;
		this.synapseJsniUtils = synapseJsniUtils;
		this.jsClient = jsClient;
		publicAclPrincipalId = synapseProperties.getSynapseProperty(WebConstants.PUBLIC_ACL_PRINCIPAL_ID);
		authenticatedAclPrincipalId = synapseProperties.getSynapseProperty(WebConstants.AUTHENTICATED_ACL_PRINCIPAL_ID);
	}

	public void setMaxNameLength(Integer maxLength) {
		this.maxNameLength = maxLength;
	}

	public void configure(String teamId, ClickHandler customClickHandler) {
		this.customClickHandler = customClickHandler;
		configure(teamId);
	}

	public void configure(String teamId) {
		if (teamId != null && teamId.trim().length() > 0) {
			if (teamId.equals(publicAclPrincipalId)) {
				view.setTeamWithoutLink(PUBLIC_GROUP_NAME, true);
			} else if (teamId.equals(authenticatedAclPrincipalId)) {
				view.setTeamWithoutLink(AUTHENTICATED_USERS_GROUP_NAME, true);
			} else {
				view.showLoading();
				teamAsyncHandler.getTeam(teamId, new AsyncCallback<Team>() {
					@Override
					public void onSuccess(Team team) {
						configure(team);
					}

					@Override
					public void onFailure(Throwable caught) {
						if (teamName != null) {
							view.setTeamWithoutLink(teamName, false);
						} else {
							view.showLoadError(teamId);
						}
					}
				});
			} ;
		}

	}

	public void configure(Team team) {
		if (DisplayUtils.isDefined(team.getIcon())) {
			jsClient.getTeamPicturePreviewURL(team.getId(), new AsyncCallback<String>() {
				@Override
				public void onFailure(Throwable caught) {
					synapseJsniUtils.consoleError(caught);
					setViewTeam(team, null);
				}
				@Override
				public void onSuccess(String teamIconUrl) {
					setViewTeam(team, teamIconUrl);
				}
			});
		} else {
			setViewTeam(team, null);
		}
	}

	private void setViewTeam(Team team, String teamIconUrl) {
		view.setTeam(team, maxNameLength, teamIconUrl, customClickHandler);
	}

	/**
	 * If the teamId is not valid, a badge will be created from the given teamName.
	 */
	public void configure(String teamId, String teamName) {
		this.teamName = teamName;
		configure(teamId);
	}

	@SuppressWarnings("unchecked")
	public void clearState() {}

	@Override
	public Widget asWidget() {
		return view.asWidget();
	}

	public void setVisible(boolean visible) {
		view.setVisible(visible);
	}

	@Override
	public void setNotificationValue(String value) {
		view.setRequestCount(value);
	}

	public void addStyleName(String style) {
		view.addStyleName(style);
	}

	public void setOpenNewWindow(boolean isNewWindow) {
		String target = isNewWindow ? "_blank" : "";
		view.setTarget(target);
	}
}


text:
/*
 * StructSetOrResultsSet.java Utlity Class : Can be used to compare the results (StructSet OR
 * ResultsSet) under the scenario without/with Index Usage. Created on June 13, 2005, 11:16 AM
 */
package org.apache.geode.cache.query.functional;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.geode.LogWriter;
import org.apache.geode.cache.query.CacheUtils;
import org.apache.geode.cache.query.FunctionDomainException;
import org.apache.geode.cache.query.NameResolutionException;
import org.apache.geode.cache.query.Query;
import org.apache.geode.cache.query.QueryInvocationTargetException;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.cache.query.Struct;
import org.apache.geode.cache.query.TypeMismatchException;
import org.apache.geode.cache.query.internal.CompiledGroupBySelect;
import org.apache.geode.cache.query.internal.CompiledSelect;
import org.apache.geode.cache.query.internal.CompiledSortCriterion;
import org.apache.geode.cache.query.internal.CompiledValue;
import org.apache.geode.cache.query.internal.DefaultQuery;
import org.apache.geode.cache.query.internal.ExecutionContext;
import org.apache.geode.cache.query.internal.OrderByComparator;
import org.apache.geode.cache.query.internal.QueryObserverAdapter;
import org.apache.geode.cache.query.internal.QueryObserverHolder;
import org.apache.geode.cache.query.types.ObjectType;
import org.apache.geode.internal.util.ArrayUtils;

/**
 * Used by these tests:
 *

 *
EquiJoinIntegrationTest

 *
IUMRCompositeIteratorJUnitTest

 *
IUMRMultiIndexesMultiRegionJUnitTest

 *
IUMRShuffleIteratorsJUnitTest

 *
IUMRSingleRegionJUnitTest

 *
IndexCreationJUnitTest

 *
IndexHintJUnitTest

 *
IndexMaintainceJUnitTest

 *
IndexUseJUnitTest

 *
IndexedMergeEquiJoinScenariosJUnitTest

 *
MultiRegionIndexUsageJUnitTest

 *
NonDistinctOrderByPartitionedJUnitTest

 *
NonDistinctOrderByReplicatedJUnitTest

 *
NonDistinctOrderByTestImplementation

 *
OrderByPartitionedJUnitTest

 *
OrderByReplicatedJUnitTest

 *
OrderByTestImplementation

 *
QueryIndexUsingXMLDUnitTest

 *
QueryREUpdateInProgressJUnitTest

 *
QueryUsingFunctionContextDUnitTest

 *
QueryUsingPoolDUnitTest

 *
TestNewFunctionSSorRSIntegrationTest

 *

 * Also used by:
 *

 *
GroupByTestImpl

 *
PdxGroupByTestImpl

 *
PRQueryDUnitHelper

 *

 */
public class StructSetOrResultsSet {

  public void CompareQueryResultsWithoutAndWithIndexes(Object[][] r, int len, String[] queries) {
    CompareQueryResultsWithoutAndWithIndexes(r, len, false, queries);
  }

  /* Creates a new instance of StructSetOrResultsSet */
  public void CompareQueryResultsWithoutAndWithIndexes(Object[][] r, int len, boolean checkOrder,
      String[] queries) {

    Collection coll1;
    Collection coll2;
    for (int j = 0; j < len; j++) {
      checkSelectResultTypes((SelectResults) r[j][0], (SelectResults) r[j][1], queries[j]);
      checkResultSizes((SelectResults) r[j][0], (SelectResults) r[j][1], queries[j]);

      if (checkOrder) {
        coll2 = (((SelectResults) r[j][1]).asList());
        coll1 = (((SelectResults) r[j][0]).asList());
      } else {
        coll2 = (((SelectResults) r[j][1]).asSet());
        coll1 = (((SelectResults) r[j][0]).asSet());
      }
      compareResults(coll1, coll2, queries[j], checkOrder);
    }
  }

  public void compareExternallySortedQueriesWithOrderBy(String[] queries, Object[][] baseResults)
      throws Exception {
    for (int i = 0; i < queries.length; i++) {
      Query q;
      try {
        String query = queries[i];
        int indexOfOrderBy = query.indexOf("order ");
        query = query.substring(0, indexOfOrderBy);
        q = CacheUtils.getQueryService().newQuery(query);
        CacheUtils.getLogger().info("Executing query: " + query);
        baseResults[i][1] = q.execute();
        int unorderedResultsSize = ((SelectResults) baseResults[i][1]).size();
        if (unorderedResultsSize == 0) {
          fail(
              "The test results size is 0. It may not be validating anything. Please rewrite the test.");
        }
        Wrapper wrapper = getOrderByComparatorAndLimitForQuery(queries[i], unorderedResultsSize);
        if (wrapper.validationLevel != ValidationLevel.NONE) {
          Object[] externallySorted = ((SelectResults) baseResults[i][1]).toArray();
          if (wrapper.validationLevel != ValidationLevel.MATCH_ONLY) {
            Arrays.sort(externallySorted, wrapper.obc);
          }
          if (wrapper.limit != -1) {
            if (externallySorted.length > wrapper.limit) {
              Object[] newExternallySorted = new Object[wrapper.limit];
              System.arraycopy(externallySorted, 0, newExternallySorted, 0, wrapper.limit);
              externallySorted = newExternallySorted;
            }
          }
          StructSetOrResultsSet ssOrrs1 = new StructSetOrResultsSet();
          ssOrrs1.compareQueryResultsWithExternallySortedResults((SelectResults) baseResults[i][0],
              externallySorted, queries[i], wrapper);

        }
      } catch (Exception e) {
        e.printStackTrace();
        throw new AssertionError(
            "query with index=" + i + " has failed. failed query=" + queries[i], e);
      }
    }
  }

  private void compareQueryResultsWithExternallySortedResults(SelectResults sr,
      Object[] externallySorted, String query, Wrapper wrapper) {

    if (sr.size() == externallySorted.length) {
      CacheUtils.log("Both SelectResults are of Same Size i.e.  Size= " + sr.size());
    } else {
      fail("FAILED:SelectResults size is different in both the cases. Size1=" + sr.size()
          + " Size2 = " + externallySorted.length + "; failed query=" + query);
    }

    Collection coll1 = null;
    coll1 = sr.asList();
    int j = 0;
    if (wrapper.validationLevel != ValidationLevel.ORDER_BY_ONLY) {
      for (Object o : externallySorted) {
        boolean removed = coll1.remove(o);
        if (!removed) {
          LogWriter logger = CacheUtils.getLogger();
          logger.error("order by inconsistency at element index = " + j);
          logger.error(" query result =****");
          logger.error(" query result =" + coll1);
          logger.error(" query result elementType=" + sr.getCollectionType().getElementType());
          logger.error(" externally sorted result =****");
          logger.error(ArrayUtils.toString(externallySorted));

          fail("failed query due to element mismatch=" + query);
        }
        ++j;
      }
      assertTrue(coll1.isEmpty());
    }

    if (wrapper.validationLevel != ValidationLevel.MATCH_ONLY) {
      coll1 = sr.asList();
      Iterator itert1 = coll1.iterator();
      int i = 0;
      for (Object o : externallySorted) {

        if (wrapper.obc.compare(o, itert1.next()) != 0) {
          LogWriter logger = CacheUtils.getLogger();
          logger.error("order by inconsistency at element index = " + i);
          logger.error(" query result =****");
          logger.error(" query result =" + coll1);
          logger.error(" externally sorted result =****");
          logger.error(ArrayUtils.toString(externallySorted));
          fail("failed query due to order mismatch=" + query);
        }
        ++i;
      }
    }
  }

  public Wrapper getOrderByComparatorAndLimitForQuery(String orderByQuery, int unorderedResultSize)
      throws FunctionDomainException, TypeMismatchException, NameResolutionException,
      QueryInvocationTargetException, NoSuchFieldException, SecurityException,
      IllegalArgumentException, IllegalAccessException, NoSuchMethodException,
      InvocationTargetException {
    DefaultQuery q = (DefaultQuery) CacheUtils.getQueryService().newQuery(orderByQuery);
    CompiledSelect cs = q.getSimpleSelect();
    List<CompiledSortCriterion> orderByAttribs = null;
    if (cs.getType() == CompiledValue.GROUP_BY_SELECT) {
      Field originalOrderByMethod =
          CompiledGroupBySelect.class.getDeclaredField("originalOrderByClause");
      originalOrderByMethod.setAccessible(true);
      orderByAttribs = (List<CompiledSortCriterion>) originalOrderByMethod.get(cs);
    } else {
      orderByAttribs = cs.getOrderByAttrs();
    }
    ObjectType resultType = cs.getElementTypeForOrderByQueries();
    ExecutionContext context = new ExecutionContext(null, CacheUtils.getCache());
    final OrderByComparator obc = new OrderByComparator(orderByAttribs, resultType, context);
    Comparator baseComparator = obc;
    if (resultType.isStructType()) {
      baseComparator =
          (Comparator<Struct>) (o1, o2) -> obc.compare(o1.getFieldValues(), o2.getFieldValues());
    }
    final Comparator secondLevelComparator = baseComparator;
    final Comparator finalComparator = (o1, o2) -> {
      final boolean[] orderByColsEqual = new boolean[] {false};
      QueryObserverHolder.setInstance(new QueryObserverAdapter() {
        @Override
        public void orderByColumnsEqual() {
          orderByColsEqual[0] = true;
        }
      });
      int result = secondLevelComparator.compare(o1, o2);
      if (result != 0 && orderByColsEqual[0]) {
        result = 0;
      }
      return result;
    };

    Field hasUnmappedOrderByColsField =
        CompiledSelect.class.getDeclaredField("hasUnmappedOrderByCols");
    hasUnmappedOrderByColsField.setAccessible(true);
    boolean skip = (Boolean) hasUnmappedOrderByColsField.get(cs);
    ValidationLevel validationLevel = ValidationLevel.ALL;

    int limit;

    if (cs.getType() == CompiledValue.GROUP_BY_SELECT) {
      Field limitCVField = CompiledGroupBySelect.class.getDeclaredField("limit");
      limitCVField.setAccessible(true);
      CompiledValue limitCV = (CompiledValue) limitCVField.get(cs);
      Method evaluateLimitMethod = CompiledSelect.class.getDeclaredMethod("evaluateLimitValue",
          ExecutionContext.class, CompiledValue.class);
      evaluateLimitMethod.setAccessible(true);
      limit = (Integer) evaluateLimitMethod.invoke(null, context, limitCV);
    } else {
      limit = cs.getLimitValue(null);
    }

    if (limit != -1 && limit < unorderedResultSize) {
      // chances are that results will not match
      if (skip) {
        validationLevel = ValidationLevel.NONE;
      } else {
        validationLevel = ValidationLevel.ORDER_BY_ONLY;
      }
    } else {
      if (skip) {
        validationLevel = ValidationLevel.MATCH_ONLY;
      }
    }
    return new Wrapper(finalComparator, limit, validationLevel);
  }

  enum ValidationLevel {
    ALL, ORDER_BY_ONLY, MATCH_ONLY, NONE
  }

  private static class Wrapper {
    final Comparator obc;
    final int limit;
    final ValidationLevel validationLevel;

    Wrapper(Comparator obc, int limit, ValidationLevel validationLevel) {
      this.obc = obc;
      this.limit = limit;
      this.validationLevel = validationLevel;
    }
  }

  /* Creates a new instance of StructSetOrResultsSet */
  public void CompareCountStarQueryResultsWithoutAndWithIndexes(Object[][] r, int len,
      boolean checkOrder, String[] queries) {

    Integer count1, count2;
    Iterator<Integer> itert1, itert2;
    SelectResults result1, result2;
    boolean exactMatch = true;
    for (int j = 0; j < len; j++) {
      result1 = ((SelectResults) r[j][0]);
      result2 = ((SelectResults) r[j][1]);
      assertEquals(queries[j], 1, result1.size());
      assertEquals(queries[j], 1, result2.size());

      checkSelectResultTypes((SelectResults) r[j][0], (SelectResults) r[j][1], queries[j]);
      checkResultSizes((SelectResults) r[j][0], (SelectResults) r[j][1], queries[j]);
      compareResults(result1, result2, queries[j], true);
    }
  }

  /*
   * Compares two ArrayLists containing query results with/without order.
   */
  public void CompareQueryResultsAsListWithoutAndWithIndexes(Object[][] r, int len,
      boolean checkOrder, String[] queries) {
    CompareQueryResultsAsListWithoutAndWithIndexes(r, len, checkOrder, true, queries);
  }

  public void CompareQueryResultsAsListWithoutAndWithIndexes(Object[][] r, int len,
      boolean checkOrder, boolean checkClass, String[] queries) {
    Integer count1, count2;
    Iterator<Integer> itert1, itert2;
    ArrayList result1, result2;

    for (int j = 0; j < len; j++) {
      result1 = ((ArrayList) r[j][0]);
      result2 = ((ArrayList) r[j][1]);
      result1.trimToSize();
      result2.trimToSize();

      compareQueryResultLists(result1, result2, len, checkOrder, checkClass, queries[j]);
    }
  }

  public void compareQueryResultLists(List r1, List r2, int len, boolean checkOrder,
      boolean checkClass, String query) {
    if (checkClass) {
      if ((r1.get(0).getClass().getName()).equals(r2.get(0).getClass().getName())) {
        CacheUtils.log(
            "Both SelectResults are of the same Type i.e.--> " + r1.get(0).getClass().getName());
      } else {
        fail("FAILED:Select result Type is different in both the cases."
            + r1.get(0).getClass().getName() + "and" + r1.get(0).getClass().getName()
            + "; failed query=" + query);
      }
    }

    checkResultSizes(r1, r2, query);
    compareResults(r1, r2, query, checkOrder);
  }

  private void checkSelectResultTypes(SelectResults r1, SelectResults r2, String query) {
    ObjectType type1, type2;
    type1 = r1.getCollectionType().getElementType();
    type2 = r2.getCollectionType().getElementType();
    if (!(type1.getClass().getName()).equals(type2.getClass().getName())) {
      CacheUtils
          .log("Classes are : " + type1.getClass().getName() + " " + type2.getClass().getName());
      fail("FAILED:Select result Type is different in both the cases." + "; failed query=" + query);
    }
  }

  private void checkResultSizes(Collection r1, Collection r2, String query) {
    if (r1.size() != r2.size()) {
      fail("FAILED:SelectResults size is different in both the cases. Size1=" + r1.size()
          + " Size2 = " + r2.size() + "; failed query=" + query);
    }
  }

  private void compareResults(Collection result1, Collection result2, String query,
      boolean checkOrder) {
    Iterator itert1 = result1.iterator();
    Iterator itert2 = result2.iterator();
    int currentIndex = 0;
    while (itert1.hasNext()) {
      Object p1 = itert1.next();
      Object p2 = null;
      if (!checkOrder) {
        if (!collectionContains(result2, p1)) {
          fail("Atleast one element in the pair of SelectResults "
              + "supposedly identical, is not equal " + "Match not found for :" + p1
              + " compared with:" + p2 + "; failed query=" + query + "; element unmatched =" + p1
              + ";p1 class=" + p1.getClass() + " ; other set has =" + result2);
        }
      } else {
        boolean matched = false;
        if (itert2.hasNext()) {
          p2 = itert2.next();
          matched = objectsEqual(p1, p2);
          if (!matched) {
            fail("Order of results was not the same, match not found for :" + p1 + " compared with:"
                + p2 + "; failed query=" + query + "; element unmatched =" + p1 + ";p1 class="
                + p1.getClass() + " compared with " + p2 + ";p2 class=" + p2.getClass()
                + "currentIndex:" + currentIndex + "\nr1:" + result1 + "\n\nr2:" + result2);
          }
        }
      }
      currentIndex++;
    }
  }

  private boolean collectionContains(Collection collection, Object object) {
    for (final Object o : collection) {
      if (objectsEqual(object, o)) {
        return true;
      }
    }
    return false;
  }

  private boolean objectsEqual(Object o1, Object o2) {
    // Assumed that o1 and o2 are the same object type as both are from collections created by
    // executing the same query
    if (o1 instanceof Struct) {
      // if o2 is null, an NPE will be thrown.
      Object[] values1 = ((Struct) o1).getFieldValues();
      Object[] values2 = ((Struct) o2).getFieldValues();
      assertEquals(values1.length, values2.length);
      boolean elementEqual = true;
      for (int i = 0; i < values1.length; ++i) {
        elementEqual =
            elementEqual && ((values1[i] == values2[i]) || values1[i].equals(values2[i]));
      }
      return elementEqual;
    } else {
      // if o1 is null and o2 is not, an NPE will be thrown
      return o1 == o2 || o1.equals(o2);
    }
  }
}


text:
package edu.wustl.common.query.queryobject.impl.metadata;

import java.util.ArrayList;
import java.util.List;

import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.query.queryobject.impl.OutputTreeDataNode;
import edu.wustl.common.querysuite.queryobject.IOutputAttribute;

/**
 *
 * @author deepti_shelar
 *
 */
public class SelectedColumnsMetadata
{

	/**
	 * Selected object by user at the time of defining columns.
	 */
	private OutputTreeDataNode currentSelectedObject;
	/**
	 * List of attributes user has selected.
	 */
	private List<QueryOutputTreeAttributeMetadata> selectedAttributeMetaDataList;
	/**
	 * List of name value bean object for selected columns.
	 */
	private List<NameValueBean> selColNVBeanList;

	/**
	 * Returns true/false Whether view is defined.
	 */
	private boolean ifDefinedView;
	/**
	 * List of output attribute objects.
	 */
	private List<IOutputAttribute> selectedOutputAttributeList;

	/**
	 * Check if it's define view.
	 * @return ifDefinedView
	 */
	public boolean isDefinedView()
	{
		return ifDefinedView;
	}

	/**
	 * Set defined view.
	 * @param isDefinedView isDefinedView
	 */
	public void setDefinedView(boolean isDefinedView)
	{
		this.ifDefinedView = isDefinedView;
	}

	/**
	 * Returns the attribute list.
	 * @return attributeList
	 */
	public List<AttributeInterface> getAttributeList()
	{
		List<AttributeInterface> attributeList = new ArrayList<AttributeInterface>();
		if (selectedAttributeMetaDataList != null)
		{
			for (QueryOutputTreeAttributeMetadata metadata : selectedAttributeMetaDataList)
			{
				attributeList.add(metadata.getAttribute());
			}
		}
		return attributeList;
	}

	//	public void setAttributeList(List<AttributeInterface> attributeList)
	//	{
	//		this.attributeList = attributeList;
	//	}
	/**
	 * Get current selected object.
	 * @return currentSelectedObject
	 */
	public OutputTreeDataNode getCurrentSelectedObject()
	{
		return currentSelectedObject;
	}

	/**
	 * @param currentSelectedObject the currentSelectedObject to set
	 */
	public void setCurrentSelectedObject(OutputTreeDataNode currentSelectedObject)
	{
		this.currentSelectedObject = currentSelectedObject;
	}

	/**
	 * @return the selColNVBeanList
	 */
	public List<NameValueBean> getSelColNVBeanList()
	{
		return selColNVBeanList;
	}

	/**
	 * @param selColNVBeanList the selColNVBeanList to set
	 */
	public void setSelColNVBeanList(
			List<NameValueBean> selColNVBeanList)
	{
		this.selColNVBeanList = selColNVBeanList;
	}

	/**
	 * @return the selectedAttributeMetaDataList
	 */
	public List<QueryOutputTreeAttributeMetadata> getSelectedAttributeMetaDataList()
	{
		return selectedAttributeMetaDataList;
	}

	/**
	 * @param selectedAttributeMetaDataList the selectedAttributeMetaDataList to set
	 */
	public void setSelectedAttributeMetaDataList(
			List<QueryOutputTreeAttributeMetadata> selectedAttributeMetaDataList)
	{
		this.selectedAttributeMetaDataList = selectedAttributeMetaDataList;
	}

	/**
	 * @return the selectedOutputAttributeList
	 */
	public List<IOutputAttribute> getSelectedOutputAttributeList()
	{
		return selectedOutputAttributeList;
	}

	/**
	 * @param selectedOutputAttributeList the selectedOutputAttributeList to set
	 */
	public void setSelectedOutputAttributeList(List<IOutputAttribute> selectedOutputAttributeList)
	{
		this.selectedOutputAttributeList = selectedOutputAttributeList;
	}
}


text:
package ch.javasoft.metabolic.efm.sort;

import java.util.logging.Logger;

import ch.javasoft.util.logging.Loggers;

/*package*/ class LogPkg {
	public static final Logger LOGGER = Loggers.getLogger(LogPkg.class, -2);

	//no instances
	private LogPkg() {
		super();
	}

}


text:
class Contacts
  def self.menu *args
    Notes.drill '$c', *args
  end
end


text:
Automate and enhance your workflow.

* [Gulp.js](http://gulpjs.com/)
* [Docs](https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md)


text:
var prettyBytes = require('pretty-bytes')
var prettyMs = require('pretty-ms')
var isAbsolute = require('path-is-absolute')
var browserify = require('browserify')
var UglifyJS = require('uglify-js')
var CleanCSS = require('clean-css')
var path = require('path')
var fs = require('fs')
var color = require('term-color')
var simpleHtml = require('simple-html-index')
var hyperstream = require('hyperstream')
var envify = require('loose-envify')
var uglifyify = require('uglifyify')
var collapser = require('bundle-collapser/plugin')

var now

module.exports = build
function build (argv, babelify) {
  // set for React et al that use envify
  process.env.NODE_ENV = 'production'

  now = Date.now()
  console.error('‣', color.magenta('build'), color.bold(argv._[1]))
  var bundler = browserify({
    transform: babelify
  })

  argv._.forEach(function (file) {
    bundler.add(path.resolve(file))
  })

  bundler.transform(envify)
  bundler.transform(uglifyify)
  bundler.plugin(collapser)

  bundler.bundle(function (err, src) {
    if (err) throw err
    prep(argv, src)
  })
}

function prep (argv, src) {
  log(src.length)
  console.error('‣', color.magenta('uglify'), color.bold(argv._[1]))

  var result = UglifyJS.minify(src.toString(), { fromString: true }).code
  log(result.length)

  if (argv.css) {
    console.error('‣', color.magenta('css-compress'), color.bold(argv._[1]))
    var cssFile = argv.css
    cssFile = isAbsolute(cssFile) ? cssFile : path.resolve(process.cwd(), cssFile)
    fs.readFile(cssFile, 'utf8', function (err, cssSrc) {
      if (err) throw err
      var cssCompressed = new CleanCSS().minify(cssSrc).styles
      log(cssCompressed.length)
      emit(result, cssCompressed)
    })
  } else {
    emit(result)
  }

  function emit (compressedJS, compressedCSS) {
    var buildFile = argv.build || argv.b
    var cssAppend
    if (compressedCSS) {
      cssAppend = {
        _appendHtml: '<style type="text/css">' +
          compressedCSS + '</style>'
      }
    }

    var outStream = process.stdout
    if (typeof buildFile === 'string') {
      buildFile = isAbsolute(buildFile) ? buildFile : path.resolve(process.cwd(), buildFile)
      outStream = fs.createWriteStream(buildFile)
    }

    simpleHtml({ title: argv.title })
      .pipe(hyperstream({
        head: cssAppend,
        body: {
          _appendHtml: '<script type="text/javascript">' +
            compressedJS + '</script>'
        }
      }))
      .pipe(outStream)
  }
}

function log (length) {
  var bytes = prettyBytes(length)
  var ms = prettyMs(Date.now() - now)
  console.error('└─', color.dim(bytes), 'in', color.dim(ms))
  now = Date.now()
}


text:
#ifndef RELATION_H_
# define RELATION_H_

/* Performing operations on graphs coded as list of adjacency.

   If GRAPH is a relation, then GRAPH[Node] is a list of adjacent
   nodes, ended with END_NODE.  */

#define END_NODE ((relation_node) -1)

typedef size_t relation_node;
typedef relation_node *relation_nodes;
typedef relation_nodes *relation;

/* Report a relation R that has SIZE vertices.  */
void relation_print (relation r, relation_node size, FILE *out);

/* Compute the transitive closure of the FUNCTION on the relation R
   with SIZE vertices.

   If R (NODE-1, NODE-2) then on exit FUNCTION[NODE - 1] was extended
   (unioned) with FUNCTION[NODE - 2].  */
void relation_digraph (relation r, relation_node size, bitsetv *function);

/* Destructively transpose *R_ARG, of size N.  */
void relation_transpose (relation *R_arg, relation_node n);

#endif /* ! RELATION_H_ */


text:
<?xml version="1.0" encoding="utf-8"?>

Logging into a Site

How to login to a site. This tutorial covers the default login settings that only requires a user name and a password to login. Other user account information such as names, address details and contact details may be required for login on some sites.

Click the Login link (typically located in the top right corner of each page) - OR - Navigate to an Account Login module.

In the Username text box, enter your user name.

In the Password text box, enter your password.

    Click the  Login  button.

Optional. If the message "You are using an unverified account. Please verify your account by clicking on the link contained in the verification email we've already sent to you." is displayed, you must complete this final step in the registration to gain access all registered user services.

Once you are logged into the site and can view any messages or notifications that have been sent to your user account. You can also click on your Display Name and complete your user profile information.


text:
require 'spec_helper'

describe 'Auditable#callbacks' do

  describe Plant do
    let(:plant) { Plant.create :name => 'a green shrub' }

    it 'should have a valid audit to start with' do
      plant.name.should == 'a green shrub'
      plant.audited_changes.should == {'name' => [nil, 'a green shrub']}
      plant.audits.last.action.should == 'manual create'
    end

    it 'should create a new audit using callback' do
      plant.should_receive(:manually_update_audit) { plant.save_audit( {'action' => 'dig', :tag => 'tagged!', 'modifications' => { 'name' => 'over ruled!' } } ) }
      plant.update_attributes :name => 'an orange shrub'
      plant.audited_changes.should == {'name' => ['a green shrub', 'over ruled!']}
      plant.audits.last.action.should == 'dig'
      plant.audits.last.tag.should == 'tagged!'
    end
  end

  describe Tree do
    let(:tree) { Tree.create :name => 'a tall pine', tastey: false }

    it 'should inherit callback of the parent' do
      tree.class.audited_after_create.should eql :manually_create_audit
      tree.class.audited_after_update.should eql :manually_update_audit
    end

    it 'should have a valid audit to start with, include inherited attributes from Plant' do
      tree.name.should == 'a tall pine'
      tree.audits.size.should eql(1)
      tree.audited_changes.should == {"plants"=>[nil, []], "name"=>[nil, "a tall pine"], "tastey"=>[nil, false]}
      tree.audits.last.action.should == 'manual create'
    end

    it 'should create a new audit using callback' do
      tree.should_receive(:manually_update_audit) { tree.save_audit( {'action' => 'dig', :tag => 'tagged!', 'modifications' => { 'name' => 'over ruled!' } } ) }
      tree.update_attributes :name => 'a small oak'
      tree.audited_changes.should == {"plants"=>[[], nil], "name"=>["a tall pine", "over ruled!"]}
      tree.audits.last.action.should == 'dig'
      tree.audits.last.tag.should == 'tagged!'
    end
  end

  describe Kale do
    let(:kale) { Kale.create :name => 'a bunch of leafy kale', tastey: true }

    it 'should inherit the update callback of the parent' do
      kale.class.audited_after_update.should eql :manually_update_audit
    end

    it 'should override the create callback of the parent' do
      kale.class.audited_after_create.should eql :audit_create_callback
    end

    it 'should have a valid audit to start with, include inherited attributes from Plant' do
      kale.name.should == 'a bunch of leafy kale'
      kale.audits.size.should eql(1)
      kale.audited_changes.should == {'name'=>[nil, 'a bunch of leafy kale'], 'tastey'=>[nil, true]}
      kale.audits.last.action.should == 'audit action'
    end

    it 'should create a new audit using callback' do
      kale.should_receive(:manually_update_audit) { kale.save_audit( {'action' => 'dig', 'modifications' => { 'name' => 'over ruled!' } } ) }
      kale.update_attributes :name => 'a small oak'
      kale.audited_changes.should ==  {'tastey'=>[true, nil], 'name'=>['a bunch of leafy kale', 'over ruled!']}
      kale.audits.last.action.should == 'dig'
    end
  end
end


text:
outstanding = float(raw_input('''Enter the outstanding balance on your
credit card: '''))
interestrate = float(raw_input('''Enter the annual credit card
interest rate as a decimal: '''))
minimumrate = float(raw_input('''Enter the minimum monthly payment
rate as a decimal: '''))
total = 0

for x in range(0, 12):
    x += 1
    print 'Month:', x
    minpay = minimumrate * outstanding
    print 'Minimum monthly payment: $' + str(round(minpay, 2))
    interestpaid = interestrate/12.0 * outstanding
    principalpaid = minpay - interestpaid
    print 'Principal paid: $' + str(round(principalpaid, 2))
    outstanding = outstanding - principalpaid
    print 'Remaining balance: $' + str(round(outstanding, 2))
    total = total + interestpaid + principalpaid

print 'RESULT'
print 'Total amount paid: $' + str(round(total, 2))
print 'Remaining balance: $' + str(round(outstanding, 2))