text:
package pkg.text.simpleDateFormat;

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

public class TestSimpleDateFormat2 {

    public static String toLongDateString(Date dt){
        SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
        return myFmt.format(dt);
    }

    public static String toShortDateString(Date dt){
        SimpleDateFormat myFmt=new SimpleDateFormat("yy年MM月dd日 HH时mm分");
        return myFmt.format(dt);
    }

    public static String toLongTimeString(Date dt){
        SimpleDateFormat myFmt=new SimpleDateFormat("HH mm ss SSSS");
        return myFmt.format(dt);
    }
    public static String toShortTimeString(Date dt){
        SimpleDateFormat myFmt=new SimpleDateFormat("yy/MM/dd HH:mm");
        return myFmt.format(dt);
    }

    public static void main(String[] args) {

        Date now=new Date();

        System.out.println(TestSimpleDateFormat2.toLongDateString(now));
        System.out.println(TestSimpleDateFormat2.toShortDateString(now));
        System.out.println(TestSimpleDateFormat2.toLongTimeString(now));
        System.out.println(TestSimpleDateFormat2.toShortTimeString(now));
    }

}


text:
/**
 * Contains the Honeycomb backend for HBase.
 */
package com.nearinfinity.honeycomb.hbase;

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Bjd.Browse
{
    internal class OneBrowse
    {
        public string Name { get; private set; }
        public long Size { get; private set; }
        public BrowseKind BrowseKind { get; private set; }
        public DateTime Dt { get; private set; }

        //RemoteServerでのデータ生成
        public OneBrowse(BrowseKind browseKind, string name, long size, DateTime dt)
        {
            BrowseKind = browseKind;
            Name = name;
            Size = size;
            Dt = dt;
        }

        //RemoteClientでの復元
        public OneBrowse(string str)
        {
            Name = "";
            if (str == null)
                return;
            var tmp = str.Split('\b');
            if (tmp.Length != 4)
                return;
            BrowseKind = (BrowseKind)Enum.Parse(typeof(BrowseKind), tmp[0]);
            Name = tmp[1];
            Size = long.Parse(tmp[2]);
            Dt = DateTime.Parse(tmp[3]);
        }

        //RemoteServerでの送信データ作成
        public override string ToString()
        {
            return string.Format("{0}\b{1}\b{2}\b{3}", BrowseKind, Name, Size, Dt);
        }
    }
}


text:
namespace VersionOne {
    namespace TestComplete {
        namespace ManagedWrapper {

            class LogPublisher
            {
            public:
                __declspec(dllexport) LogPublisher(void);
                virtual __declspec(dllexport) ~LogPublisher(void);

                void __declspec(dllexport) Fatal(BSTR message);

                void __declspec(dllexport) Info(BSTR message);
                void __declspec(dllexport) Info(std::wstring message);

                void __declspec(dllexport) Debug(BSTR message);
                void __declspec(dllexport) Debug(std::wstring message);
            };

        }
    }
}


text:
require_relative 'lambda_block'

class NoSuchElementException < RuntimeError
end

class Array
  def to_seq
    Sequence.new(self.lazy)
  end
end

module Sequences
  def empty
    Sequence.empty
  end

  def sequence(*items)
    Sequence.sequence(*items)
  end

  def drop(sequence, count)
    Sequence.drop(sequence, count)
  end

  def sort(sequence, comparator=ascending)
    Sequence.sort(sequence, comparator)
  end

  def map_concurrently(sequence, fn=nil, &block)
    Sequence.map_concurrently(sequence, block_given? ? ->(value) { block.call(value) } : fn)
  end

  def group(key, enumerator)
    Group.new(key, enumerator)
  end

  def repeat(item)
    Sequence.new(repeat_enumerator(item))
  end

  def repeat_fn(item)
    Sequence.new(repeat_fn_enumerator(item))
  end

  def enumerate(fn, start)
    Sequence.new(Enumerator.new do |y|
      current = start
      loop do
        result = current
        current = fn.(current)
        y << result
      end
    end.lazy)
  end

  private

  def pair_enumerator(left, right)
    Enumerator.new do |y|
      left.rewind
      right.rewind
      loop do
        y << pair(left.next, right.next)
      end
    end.lazy
  end
end

class Sequence
  include Comparable
  include LambdaBlock

  attr_reader :enumerator

  def self.map_concurrently(sequence, fn=nil, &block)
    call_concurrently(sequence.map(defer_return(block_given? ? ->(value) { block.call(value) } : fn)))
  end

  def self.sort(sequence, comparator=ascending)
    Sequence.new(sequence.enumerator.sort { |a, b| comparator.(a, b) }.lazy)
  end

  def self.drop(sequence, count)
    Sequence.new(sequence.enumerator.drop(count))
  end

  def self.repeat(item)
    Sequence.new(repeat_enumerator(item))
  end

  def self.repeat_fn(item)
    Sequence.new(repeat_fn_enumerator(item))
  end

  def self.take(sequence, count)
    Sequence.new(sequence.enumerator.take(count))
  end

  def self.zip(left, right)
    left.zip(right)
  end

  def self.sequence(*items)
    if items.first.nil?
      empty
    else
      Sequence.new(items.lazy)
    end
  end

  def self.empty
    EMPTY
  end

  def initialize(enumerator)
    raise "Sequence only accepts Enumerator::Lazy, not #{enumerator.class}" unless (enumerator.class == Enumerator::Lazy)
    @enumerator = enumerator
  end

  def is_empty?
    @enumerator.rewind
    begin
      @enumerator.peek
      false
    rescue
      true
    end
  end

  def size
    @enumerator.count
  end

  def head
    @enumerator.first
  end

  alias first head

  def second
    tail.head
  end

  def head_option
    option(head)
  end

  def last
    reverse.head
  end

  def last_option
    reverse.head_option
  end

  def reverse
    Sequence.new(reverse_enumerator(@enumerator))
  end

  def tail
    unless has_next(@enumerator)
      raise NoSuchElementException.new
    end
    Sequence.new(@enumerator.drop(1))
  end

  def init
    reverse.tail.reverse
  end

  def map(fn=nil, &block)
    assert_funcs(fn, block_given?)
    Sequence.new(@enumerator.map { |value|
      block_given? ? block.call(value) : fn.(value)
    })
  end

  def fold(seed, fn=nil, &block)
    assert_funcs(fn, block_given?)
    @enumerator.inject(seed) { |accumulator, value|
      block_given? ? block.call(accumulator, value) : fn.(accumulator, value)
    }
  end

  alias fold_left fold

  def fold_right(seed, fn=nil, &block)
    assert_funcs(fn, block_given?)
    reverse_enumerator(@enumerator).inject(seed) { |accumulator, value|
      block_given? ? block.call(value, accumulator) : fn.(value, accumulator)
    }
  end

  def reduce(fn=nil, &block)
    assert_funcs(fn, block_given?)
    _fn = block_given? ? ->(a, b) { block.call(a, b) } : fn
    accumulator = seed(@enumerator, fn)
    while has_next(@enumerator)
      accumulator = _fn.(accumulator, @enumerator.next)
    end
    accumulator
  end

  alias reduce_left reduce

  def reduce_right(fn=nil, &block)
    assert_funcs(fn, block_given?)
    _fn = block_given? ? ->(a, b) { block.call(a, b) } : fn
    reversed = reverse_enumerator(@enumerator)
    accumulator = seed(reversed, fn)
    while has_next(reversed)
      accumulator = _fn.(reversed.next, accumulator)
    end
    accumulator
  end

  def find(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    @enumerator.rewind
    while has_next(@enumerator)
      item = @enumerator.next
      result = block_given? ? block_pred.call(item) : fn_pred.(item)
      if result
        return(some(item))
      end
    end
    none
  end

  def zip(other)
    Sequence.new(pair_enumerator(@enumerator, other.enumerator))
  end

  def zip_with_index
    Sequence.zip(range_from(0), self)
  end

  def find_index_of(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    zip_with_index.find(->(pair) { block_given? ? block_pred.call(pair.second) : fn_pred.(pair.second) }).map(->(pair) { pair.first })
  end

  def take(count)
    Sequence.take(self, count)
  end

  def take_while(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    Sequence.new(@enumerator.take_while { |value| block_given? ? block_pred.call(value) : fn_pred.(value) })
  end

  def drop(count)
    Sequence.drop(self, count)
  end

  def drop_while(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    Sequence.new(@enumerator.drop_while { |value| block_given? ? block_pred.call(value) : fn_pred.(value) })
  end

  def flat_map(fn=nil, &block)
    assert_funcs(fn, block_given?)
    map(block_given? ? ->(value) { block.call(value) } : fn).flatten
  end

  def flatten
    Sequence.new(flatten_enumerator(enumerator))
  end

  def sort_by(comparator)
    Sequence.sort(self, comparator)
  end

  def contains?(value)
    @enumerator.member?(value)
  end

  def exists?(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    @enumerator.any? { |value| block_given? ? block_pred.call(value) : fn_pred.(value) }
  end

  def for_all?(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    @enumerator.all? { |value| block_given? ? block_pred.call(value) : fn_pred.(value) }
  end

  def filter(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    Sequence.new(@enumerator.select { |value| block_given? ? block_pred.call(value) : fn_pred.(value) })
  end

  def reject(fn_pred=nil, &block_pred)
    assert_funcs(fn_pred, block_given?)
    filter(is_not(block_given? ? ->(value) { block_pred.call(value) } : fn_pred))
  end

  def group_by(fn=nil, &block)
    assert_funcs(fn, block_given?)
    groups = @enumerator.group_by { |value| block_given? ? block.call(value) : fn.(value) }
    Sequence.new(groups.to_a.map { |group| Group.new(group[0], group[1].lazy) }.lazy)
  end

  def each(fn=nil, &block)
    assert_funcs(fn, block_given?)
    @enumerator.each { |value| block_given? ? block.call(value) : fn.(value) }
  end

  def map_concurrently(fn=nil, &block)
    assert_funcs(fn, block_given?)
    Sequence.map_concurrently(self, block_given? ? ->(value) { block.call(value) } : fn)
  end

  def realise
    Sequence.new(@enumerator.to_a.lazy)
  end

  def join(other)
    Sequence.new(Enumerator.new do |y|
      @enumerator.each { |value| y << value }
      other.enumerator.each { |value| y << value }
    end.lazy)
  end

  def cycle
    Sequence.new(cycle_enumerator(@enumerator))
  end

  def to_a
    @enumerator.to_a
  end

  def <=>(other)
    @enumerator.entries <=> other.enumerator.entries
  end

  def inspect
    to_s
  end

  def to_s
    sample = take(100).to_a.to_seq
    "[#{sample.is_empty? ? '' : sample.reduce(join_with_sep(','))}]"
  end

  private
  def seed(enumerator, fn)
    enumerator.rewind
    !fn.nil? && fn.respond_to?(:identity) ? fn.identity : enumerator.next
  end
end

class Group < Sequence
  include Comparable
  attr_reader :key

  def initialize(key, enumerator)
    super(enumerator)
    @key = key
  end

  def <=>(other)
    (@key <=> other.key) <=> (enumerator.entries<=>(other.enumerator.entries))
  end
end

EMPTY=Sequence.new([].lazy)


text:
        <title>startTime attribute test</title>

        <video controls> </video>

Test the, so far unused, 'startTime' attribute.


text:
layout: post
title: "Daily Digest #70"
type: digest
tags:
    - daily
    - development
description: ""
publish: false
---


text:
public class Song {
	/*
	 * CS312 Assignment 1.
	 * On my honor, Jacob Tobias, this programming assignment is my own work.
	 * Section Number: 50585
	 *
	 * A program to print out the lyrics to the
	 * children's song, "There was an old woman".
	 *
	 *  Name: Jacob Tobias
	 *  email address: tobiasslugger@gmail.com
	 *  UTEID: jwt943
	 *  Section 5 digit ID: 50585
	 *  Grader name: Professor Roman Hennandex
	 *  Number of slip days used on this assignment: 0
	 */
	public static void main(String[] args) {
		verseOne();
		verseTwo();
		verseThree();
		verseFour();
		verseFive();
		verseSix();
		verseSeven();
		verseEight();

	}
	/*
	 * Each method that starts out with "inner" contains the third sentence in each verse
	 * and then each method after the first has the phrase that the previous method had in it, with
	 * the repeating end to the song as well.
	 */
	public static void end(){
		System.out.println("I don't know why she swallowed that fly,");
		System.out.println("Perhaps she'll die.");
		System.out.println();
	}
	public static void inner2(){
		System.out.println("She swallowed the spider to catch the fly,");
		end();
	}
	public static void inner3(){
		System.out.println("She swallowed the bird to catch the spider,");
		inner2();
	}
	public static void inner4(){
		System.out.println("She swallowed the cat to catch the bird,");
		inner3();
	}
	public static void inner5(){
		System.out.println("She swallowed the dog to catch the cat,");
		inner4();
	}
	public static void inner6(){
		System.out.println("She swallowed the goat to catch the dog,");
		inner5();
	}
	public static void inner7(){
		System.out.println("She swallowed the cow to catch the goat,");
		inner6();
	}

	public static void verseOne(){
		System.out.println("There was an old woman who swallowed a fly.");
		end();
	}
	public static void verseTwo(){
		System.out.println("There was an old woman who swallowed a spider,");
		System.out.println("That wriggled and iggled and jiggled inside her.");
		inner2();
	}
	public static void verseThree(){
		System.out.println("There was an old woman who swallowed a bird,");
		System.out.println("How absurd to swallow a bird.");
		inner3();
	}
	public static void verseFour(){
		System.out.println("There was an old woman who swallowed a cat,");
		System.out.println("Imagine that to swallow a cat.");
		inner4();
	}
	public static void verseFive(){
		System.out.println("There was an old woman who swallowed a dog,");
		System.out.println("What a hog to swallow a dog.");
		inner5();
	}
	public static void verseSix(){
		System.out.println("There was an old woman who swallowed a goat,");
		System.out.println("She just opened her throat to swallow a goat.");
		inner6();
	}
	public static void verseSeven(){
		System.out.println("There was an old woman who swallowed a cow,");
		System.out.println("I don't know how she swallowed a cow.");
		inner7();
	}
	public static void verseEight(){
		System.out.println("There was an old woman who swallowed a horse,");
		System.out.println("She died of course.");
		System.out.println();
	}
}


text:
package com.orasi.utils.dataHelpers.personFactory;

import static com.orasi.utils.TestReporter.logTrace;

import java.util.ArrayList;

public class Party {

    private ArrayList<Person> party = new ArrayList<Person>();

    public Party(int numberOfPeople) {
        logTrace("Entering Party#init with number of People");
        logTrace("Creating party with [" + numberOfPeople + "] party");

        for (int x = 0; x < numberOfPeople; x++) {
            logTrace("Generating Person [" + (x + 1) + "]");
            addPerson(new Person());

            logTrace("Setting Person [" + (x + 1) + "] Address, Phone and Email to primary Person");
            party.get(x).getAllAddresses().get(0).setPrimary(true);
            party.get(x).getAllAddresses().get(0).setStreetName(party.get(0).primaryAddress().getStreetName());
            party.get(x).getAllAddresses().get(0).setStreetNumber(party.get(0).primaryAddress().getStreetNumber());
            party.get(x).getAllAddresses().get(0).setCity(party.get(0).primaryAddress().getCity());
            party.get(x).getAllAddresses().get(0).setState(party.get(0).primaryAddress().getState());
            party.get(x).getAllAddresses().get(0).setStateAbbv(party.get(0).primaryAddress().getStateAbbv());
            party.get(x).getAllAddresses().get(0).setZipCode(party.get(0).primaryAddress().getZipCode());
            party.get(x).getAllAddresses().get(0).setOptIn(true);
            party.get(x).getAllPhones().get(0).setPrimary(true);
            party.get(x).getAllEmails().get(0).setPrimary(true);
            logTrace("\n" + party.get(x).toString().replace("<br/>", "\n"));
        }

        logTrace("Set first Person as Primary Person");
        party.get(0).setPrimary(true);
        logTrace("Ensure first Person is older than 18");
        if (Integer.parseInt(party.get(0).getAge()) <= 18) {
            party.get(0).setAge("45");
            party.get(0).setBirthDate("1970-01-14");
        }
        logTrace("Entering Party#init with number of Persons");
    }

    /**
     * Associate a new Person to the person using preset data
     *
     * @author Justin Phlegar
     * @version 11/28/2015 Justin Phlegar - original
     */
    public void addPerson(Person person) {
        party.add(person);
    }

    /**
     * Return the person marked as Primary
     *
     * @author Justin Phlegar
     * @version 11/28/2015 Justin Phlegar - original
     * @return the Party primary Person
     */
    public Person primaryPerson() {
        Person primaryPerson = null;

        for (Person person : party) {
            if (person.isPrimary()) {
                primaryPerson = person;
            }
        }

        return primaryPerson;
    }

    /**
     * Return all People associated to the Party
     *
     * @author Justin Phlegar
     * @version 11/28/2015 Justin Phlegar - original
     * @return all People as an ArrayList
     */
    public ArrayList<Person> getAllPersons() {
        return party;
    }

    /**
     * Return the number of Children currently in Party
     *
     * @author Justin Phlegar
     * @version 11/28/2015 Justin Phlegar - original
     * @return the number of children in Party
     */
    public int numberOfChildren() {
        int numberOfChildren = 0;
        for (Person person : party) {
            if (person.isChild() && Integer.valueOf(person.getAge()) > 2
                    && Integer.valueOf(person.getAge()) < 18) {
                numberOfChildren++;
            }
        }
        return numberOfChildren;
    }

    public int numberOfInfants() {
        int numberOfInfant = 0;
        for (Person person : party) {
            if (person.isChild() && Integer.valueOf(person.getAge()) <= 2) {
                numberOfInfant++;
            }
        }
        return numberOfInfant;
    }

    /**
     * Return the number of adults currently in Party
     *
     * @author Justin Phlegar
     * @version 11/28/2015 Justin Phlegar - original
     * @return the number of adults in Party
     */
    public int numberOfAdults() {
        int numberOfAdults = 0;
        for (Person person : party) {
            if (!person.isChild()) {
                numberOfAdults++;
            }
        }
        return numberOfAdults;
    }

}


text:
module.exports = function(sequelize, DataTypes) {
    var TestRuns = sequelize.define('TestRuns', {
        backgroundSpeed: DataTypes.STRING,
        sameAsForeground: DataTypes.BOOLEAN,
        noticedObject: DataTypes.BOOLEAN,
        ipAddress: {type: DataTypes.STRING, unique: true}
    }, {});

    return TestRuns;
};


text:
/* global QUnit, $, testData_ */
QUnit.module('$.fn.cascadeSelect')

QUnit.test('namespace', function (assert) {
  assert.ok(typeof $.fn.cascadeSelect === 'function', 'Passed!')
})

QUnit.test('constructor', function (assert) {
  var $ele = $('

')
  $ele.appendTo('#qunit-fixture')

  var result

  try {
    $ele.cascadeSelect()
    result = 1
  } catch (e) {
    result = 2
  }

  assert.equal(result, 2, 'should fire a exception without options')
})

QUnit.test('init plugin with normal data', function (assert) {
  var done = assert.async()

  testData_.initPluginWithNormalData(function ($list1, $list2, $list3) {
    var testSize = function ($list, no) {
      assert.equal($list.size(), 1, 'List ' + no + ' here!')
    }

    var testDefaultVal = function ($list) {
      var firstValue = $list.find('option').attr('value')
      var otherValues = $list.find('option').filter(':not(:eq(0))').map(function (i, ele) { return $(ele).attr('value') }).get()
      var joinedId = testData_.joinIds.apply(null, otherValues)

      assert.equal($list.val(), firstValue, 'default value is first item')
      assert.equal(firstValue, joinedId, 'the first value is all other joined!')
    }

    testSize($list1, 1)
    testSize($list2, 1)
    testSize($list3, 1)

    testDefaultVal($list1)
    testDefaultVal($list2)
    testDefaultVal($list3)

    done()
  })
})

QUnit.test('function with normal data', function (assert) {
  var done = assert.async()

  var setAndGet = function ($list, dataMap, parentValue) {
    var list = testData_.getListByParent(parentValue, dataMap)
    var ids = testData_.getIds(list)
    var firstValue = ids[0]
    var lastValue = ids[ids.length - 1]
    $list.val(firstValue)

    return {
      firstValue,
      lastValue,
      ids
    }
  }

  testData_.initPluginWithNormalData(function ($list1, $list2, $list3) {
    var result1 = setAndGet($list1, testData_.list1)
    var result2 = setAndGet($list2, testData_.list2, result1.firstValue)
    var result3 = setAndGet($list3, testData_.list3, result2.firstValue)

    assert.equal($list1.val(), result1.firstValue, 'match the list 1 selected value!')
    assert.equal($list2.val(), result2.firstValue, 'match the list 2 selected value!')
    assert.equal($list3.val(), result3.firstValue, 'match the list 3 selected value!')

    assert.equal($list2.find('option').size(), result2.ids.length + 1, 'should has some items, including the check-all item!')
    assert.equal($list3.find('option').size(), result3.ids.length + 1, 'should has some items, including the check-all item!')

    $list2.val(result2.lastValue)

    var ids = testData_.getIds(testData_.getListByParent(result2.lastValue, testData_.list3))
    assert.equal($list3.val(), testData_.joinIds(ids), 'Change the parent will reset the child list with the first item (default) !')

    done()
  })
})


text:
package org.springframework.boot.logging.logback;

import java.io.File;
import java.util.EnumSet;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogManager;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.ILoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
import org.slf4j.impl.StaticLoggerBinder;

import org.springframework.boot.logging.AbstractLoggingSystemTests;
import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerConfiguration;
import org.springframework.boot.logging.LoggingInitializationContext;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.LoggingSystemProperties;
import org.springframework.boot.testsupport.assertj.Matched;
import org.springframework.boot.testsupport.rule.OutputCapture;
import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.StringUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.contentOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link LogbackLoggingSystem}.
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Ben Hale
 * @author Madhura Bhave
 * @author Vedran Pavic
 * @author Robert Thornton
 */
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions("log4j-*.jar")
public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests {

	@Rule
	public OutputCapture output = new OutputCapture();

	private final LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem(
			getClass().getClassLoader());

	private Logger logger;

	private LoggingInitializationContext initializationContext;

	@Before
	public void setup() {
		this.loggingSystem.cleanUp();
		this.logger = ((LoggerContext) StaticLoggerBinder.getSingleton()
				.getLoggerFactory()).getLogger(getClass());
		MockEnvironment environment = new MockEnvironment();
		this.initializationContext = new LoggingInitializationContext(environment);
	}

	@Override
	@After
	public void clear() {
		super.clear();
		this.loggingSystem.cleanUp();
		((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()).stop();
	}

	@Test
	public void noFile() {
		this.loggingSystem.beforeInitialize();
		this.logger.info("Hidden");
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.logger.info("Hello world");
		String output = this.output.toString().trim();
		assertThat(output).contains("Hello world").doesNotContain("Hidden");
		assertThat(getLineWithText(output, "Hello world")).contains("INFO");
		assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse();
	}

	@Test
	public void withFile() {
		this.loggingSystem.beforeInitialize();
		this.logger.info("Hidden");
		this.loggingSystem.initialize(this.initializationContext, null,
				getLogFile(null, tmpDir()));
		this.logger.info("Hello world");
		String output = this.output.toString().trim();
		File file = new File(tmpDir() + "/spring.log");
		assertThat(output).contains("Hello world").doesNotContain("Hidden");
		assertThat(getLineWithText(output, "Hello world")).contains("INFO");
		assertThat(file.exists()).isTrue();
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize")
				.toString()).isEqualTo("10 MB");
		assertThat(getRollingPolicy().getMaxHistory())
				.isEqualTo(CoreConstants.UNBOUND_HISTORY);
	}

	@Test
	public void defaultConfigConfiguresAConsoleAppender() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		assertThat(getConsoleAppender()).isNotNull();
	}

	@Test
	public void testNonDefaultConfigLocation() {
		int existingOutputLength = this.output.toString().length();
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext,
				"classpath:logback-nondefault.xml",
				getLogFile(tmpDir() + "/tmp.log", null));
		this.logger.info("Hello world");
		String output = this.output.toString().trim();
		assertThat(output.substring(existingOutputLength)).doesNotContain("DEBUG");
		assertThat(output).contains("Hello world").contains(tmpDir() + "/tmp.log");
		assertThat(output).endsWith("BOOTBOOT");
		assertThat(new File(tmpDir() + "/tmp.log").exists()).isFalse();
	}

	@Test
	public void testLogbackSpecificSystemProperty() {
		System.setProperty("logback.configurationFile", "/foo/my-file.xml");
		try {
			this.loggingSystem.beforeInitialize();
			this.loggingSystem.initialize(this.initializationContext, null, null);
			String output = this.output.toString().trim();
			assertThat(output).contains("Ignoring 'logback.configurationFile' "
					+ "system property. Please use 'logging.config' instead.");
		}
		finally {
			System.clearProperty("logback.configurationFile");
		}
	}

	@Test
	public void testNonexistentConfigLocation() {
		this.loggingSystem.beforeInitialize();
		assertThatIllegalStateException().isThrownBy(() -> this.loggingSystem.initialize(
				this.initializationContext, "classpath:logback-nonexistent.xml", null));
	}

	@Test
	public void getSupportedLevels() {
		assertThat(this.loggingSystem.getSupportedLogLevels())
				.isEqualTo(EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO,
						LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF));
	}

	@Test
	public void setLevel() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.logger.debug("Hello");
		this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG);
		this.logger.debug("Hello");
		assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello"))
				.isEqualTo(1);
	}

	@Test
	public void setLevelToNull() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.logger.debug("Hello");
		this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG);
		this.logger.debug("Hello");
		this.loggingSystem.setLogLevel("org.springframework.boot", null);
		this.logger.debug("Hello");
		assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello"))
				.isEqualTo(1);
	}

	@Test
	public void getLoggingConfigurations() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG);
		List<LoggerConfiguration> configurations = this.loggingSystem
				.getLoggerConfigurations();
		assertThat(configurations).isNotEmpty();
		assertThat(configurations.get(0).getName())
				.isEqualTo(LoggingSystem.ROOT_LOGGER_NAME);
	}

	@Test
	public void getLoggingConfiguration() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG);
		LoggerConfiguration configuration = this.loggingSystem
				.getLoggerConfiguration(getClass().getName());
		assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(),
				LogLevel.DEBUG, LogLevel.DEBUG));
	}

	@Test
	public void getLoggingConfigurationForALL() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory()
				.getLogger(getClass().getName());
		logger.setLevel(Level.ALL);
		LoggerConfiguration configuration = this.loggingSystem
				.getLoggerConfiguration(getClass().getName());
		assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(),
				LogLevel.TRACE, LogLevel.TRACE));
	}

	@Test
	public void systemLevelTraceShouldReturnNativeLevelTraceNotAll() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.TRACE);
		Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory()
				.getLogger(getClass().getName());
		assertThat(logger.getLevel()).isEqualTo(Level.TRACE);
	}

	@Test
	public void loggingThatUsesJulIsCaptured() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		java.util.logging.Logger julLogger = java.util.logging.Logger
				.getLogger(getClass().getName());
		julLogger.info("Hello world");
		String output = this.output.toString().trim();
		assertThat(output).contains("Hello world");
	}

	@Test
	public void loggingLevelIsPropagatedToJul() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG);
		java.util.logging.Logger julLogger = java.util.logging.Logger
				.getLogger(getClass().getName());
		julLogger.fine("Hello debug world");
		String output = this.output.toString().trim();
		assertThat(output).contains("Hello debug world");
	}

	@Test
	public void bridgeHandlerLifecycle() {
		assertThat(bridgeHandlerInstalled()).isFalse();
		this.loggingSystem.beforeInitialize();
		assertThat(bridgeHandlerInstalled()).isTrue();
		this.loggingSystem.cleanUp();
		assertThat(bridgeHandlerInstalled()).isFalse();
	}

	@Test
	public void standardConfigLocations() {
		String[] locations = this.loggingSystem.getStandardConfigLocations();
		assertThat(locations).containsExactly("logback-test.groovy", "logback-test.xml",
				"logback.groovy", "logback.xml");
	}

	@Test
	public void springConfigLocations() {
		String[] locations = getSpringConfigLocations(this.loggingSystem);
		assertThat(locations).containsExactly("logback-test-spring.groovy",
				"logback-test-spring.xml", "logback-spring.groovy", "logback-spring.xml");
	}

	private boolean bridgeHandlerInstalled() {
		java.util.logging.Logger rootLogger = LogManager.getLogManager().getLogger("");
		Handler[] handlers = rootLogger.getHandlers();
		for (Handler handler : handlers) {
			if (handler instanceof SLF4JBridgeHandler) {
				return true;
			}
		}
		return false;
	}

	@Test
	public void testConsolePatternProperty() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.pattern.console", "%logger %msg");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		this.loggingSystem.initialize(loggingInitializationContext, null, null);
		this.logger.info("Hello world");
		String output = this.output.toString().trim();
		assertThat(getLineWithText(output, "Hello world")).doesNotContain("INFO");
	}

	@Test
	public void testLevelPatternProperty() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.pattern.level", "X%clr(%p)X");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		this.loggingSystem.initialize(loggingInitializationContext, null, null);
		this.logger.info("Hello world");
		String output = this.output.toString().trim();
		assertThat(getLineWithText(output, "Hello world")).contains("XINFOX");
	}

	@Test
	public void testFilePatternProperty() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.pattern.file", "%logger %msg");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext, null, logFile);
		this.logger.info("Hello world");
		String output = this.output.toString().trim();
		assertThat(getLineWithText(output, "Hello world")).contains("INFO");
		assertThat(getLineWithText(file, "Hello world")).doesNotContain("INFO");
	}

	@Test
	public void testCleanHistoryOnStartProperty() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.clean-history-on-start", "true");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext, null, logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(getRollingPolicy().isCleanHistoryOnStart()).isTrue();
	}

	@Test
	public void testCleanHistoryOnStartPropertyWithXmlConfiguration() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.clean-history-on-start", "true");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext,
				"classpath:logback-include-base.xml", logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(getRollingPolicy().isCleanHistoryOnStart()).isTrue();
	}

	@Test
	public void testMaxFileSizePropertyWithLogbackFileSize() {
		testMaxFileSizeProperty("100 MB", "100 MB");
	}

	@Test
	public void testMaxFileSizePropertyWithDataSize() {
		testMaxFileSizeProperty("15MB", "15 MB");
	}

	@Test
	public void testMaxFileSizePropertyWithBytesValue() {
		testMaxFileSizeProperty(String.valueOf(10 * 1024 * 1024), "10 MB");
	}

	private void testMaxFileSizeProperty(String sizeValue, String expectedFileSize) {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.max-size", sizeValue);
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext, null, logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize")
				.toString()).isEqualTo(expectedFileSize);
	}

	@Test
	public void testMaxFileSizePropertyWithXmlConfiguration() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.max-size", "100MB");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext,
				"classpath:logback-include-base.xml", logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize")
				.toString()).isEqualTo("100 MB");
	}

	@Test
	public void testMaxHistoryProperty() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.max-history", "30");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext, null, logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(getRollingPolicy().getMaxHistory()).isEqualTo(30);
	}

	@Test
	public void testMaxHistoryPropertyWithXmlConfiguration() throws Exception {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.max-history", "30");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext,
				"classpath:logback-include-base.xml", logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(getRollingPolicy().getMaxHistory()).isEqualTo(30);
	}

	@Test
	public void testTotalSizeCapPropertyWithLogbackFileSize() {
		testTotalSizeCapProperty("101 MB", "101 MB");
	}

	@Test
	public void testTotalSizeCapPropertyWithDataSize() {
		testTotalSizeCapProperty("10MB", "10 MB");
	}

	@Test
	public void testTotalSizeCapPropertyWithBytesValue() {
		testTotalSizeCapProperty(String.valueOf(10 * 1024 * 1024), "10 MB");
	}

	private void testTotalSizeCapProperty(String sizeValue, String expectedFileSize) {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.total-size-cap", sizeValue);
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext, null, logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "totalSizeCap")
				.toString()).isEqualTo(expectedFileSize);
	}

	@Test
	public void testTotalSizeCapPropertyWithXmlConfiguration() {
		String expectedSize = "101 MB";
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.file.total-size-cap", expectedSize);
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		File file = new File(tmpDir(), "logback-test.log");
		LogFile logFile = getLogFile(file.getPath(), null);
		this.loggingSystem.initialize(loggingInitializationContext,
				"classpath:logback-include-base.xml", logFile);
		this.logger.info("Hello world");
		assertThat(getLineWithText(file, "Hello world")).contains("INFO");
		assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "totalSizeCap")
				.toString()).isEqualTo(expectedSize);
	}

	@Test
	public void exceptionsIncludeClassPackaging() {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null,
				getLogFile(null, tmpDir()));
		Matcher<String> expectedOutput = containsString("[junit-");
		this.output.expect(expectedOutput);
		this.logger.warn("Expected exception", new RuntimeException("Expected"));
		String fileContents = contentOf(new File(tmpDir() + "/spring.log"));
		assertThat(fileContents).is(Matched.by(expectedOutput));
	}

	@Test
	public void customExceptionConversionWord() {
		System.setProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD, "%ex");
		try {
			this.loggingSystem.beforeInitialize();
			this.logger.info("Hidden");
			this.loggingSystem.initialize(this.initializationContext, null,
					getLogFile(null, tmpDir()));
			Matcher<String> expectedOutput = Matchers.allOf(
					containsString("java.lang.RuntimeException: Expected"),
					not(containsString("Wrapped by:")));
			this.output.expect(expectedOutput);
			this.logger.warn("Expected exception",
					new RuntimeException("Expected", new RuntimeException("Cause")));
			String fileContents = contentOf(new File(tmpDir() + "/spring.log"));
			assertThat(fileContents).is(Matched.by(expectedOutput));
		}
		finally {
			System.clearProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD);
		}
	}

	@Test
	public void initializeShouldSetSystemProperty() {
		// gh-5491
		this.loggingSystem.beforeInitialize();
		this.logger.info("Hidden");
		LogFile logFile = getLogFile(tmpDir() + "/example.log", null, false);
		this.loggingSystem.initialize(this.initializationContext,
				"classpath:logback-nondefault.xml", logFile);
		assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE))
				.endsWith("example.log");
	}

	@Test
	public void initializationIsOnlyPerformedOnceUntilCleanedUp() {
		LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton()
				.getLoggerFactory();
		LoggerContextListener listener = mock(LoggerContextListener.class);
		loggerContext.addListener(listener);
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		verify(listener, times(1)).onReset(loggerContext);
		this.loggingSystem.cleanUp();
		loggerContext.addListener(listener);
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(this.initializationContext, null, null);
		verify(listener, times(2)).onReset(loggerContext);
	}

	@Test
	public void testDateformatPatternProperty() {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("logging.pattern.dateformat",
				"yyyy-MM-dd'T'hh:mm:ss.SSSZ");
		LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(
				environment);
		this.loggingSystem.initialize(loggingInitializationContext, null, null);
		this.logger.info("Hello world");
		String output = this.output.toString().trim();
		assertThat(getLineWithText(output, "Hello world"))
				.containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}");
	}

	private static Logger getRootLogger() {
		ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory();
		LoggerContext context = (LoggerContext) factory;
		return context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
	}

	private static ConsoleAppender<?> getConsoleAppender() {
		return (ConsoleAppender<?>) getRootLogger().getAppender("CONSOLE");
	}

	private static RollingFileAppender<?> getFileAppender() {
		return (RollingFileAppender<?>) getRootLogger().getAppender("FILE");
	}

	private static SizeAndTimeBasedRollingPolicy<?> getRollingPolicy() {
		return (SizeAndTimeBasedRollingPolicy<?>) getFileAppender().getRollingPolicy();
	}

	private String getLineWithText(File file, String outputSearch) {
		return getLineWithText(contentOf(file), outputSearch);
	}

	private String getLineWithText(String output, String outputSearch) {
		String[] lines = output.split("\\r?\\n");
		for (String line : lines) {
			if (line.contains(outputSearch)) {
				return line;
			}
		}
		return null;
	}

}


text:
/**
 * @author Sergey Burlak
 */

package javax.swing.plaf;

import java.awt.Component;
import java.awt.Graphics;
import java.io.Serializable;
import javax.swing.Icon;

import org.apache.harmony.x.swing.internal.nls.Messages;

public class IconUIResource implements Icon, UIResource, Serializable {
    private Icon icon;

    public IconUIResource(final Icon icon) {
        if (icon == null) {
            throw new IllegalArgumentException(Messages.getString("swing.6B")); //$NON-NLS-1$
        }
        this.icon = icon;
    }

    public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
        icon.paintIcon(c, g, x, y);
    }

    public int getIconWidth() {
        return icon.getIconWidth();
    }

    public int getIconHeight() {
        return icon.getIconHeight();
    }
}


text:
const BaseController       = require( "app/controllers/BaseController" )
const FetchNoteCommand     = require( "reponote-core/app/commands/FetchNoteCommand" )
const FetchNoteListCommand = require( "reponote-core/app/commands/FetchNoteListCommand" )
const SaveNoteCommand      = require( "reponote-core/app/commands/SaveNoteCommand" )

class RepoController extends BaseController {

  constructor( injectables ) {
    super() // Don't forget this guy
    this.commandDispatcher = injectables.commandDispatcher
    this.workingDirManager = injectables.workingDirManager
    this.request           = injectables.request
    this.response          = injectables.response
  }

  //
  // Actions
  //

  // TODO: handle non-validation app errors (auth, etc)

  getIndex() {
    this.respond( () => {

      let command = new FetchNoteListCommand( {
        repoAuthData: this.extractRepoAuthData(),
        repoType:     this.extractParam( "repoType" ),
      } )

      return this.processCommand( command )
    } )
  }

  getPath() {
    this.respond( () => {

      let command = new FetchNoteCommand( {
        repoAuthData: this.extractRepoAuthData(),
        repoType:     this.extractParam( "repoType" ),
        filePath:     this.extractFilePath(),
      } )

      return this.processCommand( command )
    } )
  }

  postPath() {
    this.respond( () => {

      let command = new SaveNoteCommand( {
        repoAuthData: this.extractRepoAuthData(),
        repoType:     this.extractParam( "repoType" ),
        filePath:     this.extractFilePath(),
        baseRevision: this.extractPayload( "baseRevision" ),
        newContent:   this.extractPayload( "newContent" ),
      } )

      return this.processCommand( command )
    } )
  }

  //
  // Private
  //

  processCommand( command ) {
    command.validate()
    // TODO: weird...
    command.assignWorkingDir( this.workingDirManager.pathFor( command.repoAuthData.hash ) )
    return this.commandDispatcher.process( command )
  }

}

module.exports = RepoController


text:
package com.lru.memory.disk.cache;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map.Entry;

/**
 *
 * @author sathayeg
 * @param <K>
 * @param <V>
 */
public class LRUCache<K extends String, V> extends LinkedHashMap<K, V> {

    private static final long serialVersionUID = 1L;
    private static final float loadfactor = 0.75f;
    private final int cachesize;
    private final DirLocate dirLocate;

    public LRUCache(int cachesize, DirLocate dirLocate) {
        super((int) Math.ceil(cachesize / loadfactor), loadfactor, true);
        this.cachesize = cachesize;
        this.dirLocate = dirLocate;
    }

    @Override
    protected boolean removeEldestEntry(Entry<K, V> eldest) {
        if(this.size() > this.cachesize){
            if(this.dirLocate.isDiskPersistent()) deleteFromFilesystem(eldest);
            return true;
        }
        return false;
    }

    private void deleteFromFilesystem(Entry<K, V> eldest){
        try{
            File f = new File(this.dirLocate.getPathToFile(eldest.getKey()));
            if(f.exists() && (! f.isDirectory())){
                f.delete();
            }
        }catch(Exception e){}
    }
}


text:
package grafana

import (
	"regexp"
	"strings"

	"encoding/json"

	cmodel "github.com/Cepave/open-falcon-backend/common/model"
	"github.com/Cepave/open-falcon-backend/modules/query/gin_http/computeFunc"
	"github.com/Cepave/open-falcon-backend/modules/query/gin_http/openFalcon"
	"github.com/Cepave/open-falcon-backend/modules/query/model"
	"github.com/Jeffail/gabs"
	"github.com/emirpasic/gods/sets/hashset"
	"github.com/gin-gonic/gin"
	"github.com/robertkrimen/otto"
	_ "github.com/robertkrimen/otto/underscore"
	log "github.com/sirupsen/logrus"
)

type GrafanaResp struct {
	Expandable bool   `json:"expandable"`
	Text       string `json:"text"`
}

func ResultGen(alist []string) (result []GrafanaResp) {
	result = []GrafanaResp{}
	for _, enp := range alist {
		result = append(result, GrafanaResp{true, enp})
	}
	return
}

func parseTager(query string) (endpoints []string, counter string, ldfunction string) {
	log.Debugf("got query string: %s ", query)
	parseRgex := "^([^#]+)#(.+)"
	if strings.Contains(query, "#{") {
		parseRgex = "^([^#]+)#(.+)#({.+)"
	}
	r := regexp.MustCompile(parseRgex)
	matched := r.FindStringSubmatch(query)
	endpointstr := matched[1]
	counter = matched[2]
	ldfunction = "null"
	if len(matched) > 3 {
		ldfunction = matched[3]
	}
	repx := regexp.MustCompile("(^{|}$)")
	endpointstr = repx.ReplaceAllString(endpointstr, "")
	endpoints = strings.Split(endpointstr, ",")
	log.Debugf("counter: %s, endpoints: %v, ldfunction: %v", counter, endpoints, ldfunction)
	return
}

func GrafanaMain(c *gin.Context) {
	query := c.DefaultQuery("query", ".+")
	log.Debugf("got query string: %s, find keyword? %v", query, strings.Contains(query, "#"))
	if strings.Contains(query, "#") {
		endpoints, counter, _ := parseTager(query)
		endpid := model.EndpointIdQuery(endpoints)
		if len(endpid) == 0 {
			c.JSON(300, gin.H{"error": "can not find any endpoint id, please check your database."})
		}
		catchAll := false
		if strings.Contains(counter, "%") {
			catchAll = true
		}
		counter = strings.Replace(counter, ".*", "%", 1)
		counter = strings.Replace(counter, "#", ".", -1)
		counters := model.FindMatchedCounters(endpid, counter)
		result := []GrafanaResp{}
		perfix := strings.Replace(counter, "%", "", 1)
		tset := hashset.New()
		if perfix == "" {
			for _, c := range counters {
				keys := strings.Split(c, ".")
				if !tset.Contains(keys[0]) {
					expandable := true
					if len(keys) == 0 {
						expandable = false
					}
					result = append(result, GrafanaResp{
						expandable,
						keys[0],
					})
					tset.Add(keys[0])
				}
			}
		} else if catchAll {
			result = []GrafanaResp{{false, "renderAll"}}
		} else {
			for _, c := range counters {
				skey := strings.Replace(c, perfix, "", 1)
				if skey == "" {
					result = append(result, GrafanaResp{false, c})
				} else {
					keys := strings.Split(skey, ".")
					if !tset.Contains(keys[0]) {
						expandable := true
						if len(keys) == 0 {
							expandable = false
						}
						result = append(result, GrafanaResp{expandable, keys[0]})
						tset.Add(keys[0])
					}
				}
			}
		}
		c.JSON(200, result)
		return
	}
	endpoints := model.EndpointQuery(query)
	var resp []GrafanaResp
	resp = ResultGen(endpoints)
	c.JSON(200, resp)
	return
}

//{"function":"sumAll","aliasName":"sumAll"}
func parseFunc(funjs string) (string, map[string]string) {
	parsedjson, err := gabs.ParseJSON([]byte(funjs))
	if err != nil {
		log.Errorf("during parse UDF got error with -> %s", err.Error())
	}
	funName := parsedjson.Search("function").Data().(string)
	c := computeFunc.GetFuncSetup(funName)
	gotKey := map[string]string{}
	for _, pa := range c.Params {
		pramArr := strings.Split(pa, ":")
		pname := pramArr[0]
		// ptype := pramArr[1]
		if parsedjson.Exists(pname) {
			gotKey[pname] = parsedjson.Search(pname).Data().(string)
		}
	}
	log.Debugf("got http map: %v, funName: %s", gotKey, funName)
	return funName, gotKey
}

type GrafanaPostPrams struct {
	Format        string   `form:"format" json:"format"`
	From          int64    `form:"from" json:"from"`
	MaxDataPoints int      `form:"maxDataPoints" json:"maxDataPoints"`
	Targets       []string `form:"targets" json:"targets"`
	Until         int64    `form:"until" json:"until"`
}

func GetQueryTargets(c *gin.Context) {
	// x := []string{"target", "from", "until", "format", "maxDataPoints", "ldfunction"}
	// for _, s := range x {
	// 	log.Debugf("params: %v", c.DefaultPostForm(s, "null"))
	// }
	var params GrafanaPostPrams
	err := c.Bind(&params)
	if err != nil {
		log.Error(err.Error())
	}
	mtarget := params.Targets
	var resResp []*cmodel.GraphQueryResponse
	for _, target := range mtarget {
		endpoints, counter, ldfunction := parseTager(target)
		endpid := model.EndpointIdQuery(endpoints)
		log.Debugf("got endpoints : %d itmes", len(endpid))
		counter = strings.Replace(counter, ".*", "%", 1)
		counter = strings.Replace(counter, "#", ".", -1)
		counters := model.FindMatchedCounters(endpid, counter)
		startTs := params.From
		endTs := params.Until
		result := []*cmodel.GraphQueryResponse{}
		log.Debugf("got counter : %d itmes", len(counters))
		for _, c := range counters {
			rrds := openFalcon.QueryOnce(startTs, endTs, "AVERAGE", 60, c, endpoints)
			if len(rrds) != 0 {
				for _, s := range rrds {
					result = append(result, s)
				}
			}
		}
		// ldfunction := c.DefaultPostForm("ldfunction", "null")
		if ldfunction == "null" || len(result) == 0 {
			for _, rs := range result {
				resResp = append(resResp, rs)
			}
		} else {
			vm := otto.New()
			funcName, tmpparams := parseFunc(ldfunction)
			funcInstance := computeFunc.GetFuncSetup(funcName)
			err := vm.Set("input", result)
			if err != nil {
				log.Debug(err.Error)
			}
			vm = computeFunc.SetParamsToJSVM(tmpparams, funcInstance.Params, vm)
			vm.Run(funcInstance.Codes)
			output, err := vm.Get("output")
			if err != nil {
				log.Error(err.Error())
				c.JSON(400, gin.H{
					"msg": err.Error(),
				})
				return
			}
			var res []*cmodel.GraphQueryResponse
			json.Unmarshal([]byte(output.String()), &res)
			for _, rs := range res {
				resResp = append(resResp, rs)
			}
			log.Debugf("outputStr: %v", output.String())
		}
	}
	c.JSON(200, resResp)
	return
}


text:
namespace Microsoft.Azure.Management.DigitalTwins.Models
{

    /// <summary>
    /// Defines values for EndpointProvisioningState.
    /// </summary>
    public static class EndpointProvisioningState
    {
        public const string Provisioning = "Provisioning";
        public const string Deleting = "Deleting";
        public const string Updating = "Updating";
        public const string Succeeded = "Succeeded";
        public const string Failed = "Failed";
        public const string Canceled = "Canceled";
        public const string Deleted = "Deleted";
        public const string Warning = "Warning";
        public const string Suspending = "Suspending";
        public const string Restoring = "Restoring";
        public const string Moving = "Moving";
        public const string Disabled = "Disabled";
    }
}


text:
package com.afinos.skd.storage.images;

import android.util.Log;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.stream.StreamModelLoader;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StreamDownloadTask;

import java.io.IOException;
import java.io.InputStream;

/**
 * ModelLoader implementation to download images from FirebaseStorage with Glide.
 *

 * Sample Usage:
 *

 *     StorageReference ref = FirebaseStorage.getInstance().getReference().child("myimage");
 *     ImageView iv = (ImageView) findViewById(R.id.my_image_view);
 *
 *     Glide.with(this)
 *         .using(new FirebaseImageLoader())
 *         .load(ref)
 *         .into(iv);
 *

 */
public class FirebaseImageLoader implements StreamModelLoader<StorageReference> {

    private static final String TAG = "FirebaseImageLoader";

    @Override
    public DataFetcher<InputStream> getResourceFetcher(StorageReference model, int width, int height) {
        return new FirebaseStorageFetcher(model);
    }

    private class FirebaseStorageFetcher implements DataFetcher<InputStream> {

        private StorageReference mRef;
        private StreamDownloadTask mStreamTask;
        private InputStream mInputStream;

        FirebaseStorageFetcher(StorageReference ref) {
            mRef = ref;
        }

        @Override
        public InputStream loadData(Priority priority) throws Exception {
            mStreamTask = mRef.getStream();
            mInputStream = Tasks.await(mStreamTask).getStream();

            return mInputStream;
        }

        @Override
        public void cleanup() {
            // Close stream if possible
            if (mInputStream != null) {
                try {
                    mInputStream.close();
                    mInputStream = null;
                } catch (IOException e) {
                    Log.w(TAG, "Could not close stream", e);
                }
            }
        }

        @Override
        public String getId() {
            return mRef.getPath();
        }

        @Override
        public void cancel() {
            // Cancel task if possible
            if (mStreamTask != null && mStreamTask.isInProgress()) {
                mStreamTask.cancel();
            }
        }
    }
}


text:
package org.apache.hadoop.examples;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Partitioner;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.lib.NullOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 * Dummy class for testing MR framefork. Sleeps for a defined period
 * of time in mapper and reducer. Generates fake input for map / reduce
 * jobs. Note that generated number of input pairs is in the order
 * of numMappers * mapSleepTime / 100, so the job uses
 * some disk space.
 */
public class SleepJob extends Configured implements Tool,
             Mapper<IntWritable, IntWritable, IntWritable, NullWritable>,
             Reducer<IntWritable, NullWritable, NullWritable, NullWritable>,
             Partitioner<IntWritable,NullWritable> {

  private static final String SLOW_RATIO = "sleep.job.slow.ratio";
  private static final String SLOW_MAPS = "sleep.job.slow.maps";
  private static final String SLOW_REDUCES = "sleep.job.slow.reduces";
  private static final String HOSTS_FOR_LOCALITY = "sleep.job.hosts";
  private static final String HOSTS_PER_SPLIT = "sleep.job.hosts.per.split";

  private long mapSleepDuration = 100;
  private long reduceSleepDuration = 100;
  private int mapSleepCount = 1;
  private int reduceSleepCount = 1;
  private int count = 0;
  private int countersPerTask = 0;
  protected RunningJob rJob = null;

  private static Random generator = new Random();

  public int getPartition(IntWritable k, NullWritable v, int numPartitions) {
    return k.get() % numPartitions;
  }

  public static class EmptySplit implements InputSplit {
    private List<String> hosts = new ArrayList<String>();
    public EmptySplit() { }
    public EmptySplit(String host) {
      this.hosts.add(host);
    }
    public EmptySplit(String [] hosts) {
      for (String h : hosts) {
        this.hosts.add(h);
      }
    }
    // No need to write out the hosts as RawSplit handles that for us
    public void write(DataOutput out) throws IOException { }
    public void readFields(DataInput in) throws IOException { }
    public long getLength() { return 0L; }
    public String[] getLocations() {
      if (hosts.size() == 0) {
        return new String [0];
      }
      // Hadoop expects a period at the end of the hostnames
      List<String> modifiedHosts = new ArrayList<String>();
      for (String host : this.hosts) {
        modifiedHosts.add(host + ".");
      }

      return modifiedHosts.toArray(new String[0]);
    }
  }

  public static class SleepInputFormat extends Configured
      implements InputFormat<IntWritable,IntWritable> {
    public InputSplit[] getSplits(JobConf conf, int numSplits) {
      InputSplit[] ret = new InputSplit[numSplits];
      String hostsStr = conf.get(HOSTS_FOR_LOCALITY, "");
      int hostsPerSplit = conf.getInt(HOSTS_PER_SPLIT, 0);
      // If hostsStr is empty, hosts will be [""]
      String [] hosts = hostsStr.split(",");

      // Distribute the hosts randomly to the splits
      for (int i = 0; i < numSplits; ++i) {
        Set<String> hostsForSplit = new HashSet<String>();
        for (int j = 0; j < hostsPerSplit; j++) {
          int index = generator.nextInt(hosts.length);
          hostsForSplit.add(hosts[index]);
        }
        ret[i] = new EmptySplit(hostsForSplit.toArray(new String[0]));
      }
      return ret;
    }
    public RecordReader<IntWritable,IntWritable> getRecordReader(
        InputSplit ignored, JobConf conf, Reporter reporter)
        throws IOException {
      final int count = conf.getInt("sleep.job.map.sleep.count", 1);
      if (count < 0) throw new IOException("Invalid map count: " + count);
      final int redcount = conf.getInt("sleep.job.reduce.sleep.count", 1);
      if (redcount < 0)
        throw new IOException("Invalid reduce count: " + redcount);
      final int emitPerMapTask = (redcount * conf.getNumReduceTasks());
    return new RecordReader<IntWritable,IntWritable>() {
        private int records = 0;
        private int emitCount = 0;

        public boolean next(IntWritable key, IntWritable value)
            throws IOException {
          key.set(emitCount);
          int emit = emitPerMapTask / count;
          if ((emitPerMapTask) % count > records) {
            ++emit;
          }
          emitCount += emit;
          value.set(emit);
          return records++ < count;
        }
        public IntWritable createKey() { return new IntWritable(); }
        public IntWritable createValue() { return new IntWritable(); }
        public long getPos() throws IOException { return records; }
        public void close() throws IOException { }
        public float getProgress() throws IOException {
          return records / ((float)count);
        }
      };
    }
  }

  private List<String> counterNames = null;
  private List<String> getCounterNames() {
    if (counterNames != null) {
      return counterNames;
    }
    counterNames = new ArrayList<String>();
    for(int i=0; i<this.countersPerTask; i++) {
      String counterName = "C" + i;
      counterNames.add(counterName);
    }
    return counterNames;
  }

  public void map(IntWritable key, IntWritable value,
      OutputCollector<IntWritable, NullWritable> output, Reporter reporter)
      throws IOException {

    List<String> counterNames = getCounterNames();
    for (String counterName : counterNames) {
      reporter.incrCounter("Counters from Mappers", counterName, 1);
    }
    //it is expected that every map processes mapSleepCount number of records.
    try {
      reporter.setStatus("Sleeping... (" +
          (mapSleepDuration * (mapSleepCount - count)) + ") ms left");
      Thread.sleep(mapSleepDuration);
    }
    catch (InterruptedException ex) {
      throw (IOException)new IOException(
          "Interrupted while sleeping").initCause(ex);
    }
    ++count;
    // output reduceSleepCount * numReduce number of random values, so that
    // each reducer will get reduceSleepCount number of keys.
    int k = key.get();
    for (int i = 0; i < value.get(); ++i) {
      output.collect(new IntWritable(k + i), NullWritable.get());
    }
  }

  public void reduce(IntWritable key, Iterator<NullWritable> values,
      OutputCollector<NullWritable, NullWritable> output, Reporter reporter)
      throws IOException {
    List<String> counterNames = getCounterNames();
    for (String counterName : counterNames) {
      reporter.incrCounter("Counters from Reducers", counterName, 1);
    }
    try {
      reporter.setStatus("Sleeping... (" +
          (reduceSleepDuration * (reduceSleepCount - count)) + ") ms left");
        Thread.sleep(reduceSleepDuration);

    }
    catch (InterruptedException ex) {
      throw (IOException)new IOException(
          "Interrupted while sleeping").initCause(ex);
    }
    count++;
  }

  public void configure(JobConf job) {
    this.mapSleepCount =
      job.getInt("sleep.job.map.sleep.count", mapSleepCount);
    this.reduceSleepCount =
      job.getInt("sleep.job.reduce.sleep.count", reduceSleepCount);
    this.mapSleepDuration =
      job.getLong("sleep.job.map.sleep.time" , 100) / mapSleepCount;
    this.reduceSleepDuration =
      job.getLong("sleep.job.reduce.sleep.time" , 100) / reduceSleepCount;
    this.countersPerTask =
      job.getInt("sleep.job.counters.per.task", 0);
    makeSomeTasksSlower(job);
  }

  private void makeSomeTasksSlower(JobConf job) {
    int id = getTaskId(job);
    int slowRatio = job.getInt(SLOW_RATIO, 1);
    if (isMap(job)) {
      String slowMaps[] = job.getStrings(SLOW_MAPS);
      if (slowMaps != null) {
        for (String s : job.getStrings(SLOW_MAPS)) {
          if (id == Integer.parseInt(s)) {
            System.out.println("Map task:" + id + " is slowed." +
                " slowRatio:" + slowRatio);
            this.mapSleepDuration *= slowRatio;
            return;
          }
        }
      }
    } else {
      String slowReduces[] = job.getStrings(SLOW_REDUCES);
      if (slowReduces != null) {
        for (String s : job.getStrings(SLOW_REDUCES)) {
          if (id == Integer.parseInt(s)) {
            System.out.println("Reduce task:" + id + " is slowed" +
                " slowRatio:" + slowRatio);
            this.reduceSleepDuration *= slowRatio;
            return;
          }
        }
      }
    }
  }

  private boolean isMap(JobConf job) {
    String taskid = job.get("mapred.task.id");
    return taskid.split("_")[3].equals("m");
  }

  private int getTaskId(JobConf job) {
    String taskid = job.get("mapred.task.id");
    return Integer.parseInt(taskid.split("_")[4]);
  }

  public void close() throws IOException {
  }

  public static void main(String[] args) throws Exception{
    int res = ToolRunner.run(new Configuration(), new SleepJob(), args);
    System.exit(res);
  }

  public int run(int numMapper, int numReducer, long mapSleepTime,
      int mapSleepCount, long reduceSleepTime,
      int reduceSleepCount, boolean doSpeculation,
      List<String> slowMaps, List<String> slowReduces,
      int slowRatio, int countersPerTask, List<String> hosts, int hostsPerSplit,
      boolean setup, int sortMemory)
          throws IOException {

    JobConf job = setupJobConf(numMapper, numReducer, mapSleepTime,
                  mapSleepCount, reduceSleepTime, reduceSleepCount,
                  doSpeculation, slowMaps, slowReduces, slowRatio,
                  countersPerTask, hosts, hostsPerSplit, setup,
                  sortMemory);

    rJob = JobClient.runJob(job);
    return 0;
  }

  public JobConf setupJobConf(int numMapper, int numReducer,
                                long mapSleepTime, int mapSleepCount,
                                long reduceSleepTime, int reduceSleepCount) {
    final List<String> EMPTY = Collections.emptyList();
    return setupJobConf(numMapper, numReducer, mapSleepTime, mapSleepCount,

        reduceSleepTime, reduceSleepCount, false, EMPTY, EMPTY, 1, 0,
        new ArrayList<String>(), 1, false, 0);
  }

  public JobConf setupJobConf( int numMapper, int numReducer,
                                long mapSleepTime, int mapSleepCount,
                                long reduceSleepTime, int reduceSleepCount,
                                boolean doSpeculation, List<String> slowMaps,
                                List<String> slowReduces, int slowRatio,
                                int countersPerTask, List<String> hosts,
                                int hostsPerSplit, boolean setup,
                                int sortMemory) {

    return setupJobConf(SleepJob.class,
                        numMapper, numReducer,
                        mapSleepTime, mapSleepCount,
                        reduceSleepTime, reduceSleepCount,
                        doSpeculation, slowMaps,
                        slowReduces, slowRatio,
                        countersPerTask, hosts,
                        hostsPerSplit, setup, sortMemory);
  }
  @SuppressWarnings({ "deprecation", "unchecked" })
  public JobConf setupJobConf(Class classToSet,
                                int numMapper, int numReducer,
                                long mapSleepTime, int mapSleepCount,
                                long reduceSleepTime, int reduceSleepCount,
                                boolean doSpeculation, List<String> slowMaps,
                                List<String> slowReduces, int slowRatio,
                                int countersPerTask, List<String> hosts,
                                int hostsPerSplit, boolean setup,
                                int sortMemory) {

    JobConf job = new JobConf(getConf(), classToSet);
    job.setNumMapTasks(numMapper);
    job.setNumReduceTasks(numReducer);
    job.setMapperClass(classToSet);
    job.setMapOutputKeyClass(IntWritable.class);
    job.setMapOutputValueClass(NullWritable.class);
    job.setReducerClass(classToSet);
    job.setOutputFormat(NullOutputFormat.class);
    job.setJobSetupCleanupNeeded(setup);
    job.setInputFormat(SleepInputFormat.class);
    job.setPartitionerClass(SleepJob.class);
    job.setJobName("Sleep job");
    FileInputFormat.addInputPath(job, new Path("ignored"));
    job.setLong("sleep.job.map.sleep.time", mapSleepTime);
    job.setLong("sleep.job.reduce.sleep.time", reduceSleepTime);
    job.setInt("sleep.job.map.sleep.count", mapSleepCount);
    job.setInt("sleep.job.reduce.sleep.count", reduceSleepCount);
    if (sortMemory != 0) {
      job.setInt("io.sort.mb", sortMemory);
    }
    job.setSpeculativeExecution(doSpeculation);
    job.setInt(SLOW_RATIO, slowRatio);
    job.setStrings(SLOW_MAPS, slowMaps.toArray(new String[slowMaps.size()]));
    job.setStrings(SLOW_REDUCES, slowMaps.toArray(new String[slowReduces.size()]));
    job.setInt("sleep.job.counters.per.task", countersPerTask);
    job.setStrings(HOSTS_FOR_LOCALITY, hosts.toArray(new String[hosts.size()]));
    job.setInt(HOSTS_PER_SPLIT, hostsPerSplit);
    return job;
  }

  public int run(String[] args) throws Exception {

    if(args.length < 1) {
      System.err.println("SleepJob [-m numMapper] [-r numReducer]" +
          " [-mt mapSleepTime (msec)] [-rt reduceSleepTime (msec)]" +
          " [-memory sortMemory(m)]" +
          " [-recordt recordSleepTime (msec)]" +
          " [-slowmaps slowMaps (int separated by ,)]" +
          " [-slowreduces slowReduces (int separated by ,)]" +
          " [-slowratio slowRatio]" +
          " [-counters numCountersToIncPerRecordPerTask]" +
          " [-nosetup]" +
          " [-hosts hostsToRunMaps (for testing locality. host names" +
          " separated by ,)]" +
          " [-hostspersplit numHostsPerSplit (for testing locality. number" +
          " of random hosts per split " +
          " ");

      ToolRunner.printGenericCommandUsage(System.err);
      return -1;
    }

    int numMapper = 1, numReducer = 1;
    long mapSleepTime = 100, reduceSleepTime = 100, recSleepTime = 100;
    int mapSleepCount = 1, reduceSleepCount = 1;
    int hostsPerSplit = 0;
    List<String> slowMaps = Collections.emptyList();
    List<String> slowReduces = Collections.emptyList();
    int slowRatio = 10;
    boolean setup = true;
    boolean doSpeculation = false;
    List<String> hosts = new ArrayList<String>();
    int countersPerTask = 0;
    int sortMemory = 0;

    for(int i=0; i < args.length; i++ ) {
      if(args[i].equals("-m")) {
        numMapper = Integer.parseInt(args[++i]);
      }
      else if(args[i].equals("-r")) {
        numReducer = Integer.parseInt(args[++i]);
      }
      else if(args[i].equals("-mt")) {
        mapSleepTime = Long.parseLong(args[++i]);
      }
      else if(args[i].equals("-rt")) {
        reduceSleepTime = Long.parseLong(args[++i]);
      }
      else if (args[i].equals("-memory")) {
        sortMemory = Integer.parseInt(args[++i]);
      }
      else if (args[i].equals("-recordt")) {
        recSleepTime = Long.parseLong(args[++i]);
      }
      else if (args[i].equals("-slowmaps")) {
        doSpeculation = true;
        slowMaps = parseSlowTaskList(args[++i]);
      }
      else if (args[i].equals("-slowreduces")) {
        doSpeculation = true;
        slowReduces = parseSlowTaskList(args[++i]);
      }
      else if (args[i].equals("-slowratio")) {
        doSpeculation = true;
        slowRatio = Integer.parseInt(args[++i]);
      }
      else if (args[i].equals("-hosts")) {
        for (String host : args[++i].split(",")) {
          hosts.add(host);
        }
      }
      else if (args[i].equals("-speculation")) {
        doSpeculation = true;
      }
      else if (args[i].equals("-counters")) {
        // Number of counters to increment per record per task
        countersPerTask = Integer.parseInt(args[++i]);
      }
      else if (args[i].equals("-hostspersplit")) {
        hostsPerSplit = Integer.parseInt(args[++i]);
      }
      else if (args[i].equals("-nosetup")) {
        setup = false;
      }
      else {
        System.err.println("Invalid option " + args[i]);
        System.exit(-1);
      }
    }

    // sleep for *SleepTime duration in Task by recSleepTime per record
    mapSleepCount = (int)Math.ceil(mapSleepTime / ((double)recSleepTime));
    reduceSleepCount = (int)Math.ceil(reduceSleepTime / ((double)recSleepTime));

    return run(numMapper, numReducer, mapSleepTime, mapSleepCount,
        reduceSleepTime, reduceSleepCount,
        doSpeculation, slowMaps, slowReduces, slowRatio, countersPerTask,
        hosts, hostsPerSplit, setup, sortMemory);
  }

  private List<String> parseSlowTaskList(String input) {
    String tasks[] = input.split(",");
    List<String> slowTasks = new ArrayList<String>();
    for (String task : tasks) {
      int id = Integer.parseInt(task);
      slowTasks.add(id + "");
    }
    return slowTasks;
  }

  public RunningJob getRunningJob() {
    return rJob;
  }
}


text:
@implementation JYModelModel

#pragma mark ---------- Life Cycle ----------
-(instancetype)init{
    self = [super init];
    if (self) {
        [self configurationModel];
    }
    return self;
}

#pragma mark ---------- Private Methods ----------
#pragma mark 配置Model
-(void)configurationModel{}

#pragma mark ---------- Click Event ----------

#pragma mark ---------- Delegate ----------

#pragma mark ---------- Lazy Load ----------

@end


text:
package net.freecoder.restdemo.model;

// Generated 2014-5-23 12:46:24 by Hibernate Tools 3.4.0.CR1

/**
 * WlsTagMaterial generated by hbm2java
 */
public class WlsTagMaterial implements java.io.Serializable {

	private WlsTagMaterialId id;
	private String materialType;
	private String wlsWxAccountId;

	public WlsTagMaterial() {
	}

	public WlsTagMaterial(WlsTagMaterialId id, String materialType,
			String wlsWxAccountId) {
		this.id = id;
		this.materialType = materialType;
		this.wlsWxAccountId = wlsWxAccountId;
	}

	public WlsTagMaterialId getId() {
		return this.id;
	}

	public void setId(WlsTagMaterialId id) {
		this.id = id;
	}

	public String getMaterialType() {
		return this.materialType;
	}

	public void setMaterialType(String materialType) {
		this.materialType = materialType;
	}

	public String getWlsWxAccountId() {
		return this.wlsWxAccountId;
	}

	public void setWlsWxAccountId(String wlsWxAccountId) {
		this.wlsWxAccountId = wlsWxAccountId;
	}

}


text:
<?php
$userId = $_GET['user_id'];
$action = $_GET['action'];
$upload_path_portfolio_tmp = 'images/portfolio/tmp/';
$upload_path_portfolio = 'images/portfolio/';
if(isset($_POST['portfolio_pic_name']))
{
	if ($_POST['portfolio_pic_name'])
	{
		$filename_tmp = $upload_path_portfolio_tmp . $_POST['portfolio_pic_name'];
		$filename_real = $upload_path_portfolio . $_POST['portfolio_pic_name'];
		if(file_exists($filename_tmp))
		{
			copy($filename_tmp, $filename_real);
		}
	}
	exit('Your portfolio is updated !');
}

if ($action == 'edit')
{
	$title = 'Here is title';
	$description = 'Here is Description';
	$img = 'images/rentuser/portfolio/01.jpg';
}
else {
	$title = '';
	$description = '';
	$img = '';
}
?>

Portfolio Title×

		<form id="portfolio-form" class="portfolio-form" method="post" enctype="multipart/form-data" action='popup-portfolio-add-edit.php' name="photo">

Title

<input name="portfolio-title" value="<?php echo $title?>" type="text"/>

Description

<textarea name="portfolio-desc" rows="5" cols="10"><?php echo $description?></textarea>

			<input type="hidden" value="" name="portfolio_pic_name" id="portfolio_pic_name"/>

		</form>
		<form id="portfolio-form-pic" class="portfolio-form" method="post" enctype="multipart/form-data" action='popup-portfolio-add-edit.php' name="photo">

Picture

				<?php if ($img) {?>

				<?php }?>
				<input type="hidden" value="Upload" class="upload_button" name="submitbtn" />
				<input type="hidden" value="portfolio" class="upload_button" name="upload_type" />

<input type="file" name="imagefile" id="portfolio-pic"/>

		</form>

			<button type="button" id="portfolio-submit-button" class="btn btn-image-save">Submit</button>