text:
#include <sys/param.h>
#include <sys/sysproto.h>
#include <sys/resourcevar.h>
#include <sys/signalvar.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/sysent.h>
#include <sys/proc.h>
#include <sys/time.h>
#include <sys/vnode.h>
#include <vm/vm.h>
#include <vm/vm_extern.h>

struct timezone tz;

/*
 * Time of day and interval timer support.
 *
 * These routines provide the kernel entry points to get and set
 * the time-of-day and per-process interval timers.  Subroutines
 * here provide support for adding and subtracting timeval structures
 * and decrementing interval timers, optionally reloading the interval
 * timers when they expire.
 */

static int	nanosleep1 __P((struct proc *p, struct timespec *rqt,
		    struct timespec *rmt));
static int	settime __P((struct timeval *));
static void	timevalfix __P((struct timeval *));
static void	no_lease_updatetime __P((int));

static void
no_lease_updatetime(deltat)
	int deltat;
{
}

void (*lease_updatetime) __P((int))  = no_lease_updatetime;

static int
settime(tv)
	struct timeval *tv;
{
	struct timeval delta, tv1, tv2;
	static struct timeval maxtime, laststep;
	struct timespec ts;
	int s;

	s = splclock();
	microtime(&tv1);
	delta = *tv;
	timevalsub(&delta, &tv1);

	/*
	 * If the system is secure, we do not allow the time to be
	 * set to a value earlier than 1 second less than the highest
	 * time we have yet seen. The worst a miscreant can do in
	 * this circumstance is "freeze" time. He couldn't go
	 * back to the past.
	 *
	 * We similarly do not allow the clock to be stepped more
	 * than one second, nor more than once per second. This allows
	 * a miscreant to make the clock march double-time, but no worse.
	 */
	if (securelevel > 1) {
		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
			/*
			 * Update maxtime to latest time we've seen.
			 */
			if (tv1.tv_sec > maxtime.tv_sec)
				maxtime = tv1;
			tv2 = *tv;
			timevalsub(&tv2, &maxtime);
			if (tv2.tv_sec < -1) {
				tv->tv_sec = maxtime.tv_sec - 1;
				printf("Time adjustment clamped to -1 second\n");
			}
		} else {
			if (tv1.tv_sec == laststep.tv_sec) {
				splx(s);
				return (EPERM);
			}
			if (delta.tv_sec > 1) {
				tv->tv_sec = tv1.tv_sec + 1;
				printf("Time adjustment clamped to +1 second\n");
			}
			laststep = *tv;
		}
	}

	ts.tv_sec = tv->tv_sec;
	ts.tv_nsec = tv->tv_usec * 1000;
	set_timecounter(&ts);
	(void) splsoftclock();
	lease_updatetime(delta.tv_sec);
	splx(s);
	resettodr();
	return (0);
}

#ifndef _SYS_SYSPROTO_H_
struct clock_gettime_args {
	clockid_t clock_id;
	struct	timespec *tp;
};
#endif

/* ARGSUSED */
int
clock_gettime(p, uap)
	struct proc *p;
	struct clock_gettime_args *uap;
{
	struct timespec ats;

	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
		return (EINVAL);
	nanotime(&ats);
	return (copyout(&ats, SCARG(uap, tp), sizeof(ats)));
}

#ifndef _SYS_SYSPROTO_H_
struct clock_settime_args {
	clockid_t clock_id;
	const struct	timespec *tp;
};
#endif

/* ARGSUSED */
int
clock_settime(p, uap)
	struct proc *p;
	struct clock_settime_args *uap;
{
	struct timeval atv;
	struct timespec ats;
	int error;

	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
		return (error);
	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
		return (EINVAL);
	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
		return (error);
	if (ats.tv_nsec < 0 || ats.tv_nsec >= 1000000000)
		return (EINVAL);
	/* XXX Don't convert nsec->usec and back */
	TIMESPEC_TO_TIMEVAL(&atv, &ats);
	if ((error = settime(&atv)))
		return (error);
	return (0);
}

#ifndef _SYS_SYSPROTO_H_
struct clock_getres_args {
	clockid_t clock_id;
	struct	timespec *tp;
};
#endif

int
clock_getres(p, uap)
	struct proc *p;
	struct clock_getres_args *uap;
{
	struct timespec ts;
	int error;

	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
		return (EINVAL);
	error = 0;
	if (SCARG(uap, tp)) {
		ts.tv_sec = 0;
		ts.tv_nsec = 1000000000 / timecounter->tc_frequency;
		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
	}
	return (error);
}

static int nanowait;

static int
nanosleep1(p, rqt, rmt)
	struct proc *p;
	struct timespec *rqt, *rmt;
{
	struct timespec ts, ts2, ts3;
	struct timeval tv;
	int error;

	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
		return (EINVAL);
	if (rqt->tv_sec < 0 || rqt->tv_sec == 0 && rqt->tv_nsec == 0)
		return (0);
	getnanouptime(&ts);
	timespecadd(&ts, rqt);
	TIMESPEC_TO_TIMEVAL(&tv, rqt);
	for (;;) {
		error = tsleep(&nanowait, PWAIT | PCATCH, "nanslp",
		    tvtohz(&tv));
		getnanouptime(&ts2);
		if (error != EWOULDBLOCK) {
			if (error == ERESTART)
				error = EINTR;
			if (rmt != NULL) {
				timespecsub(&ts, &ts2);
				if (ts.tv_sec < 0)
					timespecclear(&ts);
				*rmt = ts;
			}
			return (error);
		}
		if (timespeccmp(&ts2, &ts, >=))
			return (0);
		ts3 = ts;
		timespecsub(&ts3, &ts2);
		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
	}
}

#ifndef _SYS_SYSPROTO_H_
struct nanosleep_args {
	struct	timespec *rqtp;
	struct	timespec *rmtp;
};
#endif

/* ARGSUSED */
int
nanosleep(p, uap)
	struct proc *p;
	struct nanosleep_args *uap;
{
	struct timespec rmt, rqt;
	int error, error2;

	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(rqt));
	if (error)
		return (error);
	if (SCARG(uap, rmtp))
		if (!useracc((caddr_t)SCARG(uap, rmtp), sizeof(rmt), B_WRITE))
			return (EFAULT);
	error = nanosleep1(p, &rqt, &rmt);
	if (error && SCARG(uap, rmtp)) {
		error2 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
		if (error2)	/* XXX shouldn't happen, did useracc() above */
			return (error2);
	}
	return (error);
}

#ifndef _SYS_SYSPROTO_H_
struct gettimeofday_args {
	struct	timeval *tp;
	struct	timezone *tzp;
};
#endif
/* ARGSUSED */
int
gettimeofday(p, uap)
	struct proc *p;
	register struct gettimeofday_args *uap;
{
	struct timeval atv;
	int error = 0;

	if (uap->tp) {
		microtime(&atv);
		if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
		    sizeof (atv))))
			return (error);
	}
	if (uap->tzp)
		error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
		    sizeof (tz));
	return (error);
}

#ifndef _SYS_SYSPROTO_H_
struct settimeofday_args {
	struct	timeval *tv;
	struct	timezone *tzp;
};
#endif
/* ARGSUSED */
int
settimeofday(p, uap)
	struct proc *p;
	struct settimeofday_args *uap;
{
	struct timeval atv;
	struct timezone atz;
	int error;

	if ((error = suser(p->p_ucred, &p->p_acflag)))
		return (error);
	/* Verify all parameters before changing time. */
	if (uap->tv) {
		if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
		    sizeof(atv))))
			return (error);
		if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
			return (EINVAL);
	}
	if (uap->tzp &&
	    (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
		return (error);
	if (uap->tv && (error = settime(&atv)))
		return (error);
	if (uap->tzp)
		tz = atz;
	return (0);
}

int	tickdelta;			/* current clock skew, us. per tick */
long	timedelta;			/* unapplied time correction, us. */
static long	bigadj = 1000000;	/* use 10x skew above bigadj us. */

#ifndef _SYS_SYSPROTO_H_
struct adjtime_args {
	struct timeval *delta;
	struct timeval *olddelta;
};
#endif
/* ARGSUSED */
int
adjtime(p, uap)
	struct proc *p;
	register struct adjtime_args *uap;
{
	struct timeval atv;
	register long ndelta, ntickdelta, odelta;
	int s, error;

	if ((error = suser(p->p_ucred, &p->p_acflag)))
		return (error);
	if ((error =
	    copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
		return (error);

	/*
	 * Compute the total correction and the rate at which to apply it.
	 * Round the adjustment down to a whole multiple of the per-tick
	 * delta, so that after some number of incremental changes in
	 * hardclock(), tickdelta will become zero, lest the correction
	 * overshoot and start taking us away from the desired final time.
	 */
	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
	if (ndelta > bigadj || ndelta < -bigadj)
		ntickdelta = 10 * tickadj;
	else
		ntickdelta = tickadj;
	if (ndelta % ntickdelta)
		ndelta = ndelta / ntickdelta * ntickdelta;

	/*
	 * To make hardclock()'s job easier, make the per-tick delta negative
	 * if we want time to run slower; then hardclock can simply compute
	 * tick + tickdelta, and subtract tickdelta from timedelta.
	 */
	if (ndelta < 0)
		ntickdelta = -ntickdelta;
	s = splclock();
	odelta = timedelta;
	timedelta = ndelta;
	tickdelta = ntickdelta;
	splx(s);

	if (uap->olddelta) {
		atv.tv_sec = odelta / 1000000;
		atv.tv_usec = odelta % 1000000;
		(void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
		    sizeof(struct timeval));
	}
	return (0);
}

/*
 * Get value of an interval timer.  The process virtual and
 * profiling virtual time timers are kept in the p_stats area, since
 * they can be swapped out.  These are kept internally in the
 * way they are specified externally: in time until they expire.
 *
 * The real time interval timer is kept in the process table slot
 * for the process, and its value (it_value) is kept as an
 * absolute time rather than as a delta, so that it is easy to keep
 * periodic real-time signals from drifting.
 *
 * Virtual time timers are processed in the hardclock() routine of
 * kern_clock.c.  The real time timer is processed by a timeout
 * routine, called from the softclock() routine.  Since a callout
 * may be delayed in real time due to interrupt processing in the system,
 * it is possible for the real time timeout routine (realitexpire, given below),
 * to be delayed in real time past when it is supposed to occur.  It
 * does not suffice, therefore, to reload the real timer .it_value from the
 * real time timers .it_interval.  Rather, we compute the next time in
 * absolute time the timer should go off.
 */
#ifndef _SYS_SYSPROTO_H_
struct getitimer_args {
	u_int	which;
	struct	itimerval *itv;
};
#endif
/* ARGSUSED */
int
getitimer(p, uap)
	struct proc *p;
	register struct getitimer_args *uap;
{
	struct timeval ctv;
	struct itimerval aitv;
	int s;

	if (uap->which > ITIMER_PROF)
		return (EINVAL);
	s = splclock(); /* XXX still needed ? */
	if (uap->which == ITIMER_REAL) {
		/*
		 * Convert from absolute to relative time in .it_value
		 * part of real time timer.  If time for real time timer
		 * has passed return 0, else return difference between
		 * current time and time for the timer to go off.
		 */
		aitv = p->p_realtimer;
		if (timevalisset(&aitv.it_value)) {
			getmicrouptime(&ctv);
			if (timevalcmp(&aitv.it_value, &ctv, <))
				timevalclear(&aitv.it_value);
			else
				timevalsub(&aitv.it_value, &ctv);
		}
	} else
		aitv = p->p_stats->p_timer[uap->which];
	splx(s);
	return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
	    sizeof (struct itimerval)));
}

#ifndef _SYS_SYSPROTO_H_
struct setitimer_args {
	u_int	which;
	struct	itimerval *itv, *oitv;
};
#endif
/* ARGSUSED */
int
setitimer(p, uap)
	struct proc *p;
	register struct setitimer_args *uap;
{
	struct itimerval aitv;
	struct timeval ctv;
	register struct itimerval *itvp;
	int s, error;

	if (uap->which > ITIMER_PROF)
		return (EINVAL);
	itvp = uap->itv;
	if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
	    sizeof(struct itimerval))))
		return (error);
	if ((uap->itv = uap->oitv) &&
	    (error = getitimer(p, (struct getitimer_args *)uap)))
		return (error);
	if (itvp == 0)
		return (0);
	if (itimerfix(&aitv.it_value))
		return (EINVAL);
	if (!timevalisset(&aitv.it_value))
		timevalclear(&aitv.it_interval);
	else if (itimerfix(&aitv.it_interval))
		return (EINVAL);
	s = splclock(); /* XXX: still needed ? */
	if (uap->which == ITIMER_REAL) {
		if (timevalisset(&p->p_realtimer.it_value))
			untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
		if (timevalisset(&aitv.it_value))
			p->p_ithandle = timeout(realitexpire, (caddr_t)p,
						tvtohz(&aitv.it_value));
		getmicrouptime(&ctv);
		timevaladd(&aitv.it_value, &ctv);
		p->p_realtimer = aitv;
	} else
		p->p_stats->p_timer[uap->which] = aitv;
	splx(s);
	return (0);
}

/*
 * Real interval timer expired:
 * send process whose timer expired an alarm signal.
 * If time is not set up to reload, then just return.
 * Else compute next time timer should go off which is > current time.
 * This is where delay in processing this timeout causes multiple
 * SIGALRM calls to be compressed into one.
 * tvtohz() always adds 1 to allow for the time until the next clock
 * interrupt being strictly less than 1 clock tick, but we don't want
 * that here since we want to appear to be in sync with the clock
 * interrupt even when we're delayed.
 */
void
realitexpire(arg)
	void *arg;
{
	register struct proc *p;
	struct timeval ctv, ntv;
	int s;

	p = (struct proc *)arg;
	psignal(p, SIGALRM);
	if (!timevalisset(&p->p_realtimer.it_interval)) {
		timevalclear(&p->p_realtimer.it_value);
		return;
	}
	for (;;) {
		s = splclock(); /* XXX: still neeeded ? */
		timevaladd(&p->p_realtimer.it_value,
		    &p->p_realtimer.it_interval);
		getmicrouptime(&ctv);
		if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
			ntv = p->p_realtimer.it_value;
			timevalsub(&ntv, &ctv);
			p->p_ithandle = timeout(realitexpire, (caddr_t)p,
			    tvtohz(&ntv) - 1);
			splx(s);
			return;
		}
		splx(s);
	}
}

/*
 * Check that a proposed value to load into the .it_value or
 * .it_interval part of an interval timer is acceptable, and
 * fix it to have at least minimal value (i.e. if it is less
 * than the resolution of the clock, round it up.)
 */
int
itimerfix(tv)
	struct timeval *tv;
{

	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
		return (EINVAL);
	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
		tv->tv_usec = tick;
	return (0);
}

/*
 * Decrement an interval timer by a specified number
 * of microseconds, which must be less than a second,
 * i.e. < 1000000.  If the timer expires, then reload
 * it.  In this case, carry over (usec - old value) to
 * reduce the value reloaded into the timer so that
 * the timer does not drift.  This routine assumes
 * that it is called in a context where the timers
 * on which it is operating cannot change in value.
 */
int
itimerdecr(itp, usec)
	register struct itimerval *itp;
	int usec;
{

	if (itp->it_value.tv_usec < usec) {
		if (itp->it_value.tv_sec == 0) {
			/* expired, and already in next interval */
			usec -= itp->it_value.tv_usec;
			goto expire;
		}
		itp->it_value.tv_usec += 1000000;
		itp->it_value.tv_sec--;
	}
	itp->it_value.tv_usec -= usec;
	usec = 0;
	if (timevalisset(&itp->it_value))
		return (1);
	/* expired, exactly at end of interval */
expire:
	if (timevalisset(&itp->it_interval)) {
		itp->it_value = itp->it_interval;
		itp->it_value.tv_usec -= usec;
		if (itp->it_value.tv_usec < 0) {
			itp->it_value.tv_usec += 1000000;
			itp->it_value.tv_sec--;
		}
	} else
		itp->it_value.tv_usec = 0;		/* sec is already 0 */
	return (0);
}

/*
 * Add and subtract routines for timevals.
 * N.B.: subtract routine doesn't deal with
 * results which are before the beginning,
 * it just gets very confused in this case.
 * Caveat emptor.
 */
void
timevaladd(t1, t2)
	struct timeval *t1, *t2;
{

	t1->tv_sec += t2->tv_sec;
	t1->tv_usec += t2->tv_usec;
	timevalfix(t1);
}

void
timevalsub(t1, t2)
	struct timeval *t1, *t2;
{

	t1->tv_sec -= t2->tv_sec;
	t1->tv_usec -= t2->tv_usec;
	timevalfix(t1);
}

static void
timevalfix(t1)
	struct timeval *t1;
{

	if (t1->tv_usec < 0) {
		t1->tv_sec--;
		t1->tv_usec += 1000000;
	}
	if (t1->tv_usec >= 1000000) {
		t1->tv_sec++;
		t1->tv_usec -= 1000000;
	}
}


text:
body {
  width: 100%;
  height: 100%;
  font-family: "Lora", "Helvetica Neue", Helvetica, Arial, sans-serif;
  color: white;
  background-color: black;
  background-image: url("grayscale/imgbooks1.jpg");
}
html {
  width: 100%;
  height: 100%;
}
h1,
h2,
h3,
h4,
h5,
h6 {
  margin: 0 0 35px;
  text-transform: uppercase;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: 700;
  letter-spacing: 1px;
}
p {
  margin: 0 0 25px;
  font-size: 18px;
  line-height: 1.5;
}
@media (min-width: 768px) {
  p {
    margin: 0 0 35px;
    font-size: 20px;
    line-height: 1.6;
  }
}
a {
  color: #42DCA3;
  -webkit-transition: all 0.2s ease-in-out;
  -moz-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}
a:hover,
a:focus {
  text-decoration: none;
  color: #1d9b6c;
}
.light {
  font-weight: 400;
}
.navbar-custom {
  margin-bottom: 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  text-transform: uppercase;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  background-color: black;
}
.navbar-custom .navbar-toggle {
  color: white;
  background-color: rgba(255, 255, 255, 0.2);
  font-size: 12px;
}
.navbar-custom .navbar-toggle:focus,
.navbar-custom .navbar-toggle:active {
  outline: none;
}
.navbar-custom .navbar-brand {
  font-weight: 700;
}
.navbar-custom .navbar-brand:focus {
  outline: none;
}
.navbar-custom a {
  color: white;
}
.navbar-custom .nav li a {
  -webkit-transition: background 0.3s ease-in-out;
  -moz-transition: background 0.3s ease-in-out;
  transition: background 0.3s ease-in-out;
}
.navbar-custom .nav li a:hover {
  color: rgba(255, 255, 255, 0.8);
  outline: none;
  background-color: transparent;
}
.navbar-custom .nav li a:focus,
.navbar-custom .nav li a:active {
  outline: none;
  background-color: transparent;
}
.navbar-custom .nav li.active {
  outline: none;
}
.navbar-custom .nav li.active a {
  background-color: rgba(255, 255, 255, 0.3);
}
.navbar-custom .nav li.active a:hover {
  color: white;
}
@media (min-width: 768px) {
  .navbar-custom {
    padding: 20px 0;
    border-bottom: none;
    letter-spacing: 1px;
    background: transparent;
    -webkit-transition: background 0.5s ease-in-out, padding 0.5s ease-in-out;
    -moz-transition: background 0.5s ease-in-out, padding 0.5s ease-in-out;
    transition: background 0.5s ease-in-out, padding 0.5s ease-in-out;
  }
  .navbar-custom.top-nav-collapse {
    padding: 0;
    background: black;
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  }
}
.intro {
  display: table;
  width: 100%;
  height: auto;
  padding: 100px 0;
  text-align: center;
  color: white;
  background: url(../img/Books.jpg) no-repeat bottom center scroll;
  background-color: black;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}
.intro .intro-body {
  display: table-cell;
  vertical-align: middle;
}
.intro .intro-body .brand-heading {
  font-size: 40px;
}
.intro .intro-body .intro-text {
  font-size: 18px;
}
@media (min-width: 768px) {
  .intro {
    height: 100%;
    padding: 0;
  }
  .intro .intro-body .brand-heading {
    font-size: 100px;
  }
  .intro .intro-body .intro-text {
    font-size: 26px;
  }
}
.btn-circle {
  width: 70px;
  height: 70px;
  margin-top: 15px;
  padding: 7px 16px;
  border: 2px solid white;
  border-radius: 100% !important;
  font-size: 40px;
  color: white;
  background: transparent;
  -webkit-transition: background 0.3s ease-in-out;
  -moz-transition: background 0.3s ease-in-out;
  transition: background 0.3s ease-in-out;
}
.btn-circle:hover,
.btn-circle:focus {
  outline: none;
  color: white;
  background: rgba(255, 255, 255, 0.1);
}
.btn-circle i.animated {
  -webkit-transition-property: -webkit-transform;
  -webkit-transition-duration: 1s;
  -moz-transition-property: -moz-transform;
  -moz-transition-duration: 1s;
}
.btn-circle:hover i.animated {
  -webkit-animation-name: pulse;
  -moz-animation-name: pulse;
  -webkit-animation-duration: 1.5s;
  -moz-animation-duration: 1.5s;
  -webkit-animation-iteration-count: infinite;
  -moz-animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;
  -moz-animation-timing-function: linear;
}
@-webkit-keyframes pulse {
  0% {
    -webkit-transform: scale(1);
    transform: scale(1);
  }
  50% {
    -webkit-transform: scale(1.2);
    transform: scale(1.2);
  }
  100% {
    -webkit-transform: scale(1);
    transform: scale(1);
  }
}
@-moz-keyframes pulse {
  0% {
    -moz-transform: scale(1);
    transform: scale(1);
  }
  50% {
    -moz-transform: scale(1.2);
    transform: scale(1.2);
  }
  100% {
    -moz-transform: scale(1);
    transform: scale(1);
  }
}
.content-section {
  padding-top: 100px;
}
.download-section {
  width: 100%;
  padding: 50px 0;
  color: white;
  background: url(../img/downloads-bg.jpg) no-repeat center center scroll;
  background-color: black;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}
#map {
  width: 100%;
  height: 200px;
  margin-top: 100px;
}
@media (min-width: 767px) {
  .content-section {
    padding-top: 250px;
  }
  .download-section {
    padding: 100px 0;
  }
  #map {
    height: 400px;
    margin-top: 250px;
  }
}
.btn {
  text-transform: uppercase;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: 400;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
  border-radius: 0;
}
.btn-default {
  border: 1px solid #42DCA3;
  color: #42DCA3;
  background-color: transparent;
}
.btn-default:hover,
.btn-default:focus {
  border: 1px solid #42DCA3;
  outline: none;
  color: black;
  background-color: #42DCA3;
}
ul.banner-social-buttons {
  margin-top: 0;
}
@media (max-width: 1199px) {
  ul.banner-social-buttons {
    margin-top: 15px;
  }
}
@media (max-width: 767px) {
  ul.banner-social-buttons li {
    display: block;
    margin-bottom: 20px;
    padding: 0;
  }
  ul.banner-social-buttons li:last-child {
    margin-bottom: 0;
  }
}
footer {
  padding: 50px 0;
}
footer p {
  margin: 0;
}
::-moz-selection {
  text-shadow: none;
  background: #fcfcfc;
  background: rgba(255, 255, 255, 0.2);
}
::selection {
  text-shadow: none;
  background: #fcfcfc;
  background: rgba(255, 255, 255, 0.2);
}
img::selection {
  background: transparent;
}
img::-moz-selection {
  background: transparent;
}
body {
  webkit-tap-highlight-color: rgba(255, 255, 255, 0.2);
}

/* login form css */

/* Bordered form */
form {
    border: 3px ;
}

/* Full-width inputs */
input[type=text], input[type=password] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

/* Set a style for all buttons */
button {
    background-color: black;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 50%;
    border: 2px solid white;
    border-radius: 12px;
}

/* Center the avatar image inside this container */
.imgcontainer {
    text-align: center;
    margin: 24px 0 12px 0;
}

/* Avatar image */
img.avatar {
    width: 40%;
    border-radius: 50%;
}

/* Add padding to containers */
/*.container {
    padding: 16px;
}  */

/* The "Forgot password" text */
span.psw {
    float: right;
    padding-top: 16px;
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
    span.psw {
        display: block;
        float: none;
    }
    .cancelbtn {
        width: 100%;
    }
}

redpajama_set_name: RedPajamaGithub


text:
export default class ImageUtils {
    static personImageFor(externalId) {
        if (externalId) {
            return `/images/${externalId}.jpg`;
        } else {
            return this.fallbackImage();
        }
    }

    static partyLogoFor(externalId) {
        return `/images/${externalId.toLowerCase()}.png`;
    }

    static fallbackImage() {
        return '/images/unknown.jpg';
    }
}


text:
@implementation UIButton (EX)

+ (UIButton *(^)(UIButtonType))button {
    return ^UIButton *(UIButtonType type) {
        return [UIButton buttonWithType:type];
    };
}

- (UIButton *(^)(NSString *title, UIControlState status))title {
    return ^UIButton *(NSString *titleName, UIControlState status) {
        [self setTitle:titleName forState:status];
        return self;
    };
}

- (UIButton *(^)(UIImage *backgroundImage,UIControlState status))backgroundImage {
    return ^UIButton *(UIImage *backgroundImage,UIControlState status){
        [self setBackgroundImage:backgroundImage forState:status];
        return self;
    };
}

- (UIButton *(^)(UIColor * backgroundColor))bgColor {
    return ^UIButton *(UIColor * bgColor){
        [self setBackgroundColor:bgColor];
        return self;
    };
}

- (UIButton *(^)(UIColor *borderColor,CGFloat borderWidth))border {

    return ^UIButton *(UIColor *borderColor,CGFloat borderWidth) {
        self.layer.borderColor = borderColor.CGColor;
        self.layer.borderWidth = borderWidth;
        return self;
    };
}

- (UIButton *(^)(UIColor *))titleColor {
   return ^UIButton *(UIColor *titleColor){
        [self setTitleColor:titleColor forState:UIControlStateNormal];
        return self;
    };
}

- (UIButton *(^)(UIImage *, UIControlState))setShowImage {
    return ^UIButton * (UIImage *currentImage,UIControlState status) {
        [self setImage:currentImage forState:status];
        return self;
    };
}

@end


text:
<?php

namespace Helthe\Bundle\TurbolinksBundle\Composer;

use Symfony\Component\Process\Process;
use Symfony\Component\Process\PhpExecutableFinder;
use Composer\Script\Event;

/**
 * ScriptHandler for the HeltheTurbolinksBundle.
 *
 * @author Carl Alexander <carlalexander@helthe.co>
 */
class ScriptHandler
{
    /**
     * Install the component assets under the symfony bundle for better integration
     * with Symfony.
     *
     * @param Event $event
     */
    public static function installAssets(Event $event)
    {
        $options = self::getOptions($event);
        $consoleDir = self::getConsoleDir($event, 'turbolinks install');

        static::executeCommand($event, $consoleDir, 'helthe:turbolinks:install', $options['process-timeout']);
    }

    /**
     * Execute command.
     *
     * @param Event $event
     * @param string       $consoleDir
     * @param string       $cmd
     * @param integer      $timeout
     *
     * @throws \RuntimeException
     */
    protected static function executeCommand(Event $event, $consoleDir, $cmd, $timeout = 300)
    {
        $php = escapeshellarg(self::getPhp());
        $console = escapeshellarg($consoleDir.'/console');
        if ($event->getIO()->isDecorated()) {
            $console .= ' --ansi';
        }

        $process = new Process($php.' '.$console.' '.$cmd, null, null, null, $timeout);
        $process->run(function ($type, $buffer) { echo $buffer; });
        if (!$process->isSuccessful()) {
            throw new \RuntimeException(sprintf('An error occurred when executing the "%s" command.', escapeshellarg($cmd)));
        }
    }

    /**
     * Get the default options.
     *
     * @param Event $event
     *
     * @return array
     */
    protected static function getOptions(Event $event)
    {
        $options = array_merge(array(
            'symfony-app-dir' => 'app',
            'symfony-bin-dir' => 'bin',
        ), $event->getComposer()->getPackage()->getExtra());

        $options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');

        return $options;
    }

    /**
     * Get path to the PHP executable.
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    protected static function getPhp()
    {
        $phpFinder = new PhpExecutableFinder;
        if (!$phpPath = $phpFinder->find()) {
            throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
        }

        return $phpPath;
    }

    /**
     * Returns a relative path to the directory that contains the `console` command.
     *
     * @param Event $event      The command event.
     * @param string       $actionName The name of the action
     *
     * @return string|null The path to the console directory, null if not found.
     */
    protected static function getConsoleDir(Event $event, $actionName)
    {
        $options = self::getOptions($event);

        if (self::useNewDirectoryStructure($options)) {
            if (!self::hasDirectory($event, 'symfony-bin-dir', $options['symfony-bin-dir'], $actionName)) {
                return;
            }

            return $options['symfony-bin-dir'];
        }

        if (!self::hasDirectory($event, 'symfony-app-dir', $options['symfony-app-dir'], 'execute command')) {
            return;
        }

        return $options['symfony-app-dir'];
    }

    /**
     * Returns true if the new directory structure is used.
     *
     * @param array $options Composer options
     *
     * @return bool
     */
    protected static function useNewDirectoryStructure(array $options)
    {
        return isset($options['symfony-var-dir']) && is_dir($options['symfony-var-dir']);
    }

    protected static function hasDirectory(Event $event, $configName, $path, $actionName)
    {
        if (!is_dir($path)) {
            $event->getIO()->write(sprintf('The %s (%s) specified in composer.json was not found in %s, can not %s.', $configName, $path, getcwd(), $actionName));

            return false;
        }

        return true;
    }
}


text:
package main

import (
	"encoding/base32"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"os"
	"strings"
)

func escape(encoding string) {
	switch {
	case strings.HasPrefix("query", encoding):
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		os.Stdout.Write([]byte(url.QueryEscape(string(b))))
	case strings.HasPrefix("hex", encoding):
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		os.Stdout.Write([]byte(hex.EncodeToString(b)))
	default:
		fmt.Fprintf(os.Stderr, "unknown escape encoding: %q\n", encoding)
		os.Exit(2)
	}
}

func unescape(encoding string) {
	switch {
	case strings.HasPrefix("query", encoding):
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		s, err := url.QueryUnescape(string(b))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		os.Stdout.Write([]byte(s))
	case strings.HasPrefix("b32", encoding):
		d := base32.NewDecoder(base32.StdEncoding, os.Stdin)
		io.Copy(os.Stdout, d)
	default:
		fmt.Fprintf(os.Stderr, "unknown unescape encoding: %q\n", encoding)
	}
}

func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "expected two arguments: <mode> <encoding>: got %d\n", len(os.Args)-1)
		os.Exit(2)
	}
	mode := os.Args[1]
	switch {
	case strings.HasPrefix("escape", mode):
		escape(os.Args[2])
	case strings.HasPrefix("unescape", mode) || strings.HasPrefix("decode", mode):
		unescape(os.Args[2])
	default:
		fmt.Fprintf(os.Stderr, "unknown mode: %q\n", mode)
		os.Exit(2)
	}
}


text:
USE Kinder_garden
--Çàïðåùàåì âñòàâëÿòü çàïèñü â Teacher_of_section, íà òåêóùèé ìåñÿö è ãîä íà ñåêöèè óæå çàêðåïëåí ó÷èòåëü

IF OBJECT_ID('TRG_DenyInsDupOfSectOnMonthYear') IS NOT NULL
DROP TRIGGER TRG_DenyInsDupOfSectOnMonthYear
GO
CREATE TRIGGER TRG_DenyInsDupOfSectOnMonthYear
ON Teacher_Of_section
AFTER INSERT AS
	BEGIN
		SET NOCOUNT ON;
		----------------------------------------------
	IF (EXISTS(SELECT Teacher_Of_section.month_sect,Teacher_Of_section.year_sect, Teacher_Of_section.id_section
				FROM Kinder_garden.dbo.Teacher_Of_section
				WHERE (Teacher_Of_section.month_sect = (SELECT month_sect FROM INSERTED)
					AND Teacher_Of_section.year_sect = (SELECT year_sect FROM INSERTED)
					AND Teacher_Of_section.id_section = (SELECT id_section FROM INSERTED)
					)
			))

		BEGIN
			ROLLBACK
			PRINT'Âû íå ìîæåòå äîáàâèòü ïðåïîäàâàòåëÿ íà äàííûé ìåñÿö â äàííóþ ñåêöèþ, òàê êàê íà ýòó ñåêöèþ óæå çàêðåïëåí ïðåïîäàâàòåëü.'
		END
	ELSE
		BEGIN
			PRINT'Çàïèñü äîáàâëåíà.'
		END
	END
GO
USE Kinder_garden

INSERT INTO Teacher_of_section(id_section, id_employee, month_sect, year_sect) VALUES
	(2, 3, 3, 2013)
GO
SELECT * from Teacher_of_section
ORDER BY year_sect, month_sect, id_section
GO

--Ñîçäàåì ðåçåðâíóþ êîïèþ âñåõ âñòàâîê â òàáëèöó Ðàáîòíèêîâ
USE Kinder_garden
IF OBJECT_ID('TRG_InsertSyncEmp') IS NOT NULL
DROP TRIGGER TRG_InsertSyncEmp
GO

CREATE TRIGGER TRG_InsertSyncEmp
ON Kinder_garden.dbo.Employee
AFTER INSERT AS
	BEGIN
		INSERT INTO Kinder_garden.dbo.Employee_BackUp(surname, first_name, last_name, birthday, home_address, telephone, id_med_record)
		SELECT surname, first_name, last_name, birthday, home_address, telephone, id_med_record
		FROM INSERTED
	END
GO

INSERT INTO Employee (surname, first_name, last_name, birthday, home_address, telephone, id_med_record) VALUES
('Grinko', 'Alex', 'Rigorioch', '2012-10-22 00:00:00', 'st. Pobedi, 34, 22', 380987415623, null)

SELECT * from Employee
SELECT * from Employee_BackUp
GO


text:
package no.panopticon.api.internal;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
        if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
            response.setStatus(HttpStatus.NO_CONTENT.value());
        }else{
            filterChain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Chi, [Fungal Diseases of Cultivated Medicinal Plants in Guangdong Province] (Guangdong) 160 (1994)

#### Original name
Leptosphaerulina platycodonis J.F. Lue & P.K. Chi

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace aoc.csharp._2016
{
    public class Day08 : ISolver
    {
        public (string Part1, string Part2) GetSolution(TextReader input)
        {
            return GetAnswer(input);
        }

        public static (string Part1, string Part2) GetAnswer(TextReader input)
        {
            List<IInstruction> instructions = ParseInstructions(input);

            var screen = new bool[50, 6];
            InitialiseScreen(screen);

            foreach (var instruction in instructions)
            {
                instruction.Execute(screen);
            }

            var part1 = CountOnLights(screen);
            var part2 = DisplayScreen(screen);

            return (part1.ToString(), part2);
        }

        private static readonly Regex RectRegex = new Regex("^rect ([\\d]+)x([\\d]+)$");
        private static readonly Regex RotateColumnRegex = new Regex("^rotate column x=([\\d]+) by ([\\d]+)$");
        private static readonly Regex RotateRowRegex = new Regex("^rotate row y=([\\d]+) by ([\\d]+)$");

        private static int CountOnLights(bool[,] screen)
        {
            int count = 0;
            int width = screen.GetLength(0);
            int height = screen.GetLength(1);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (screen[x, y])
                    {
                        count++;
                    }
                }
            }

            return count;
        }

        public static string DisplayScreen(bool[,] screen)
        {
            int width = screen.GetLength(0);
            int height = screen.GetLength(1);

            var str = new StringBuilder();

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    str.Append(screen[x, y] ? '#' : ' ');
                }
                str.AppendLine();
            }

            return str.ToString();
        }

        public static void InitialiseScreen(bool[,] screen)
        {
            int width = screen.GetLength(0);
            int height = screen.GetLength(1);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    screen[x, y] = false;
                }
            }
        }

        public static List<IInstruction> ParseInstructions(TextReader input)
        {
            var instructions = new List<IInstruction>();
            string? line;

            while ((line = input.ReadLine()) != null)
            {
                Match match;
                if ((match = RectRegex.Match(line)).Success)
                {
                    int width = int.Parse(match.Groups[1].Value);
                    int height = int.Parse(match.Groups[2].Value);
                    instructions.Add(new Rect(width, height));
                }
                else if ((match = RotateColumnRegex.Match(line)).Success)
                {
                    int column = int.Parse(match.Groups[1].Value);
                    int amount = int.Parse(match.Groups[2].Value);
                    instructions.Add(new RotateColumn(column, amount));
                }
                else if ((match = RotateRowRegex.Match(line)).Success)
                {
                    int row = int.Parse(match.Groups[1].Value);
                    int amount = int.Parse(match.Groups[2].Value);
                    instructions.Add(new RotateRow(row, amount));
                }
                else
                {
                    throw new ArgumentException("Can't parse line");
                }
            }

            return instructions;
        }

        public interface IInstruction
        {
            void Execute(bool[,] screen);
        }

        private class Rect : IInstruction
        {
            public int Width { get; }
            public int Height { get; }

            public Rect(int width, int height)
            {
                Width = width;
                Height = height;
            }

            public override string ToString()
            {
                return $"rect {Width}x{Height}";
            }

            public void Execute(bool[,] screen)
            {
                for (int y = 0; y < Height; y++)
                {
                    for (int x = 0; x < Width; x++)
                    {
                        screen[x, y] = true;
                    }
                }
            }
        }

        private class RotateColumn : IInstruction
        {
            public int Column { get; }
            public int Amount { get; }

            public RotateColumn(int column, int amount)
            {
                Column = column;
                Amount = amount;
            }

            public override string ToString()
            {
                return $"rotate column x={Column} by {Amount}";
            }

            public void Execute(bool[,] screen)
            {
                var height = screen.GetLength(1);
                var column = new bool[height];

                for (int y = 0; y < height; y++)
                {
                    column[y] = screen[Column, y];
                }

                for (int y = 0; y < height; y++)
                {
                    screen[Column, (y + Amount) % height] = column[y];
                }
            }
        }

        private class RotateRow : IInstruction
        {
            public int Row { get; }
            public int Amount { get; }

            public RotateRow(int row, int amount)
            {
                Row = row;
                Amount = amount;
            }

            public override string ToString()
            {
                return $"rotate row y={Row} by {Amount}";
            }

            public void Execute(bool[,] screen)
            {
                var width = screen.GetLength(0);
                var row = new bool[width];

                for (int x = 0; x < width; x++)
                {
                    row[x] = screen[x, Row];
                }

                for (int x = 0; x < width; x++)
                {
                    screen[(x + Amount) % width, Row] = row[x];
                }
            }
        }
    }
}


text:
package org.br.corbaSupport.client;

/**
* Client.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from Client.idl
* Tuesday, November 26, 2013 11:12:28 AM BRST
*/

public interface Client extends ClientOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
{
} // interface Client


text:
package com.wenyu.kjw.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.mywork.util.AsyncImageLoader;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.wenyu.Data.Find_yingshi;
import com.wenyu.kaijiw.R;

public class HomeYing  extends BaseAdapter{
	private  List<Find_yingshi> strs;
	private Context context;
	private AsyncImageLoader mAsyncImageLoader;
	public HomeYing(List<Find_yingshi> strs, Context context) {
		super();
		this.strs = strs;
		this.context = context;

	}

	public void setData(List<Find_yingshi> strs){
		this.strs = strs;
	}

	@Override
	public int getCount() {
		if(strs.size()<=0){
			return 0;
		}
		return strs.size();
	}

	@Override
	public Object getItem(int arg0) {
		if(strs.size()<=0){
			return null;
		}
		return strs.get(arg0);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	/*
	 * (non-Javadoc)
	 *getView·½·¨µÄÊý¾ÝÐèÒª¸ü¸Ä¡£
	 * */
	@Override
	public View getView(int position, View convertView, final ViewGroup parent) {
		ViewHolder vh;
		if(convertView ==null){
			vh = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.drop_dowm_box
					, null);
			vh.ps = (TextView) convertView.findViewById(R.id.ps);
			vh.text = (TextView) convertView.findViewById(R.id.textView1);
			vh.image = (ImageView) convertView.findViewById(R.id.imageView);
			vh.image.setColorFilter(Color.GRAY,PorterDuff.Mode.MULTIPLY);

			convertView.setTag(vh);
		}else{
			vh = (ViewHolder) convertView.getTag();
		}
		Find_yingshi str =strs.get(position);

	    vh.text.setText(str.getName());
	    vh.text.setTextSize(20);
		vh.ps.setText(" "+str.getCountV()+"´Îä¯ÀÀ"+" ");
		final String imageUrl = str.getPicture();
		//¸øImageViewÉèÖñê¼Ç£¨Í¼Æ¬µÄurl£©£¬ÒÔ·ÀֹͼƬ¼ÓÔØ»ìÂÒ
		vh.image.setTag(imageUrl);
		ImageLoader imageloader = ImageLoader.getInstance();
		imageloader.init(ImageLoaderConfiguration.createDefault(context));

		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
		//¼ÓÔØ¿ªÊ¼Ä¬ÈϵÄͼƬ
		.showStubImage(R.drawable.z1)
		//urlΪ¿ÕʱÏÔʾ¸ÃͼƬ
		.showImageForEmptyUri(R.drawable.z2)
		.cacheInMemory(true)
		.cacheOnDisc(true)
//		.cacheOnDisc(false)
		//¼ÓÔØͼƬ³öÏÖÎÊÌâÏÔʾͼƬ
		.showImageOnFail(R.drawable.z3)
		.build();

		imageloader.displayImage(imageUrl, vh.image,defaultOptions);

		return convertView;
	}
	class ViewHolder{
		TextView ps,text;
		ImageView image;
	}
}


text:
package com.tk.cn.threads;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;

/**
 *
 * @ClassName: MultiThreadedRunner
 * @Description: (
 * (二)自定义对单个类进行多线程执行的Runner,
 * 只要在单个测试类前,加上注解:@RunWith(MultiThreadRunner.class),
 * 就可以并发的执行用例。 )
 * @author tangkuo
 * @date 2017年6月28日 下午10:22:13
 *
 */
public class MultiThreadedRunner extends BlockJUnit4ClassRunner {
	private AtomicInteger numThreads;

	public static int maxThreads = 10;

	public MultiThreadedRunner(Class<?> klass) throws InitializationError {
		super(klass);
		numThreads = new AtomicInteger(0);
	}

	// Runs the test corresponding to child,which can be assumed to be an
	// element of the list returned by getChildren()
	@Override
	protected void runChild(final FrameworkMethod method, final RunNotifier notifier) {
		while (numThreads.get() > maxThreads) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.err.println("Interrupted: " + method.getName());
				e.printStackTrace();
				return; // The user may have interrupted us; this won't happen
						// normally
			}
		}
		numThreads.incrementAndGet();
		// 用线程执行父类runChild(method, notifier)
		new Thread(new Test(method, notifier)).start();
	}

	// childrenInvoker() call runChild(Object, RunNotifier) on each object
	// returned by getChildren()
	// evaluate() run the action, 调用父类BlockJUnit4ClassRunner的evaluate()
	@Override
	protected Statement childrenInvoker(final RunNotifier notifier) {
		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				MultiThreadedRunner.super.childrenInvoker(notifier).evaluate();
				// wait for all child threads (tests) to complete
				while (numThreads.get() > 0) {
					Thread.sleep(1000);
				}
			}
		};
	}

	class Test implements Runnable {
		private final FrameworkMethod method;
		private final RunNotifier notifier;

		public Test(final FrameworkMethod method, final RunNotifier notifier) {
			this.method = method;
			this.notifier = notifier;
		}

		@Override
		public void run() {
			System.err.println(method.getName());
			MultiThreadedRunner.super.runChild(method, notifier);
			numThreads.decrementAndGet();
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-parent</artifactId>
		<version>1.4.0.BUILD-SNAPSHOT</version>
	</parent>
	<artifactId>spring-boot-devtools</artifactId>
	<name>Spring Boot Developer Tools</name>
	<description>Spring Boot Developer Tools</description>
	<url>http://projects.spring.io/spring-boot/</url>
	<organization>
		<name>Pivotal Software, Inc.</name>
		<url>http://www.spring.io</url>
	</organization>
	<properties>
		<main.basedir>${basedir}/../..</main.basedir>
	</properties>
	<dependencies>
		<!-- Compile -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
		</dependency>
		<!-- Optional -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- Annotation processing -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- Test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-logging-juli</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty.websocket</groupId>
			<artifactId>websocket-client</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring4</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>nz.net.ultraq.thymeleaf</groupId>
			<artifactId>thymeleaf-layout-dialect</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jdbc</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
package com.epam.jenkins.deployment.sphere.plugin.metadata.model;

import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import lombok.Data;

@Data
@ExportedBean
public class CommitMetaData {
    @Exported
    private String author;
    @Exported
    private String id;
    @Exported
    private String message;
}


text:
//
// System.Web.UI.TemplateControl.cs
//
// Authors:
//   Duncan Mak  (duncan@ximian.com)
//   Gonzalo Paniagua Javier (gonzalo@ximian.com)
//   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//
// (C) 2002 Ximian, Inc. (http://www.ximian.com)
//

//
// 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.
//

using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Web;
using System.Web.Compilation;
using System.Web.Util;

namespace System.Web.UI {

	public abstract class TemplateControl : Control, INamingContainer
	{
		static object abortTransaction = new object ();
		static object commitTransaction = new object ();
		static object error = new object ();
		static string [] methodNames = { "Page_Init",
						 "Page_Load",
						 "Page_DataBind",
						 "Page_PreRender",
						 "Page_Disposed",
						 "Page_Error",
						 "Page_Unload",
						 "Page_AbortTransaction",
						 "Page_CommitTransaction" };

		const BindingFlags bflags = BindingFlags.Public |
					    BindingFlags.NonPublic |
					    BindingFlags.Instance;

		#region Constructor
		protected TemplateControl ()
		{
			Construct ();
		}

		#endregion

		#region Properties
		[EditorBrowsable (EditorBrowsableState.Never)]
		protected virtual int AutoHandlers {
			get { return 0; }
			set { }
		}

		[EditorBrowsable (EditorBrowsableState.Never)]
		protected virtual bool SupportAutoEvents {
			get { return true; }
		}

		#endregion

		#region Methods

		protected virtual void Construct ()
		{
		}

		[MonoTODO]
		protected LiteralControl CreateResourceBasedLiteralControl (int offset,
										    int size,
										    bool fAsciiOnly)
		{
			return null;
		}

		internal void WireupAutomaticEvents ()
		{
			if (!SupportAutoEvents || !AutoEventWireup)
				return;

			Type type = GetType ();
			foreach (string methodName in methodNames) {
				MethodInfo method = type.GetMethod (methodName, bflags);
				if (method == null)
					continue;

				if (method.DeclaringType != type) {
					if (!method.IsPublic && !method.IsFamilyOrAssembly &&
					    !method.IsFamilyAndAssembly && !method.IsFamily)
						continue;
				}

				if (method.ReturnType != typeof (void))
					continue;

				ParameterInfo [] parms = method.GetParameters ();
				int length = parms.Length;
				bool noParams = (length == 0);
				if (!noParams && (length != 2 ||
				    parms [0].ParameterType != typeof (object) ||
				    parms [1].ParameterType != typeof (EventArgs)))
				    continue;

				int pos = methodName.IndexOf ("_");
				string eventName = methodName.Substring (pos + 1);
				EventInfo evt = type.GetEvent (eventName);
				if (evt == null) {
					/* This should never happen */
					continue;
				}

				if (noParams) {
					NoParamsInvoker npi = new NoParamsInvoker (this, methodName);
					evt.AddEventHandler (this, npi.FakeDelegate);
				} else {
					evt.AddEventHandler (this, Delegate.CreateDelegate (
							typeof (EventHandler), this, methodName));
				}
			}
		}

		[EditorBrowsable (EditorBrowsableState.Never)]
		protected virtual void FrameworkInitialize ()
		{
		}

		Type GetTypeFromControlPath (string virtualPath)
		{
			if (virtualPath == null)
				throw new ArgumentNullException ("virtualPath");

			string vpath = UrlUtils.Combine (TemplateSourceDirectory, virtualPath);
			string realpath = Context.Request.MapPath (vpath);
			return UserControlParser.GetCompiledType (vpath, realpath, Context);
		}

		public Control LoadControl (string virtualPath)
		{
			object control = Activator.CreateInstance (GetTypeFromControlPath (virtualPath));
			if (control is UserControl)
				((UserControl) control).InitializeAsUserControl (Page);

			return (Control) control;
		}

		public ITemplate LoadTemplate (string virtualPath)
		{
			Type t = GetTypeFromControlPath (virtualPath);
			return new SimpleTemplate (t);
		}

		protected virtual void OnAbortTransaction (EventArgs e)
		{
			EventHandler eh = Events [abortTransaction] as EventHandler;
			if (eh != null)
				eh (this, e);
		}

		protected virtual void OnCommitTransaction (EventArgs e)
		{
			EventHandler eh = Events [commitTransaction] as EventHandler;
			if (eh != null)
				eh (this, e);
		}

		protected virtual void OnError (EventArgs e)
		{
			EventHandler eh = Events [error] as EventHandler;
			if (eh != null)
				eh (this, e);
		}

		[MonoTODO]
		public Control ParseControl (string content)
		{
			return null;
		}

		[MonoTODO]
		[EditorBrowsable (EditorBrowsableState.Never)]
		public static object ReadStringResource (Type t)
		{
			return null;
		}

		[MonoTODO]
		[EditorBrowsable (EditorBrowsableState.Never)]
		protected void SetStringResourcePointer (object stringResourcePointer,
							 int maxResourceOffset)
		{
		}

		[MonoTODO]
		[EditorBrowsable (EditorBrowsableState.Never)]
		protected void WriteUTF8ResourceString (HtmlTextWriter output, int offset,
							int size, bool fAsciiOnly)
		{
		}

		#endregion

		#region Events

		[WebSysDescription ("Raised when the user aborts a transaction.")]
		public event EventHandler AbortTransaction {
			add { Events.AddHandler (abortTransaction, value); }
			remove { Events.RemoveHandler (abortTransaction, value); }
		}

		[WebSysDescription ("Raised when the user initiates a transaction.")]
		public event EventHandler CommitTransaction {
			add { Events.AddHandler (commitTransaction, value); }
			remove { Events.RemoveHandler (commitTransaction, value); }
		}

		[WebSysDescription ("Raised when an exception occurs that cannot be handled.")]
		public event EventHandler Error {
			add { Events.AddHandler (error, value); }
			remove { Events.RemoveHandler (error, value); }
		}

		#endregion

		class SimpleTemplate : ITemplate
		{
			Type type;

			public SimpleTemplate (Type type)
			{
				this.type = type;
			}

			public void InstantiateIn (Control control)
			{
				Control template = Activator.CreateInstance (type) as Control;
				template.SetBindingContainer (false);
				control.Controls.Add (template);
			}
		}

#if NET_2_0

	Stack dataItemCtx;

	internal void PushDataItemContext (object o)
	{
		if (dataItemCtx == null)
			dataItemCtx = new Stack ();

		dataItemCtx.Push (o);
	}

	internal void PopDataItemContext ()
	{
		if (dataItemCtx == null)
			throw new InvalidOperationException ();

		dataItemCtx.Pop ();
	}

	internal object CurrentDataItem {
		get {
			if (dataItemCtx == null || dataItemCtx.Count == 0)
				throw new InvalidOperationException ("No data item");

			return dataItemCtx.Peek ();
		}
	}

	protected object Eval (string expression)
	{
		return DataBinder.Eval (CurrentDataItem, expression);
	}

	protected object Eval (string expression, string format)
	{
		return DataBinder.Eval (CurrentDataItem, expression, format);
	}

	protected object XPath (string xpathexpression)
	{
		return XPathBinder.Eval (CurrentDataItem, xpathexpression);
	}

	protected object XPath (string xpathexpression, string format)
	{
		return XPathBinder.Eval (CurrentDataItem, xpathexpression, format);
	}

	protected IEnumerable XPathSelect (string xpathexpression)
	{
		return XPathBinder.Select (CurrentDataItem, xpathexpression);
	}
#endif

	}
}


text:
package org.apache.cassandra.cache;

import java.io.IOException;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.EvictionListener;
import com.googlecode.concurrentlinkedhashmap.Weigher;

import org.apache.cassandra.io.ISerializer;
import org.apache.cassandra.io.util.MemoryInputStream;
import org.apache.cassandra.io.util.MemoryOutputStream;
import org.apache.cassandra.io.util.WrappedDataOutputStreamPlus;

/**
 * Serializes cache values off-heap.
 */
//用于row缓存
public class SerializingCache<K, V> implements ICache<K, V>
{
    private static final Logger logger = LoggerFactory.getLogger(SerializingCache.class);

    private static final int DEFAULT_CONCURENCY_LEVEL = 64;

    private final ConcurrentLinkedHashMap<K, RefCountedMemory> map;
    private final ISerializer<V> serializer;

    private SerializingCache(long capacity, Weigher<RefCountedMemory> weigher, ISerializer<V> serializer)
    {
        this.serializer = serializer;

        EvictionListener<K,RefCountedMemory> listener = new EvictionListener<K, RefCountedMemory>()
        {
            public void onEviction(K k, RefCountedMemory mem)
            {
                mem.unreference();
            }
        };

        this.map = new ConcurrentLinkedHashMap.Builder<K, RefCountedMemory>()
                   .weigher(weigher)
                   .maximumWeightedCapacity(capacity)
                   .concurrencyLevel(DEFAULT_CONCURENCY_LEVEL)
                   .listener(listener)
                   .build();
    }

    public static <K, V> SerializingCache<K, V> create(long weightedCapacity, Weigher<RefCountedMemory> weigher, ISerializer<V> serializer)
    {
        return new SerializingCache<>(weightedCapacity, weigher, serializer);
    }

    public static <K, V> SerializingCache<K, V> create(long weightedCapacity, ISerializer<V> serializer)
    {
        return create(weightedCapacity, new Weigher<RefCountedMemory>()
        {
            public int weightOf(RefCountedMemory value)
            {
                long size = value.size();
                assert size < Integer.MAX_VALUE : "Serialized size cannot be more than 2GB";
                return (int) size;
            }
        }, serializer);
    }

    private V deserialize(RefCountedMemory mem)
    {
        try
        {
            return serializer.deserialize(new MemoryInputStream(mem));
        }
        catch (IOException e)
        {
            logger.trace("Cannot fetch in memory data, we will fallback to read from disk ", e);
            return null;
        }
    }

    private RefCountedMemory serialize(V value)
    {
        long serializedSize = serializer.serializedSize(value);
        if (serializedSize > Integer.MAX_VALUE)
            throw new IllegalArgumentException("Unable to allocate " + serializedSize + " bytes");

        RefCountedMemory freeableMemory;
        try
        {
            freeableMemory = new RefCountedMemory(serializedSize);
        }
        catch (OutOfMemoryError e)
        {
            return null;
        }

        try
        {
            serializer.serialize(value, new WrappedDataOutputStreamPlus(new MemoryOutputStream(freeableMemory)));
        }
        catch (IOException e)
        {
            freeableMemory.unreference();
            throw new RuntimeException(e);
        }
        return freeableMemory;
    }

    public long capacity()
    {
        return map.capacity();
    }

    public void setCapacity(long capacity)
    {
        map.setCapacity(capacity);
    }

    public boolean isEmpty()
    {
        return map.isEmpty();
    }

    public int size()
    {
        return map.size();
    }

    public long weightedSize()
    {
        return map.weightedSize();
    }

    public void clear()
    {
        map.clear();
    }

    @SuppressWarnings("resource")
    public V get(K key)
    {
        RefCountedMemory mem = map.get(key);
        if (mem == null)
            return null;
        if (!mem.reference())
            return null;
        try
        {
            return deserialize(mem);
        }
        finally
        {
            mem.unreference();
        }
    }

    @SuppressWarnings("resource")
    public void put(K key, V value)
    {
        RefCountedMemory mem = serialize(value);
        if (mem == null)
            return; // out of memory.  never mind.

        RefCountedMemory old;
        try
        {
            old = map.put(key, mem);
        }
        catch (Throwable t)
        {
            mem.unreference();
            throw t;
        }

        if (old != null)
            old.unreference();
    }

    @SuppressWarnings("resource")
    public boolean putIfAbsent(K key, V value)
    {
        RefCountedMemory mem = serialize(value);
        if (mem == null)
            return false; // out of memory.  never mind.

        RefCountedMemory old;
        try
        {
            old = map.putIfAbsent(key, mem);
        }
        catch (Throwable t)
        {
            mem.unreference();
            throw t;
        }

        if (old != null)
            // the new value was not put, we've uselessly allocated some memory, free it
            mem.unreference();
        return old == null;
    }

    @SuppressWarnings("resource")
    public boolean replace(K key, V oldToReplace, V value)
    {
        // if there is no old value in our map, we fail
        RefCountedMemory old = map.get(key);
        if (old == null)
            return false;

        V oldValue;
        // reference old guy before de-serializing
        if (!old.reference())
            return false; // we have already freed hence noop.

        oldValue = deserialize(old);
        old.unreference();

        if (!oldValue.equals(oldToReplace))
            return false;

        // see if the old value matches the one we want to replace
        RefCountedMemory mem = serialize(value);
        if (mem == null)
            return false; // out of memory.  never mind.

        boolean success;
        try
        {
            success = map.replace(key, old, mem);
        }
        catch (Throwable t)
        {
            mem.unreference();
            throw t;
        }

        if (success)
            old.unreference(); // so it will be eventually be cleaned
        else
            mem.unreference();
        return success;
    }

    public void remove(K key)
    {
        @SuppressWarnings("resource")
        RefCountedMemory mem = map.remove(key);
        if (mem != null)
            mem.unreference();
    }

    public Iterator<K> keyIterator()
    {
        return map.keySet().iterator();
    }

    public Iterator<K> hotKeyIterator(int n)
    {
        return map.descendingKeySetWithLimit(n).iterator();
    }

    public boolean containsKey(K key)
    {
        return map.containsKey(key);
    }
}


text:
package com.fishercoder;

import com.fishercoder.common.classes.TreeNode;
import com.fishercoder.solutions._515;
import org.junit.BeforeClass;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;

public class _515Test {
    private static _515.Solution1 solution1;
    private static _515.Solution2 solution2;
    private static List<Integer> expected;
    private static List<Integer> actual;
    private static TreeNode root;

    @BeforeClass
    public static void setup() {
        solution1 = new _515.Solution1();
        solution2 = new _515.Solution2();
    }

    @Test
    public void test1() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(3);
        root.right = new TreeNode(2);
        expected = Arrays.asList(1, 3);
        actual = solution1.largestValues(root);
        assertEquals(expected, actual);

        actual = solution2.largestValues(root);
        assertEquals(expected, actual);
    }

    @Test
    public void test2() {
        expected = new ArrayList<>();
        actual = solution1.largestValues(null);
        assertEquals(expected, actual);

        actual = solution2.largestValues(null);
        assertEquals(expected, actual);
    }
}


text:
#pragma once

#include "Context.h"

extern "C"
{
	D2DLIB_API void DrawLine(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, D2D1_COLOR_F color,
		FLOAT width = 1, D2D1_DASH_STYLE dashStyle = D2D1_DASH_STYLE::D2D1_DASH_STYLE_SOLID,
		D2D1_CAP_STYLE startCap = D2D1_CAP_STYLE::D2D1_CAP_STYLE_FLAT,
		D2D1_CAP_STYLE endCap = D2D1_CAP_STYLE::D2D1_CAP_STYLE_FLAT);

	D2DLIB_API void DrawLineWithPen(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, HANDLE pen, FLOAT width = 1);

	D2DLIB_API void DrawLines(HANDLE ctx, D2D1_POINT_2F* points, UINT count, D2D1_COLOR_F color,
		FLOAT width = 1, D2D1_DASH_STYLE dashStyle = D2D1_DASH_STYLE::D2D1_DASH_STYLE_SOLID);

	D2DLIB_API void DrawRectangle(HANDLE ctx, D2D1_RECT_F* rect, D2D1_COLOR_F color,
		FLOAT width = 1, D2D1_DASH_STYLE dashStyle = D2D1_DASH_STYLE::D2D1_DASH_STYLE_SOLID);

	D2DLIB_API void DrawRectangleWithPen(HANDLE ctx, D2D1_RECT_F* rect, HANDLE strokePen, FLOAT width = 1);

	D2DLIB_API void FillRectangle(HANDLE ctx, D2D1_RECT_F* rect, D2D1_COLOR_F color);

	D2DLIB_API void FillRectangleWithBrush(HANDLE ctx, D2D1_RECT_F* rect, HANDLE brushHandle);

	D2DLIB_API void DrawRoundedRect(HANDLE ctx, D2D1_ROUNDED_RECT* roundedRect, D2D1_COLOR_F strokeColor, D2D1_COLOR_F fillColor,
		FLOAT strokeWidth = 1, D2D1_DASH_STYLE strokeStyle = D2D1_DASH_STYLE::D2D1_DASH_STYLE_SOLID);

	D2DLIB_API void DrawRoundedRectWithBrush(HANDLE ctx, D2D1_ROUNDED_RECT* roundedRect,
		HANDLE strokePen, HANDLE fillBrush, float strokeWidth = 1);

	D2DLIB_API void DrawEllipse(HANDLE ctx, D2D1_ELLIPSE* ellipse, D2D1_COLOR_F color,
		FLOAT width = 1, D2D1_DASH_STYLE dashStyle = D2D1_DASH_STYLE::D2D1_DASH_STYLE_SOLID);

	D2DLIB_API void FillEllipse(HANDLE ctx, D2D1_ELLIPSE* ellipse, D2D1_COLOR_F color);

	D2DLIB_API void FillEllipseWithBrush(HANDLE ctx, D2D1_ELLIPSE* ellipse, HANDLE brush);

}


text:
//
//  web_api_configuration.hpp
//  WorktileCore
//
//  Created by Frank Lin on 10/29/15.
//  Copyright © 2015 Frank Lin. All rights reserved.
//

#ifndef WORKTILECORE_CORE_WEB_API_WEB_API_CONFIGURATION_H_
#define WORKTILECORE_CORE_WEB_API_WEB_API_CONFIGURATION_H_

#include <map>

#include "base/base.h"
#include "web_api/web_api_token.h"

NS_WTC_BEGIN

// |WebApiConfiguration| defines some required property to init |WebApi| and provides some algorithem
//  for |WebApi| when request to Worktile server.
class WebApiConfiguration {
public:

  static const time_t kNow = 0;

  // Creation and lifetime --------------------------------------------------------

  WebApiConfiguration();
  virtual ~WebApiConfiguration();

  // Init with required property, if token is not nullptr, you can use all of |WebApi| methods, but if
  //  token is nullptr, you should sign in to request the token.
  // It is handy for app developer to cache the token in client side.
  void Init(const std::string& app_key,
            const std::string& app_secret,
            const std::string& client_version,
            const std::string& app_channel_name,
            const std::string& api_version,
            const std::string& device_id,
            const WebApiToken* token=nullptr);

  std::unique_ptr<WebApiConfiguration> Clone() const;

  // Json coding --------------------------------------------------------

  void InitWithJson(const std::string& json);
  std::string ToJson() const;

  // Getters/Setters --------------------------------------------------------

  std::string app_key() const { return app_key_; }
  std::string app_secret() const { return app_secret_; }
  std::string client_version() const { return client_version_; }
  std::string app_channel_name() const { return app_channel_name_; }
  std::string api_version() const { return api_version_; }
  std::string device_id() const { return device_id_; }

  const WebApiToken* token() const { return token_.get(); }
  void set_token(const WebApiToken& token) { token_ = token.Clone(); }

  // Header --------------------------------------------------------

  std::map<std::string, std::string> HttpHeaderForSignIn(time_t ts=kNow) const;

  std::map<std::string, std::string> HttpHeaderForHttpMethod(sakura::HttpRequest::Type http_method, time_t ts=kNow) const;

private:
  std::string app_key_;
  std::string app_secret_;
  std::string client_version_;
  std::string app_channel_name_;
  std::string api_version_;
  std::string device_id_;

  std::unique_ptr<WebApiToken> token_;

  // Signature --------------------------------------------------------

  std::string SignatureForHttpMethod(sakura::HttpRequest::Type http_method, time_t ts=kNow) const;

  std::string SignatureForSignIn(time_t ts=kNow) const;

  DISALLOW_COPY_AND_ASSIGN(WebApiConfiguration);
};

NS_WTC_END

#endif /* WORKTILECORE_CORE_WEB_API_WEB_API_CONFIGURATION_H_ */


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit2fd9269d6fd35b0a29895f72d3169d65::getLoader();


text:
import java.lang.Math;
// Don't forget to answer the follow-up question!
public class Bin15 {

    // A string of exactly 15 characters, each a 0 or 1.
    private String myBinStr;

    // A constantly-whining constructor for your testing purposes.
    public Bin15(String input) {

        // Check for null input
        if (input == null) {
            String msg = "Your binary string is null";
            throw new NullPointerException(msg);
        }

        // Check for length
        if (input.length() != 15) {
            String msg = "Your binary string isn't of length 15";
            throw new IllegalArgumentException(msg);
        }

        // Check for illegal characters
        for (int count = 0; count < 15; count++) {
            char c = input.charAt(count);
            // Careful with comparing vs 0 and comparing vs '0'
            if (c != '0' && c != '1') {
                String msg = "Your binary string contains a non-binary character";
                throw new IllegalArgumentException(msg);
            }
        }

        // The input is good. Let's roll.
        this.myBinStr = input;
    }

    @Override
    public boolean equals(Object o) {
        return myBinStr.equals(((Bin15)o).myBinStr);
        //return false; // YOUR CODE HERE
    }

    @Override
    public int hashCode() {
        return 1;
        //return -1; // YOUR CODE HERE
    }

    /* DO THIS LAST, AFTER IMPLEMENTING EVERYTHING
    Follow-up question: The current length of our myBinStr is 15. What is the
    longest length possible for this String such that we still can produce a
    perfect hash (assuming we can rewrite the hash function)? Write your answer
    in the method followUpAnswer().
    */
    public static final int followUpAnswer() {
        return 42; // YOUR CODE HERE. THIS MAY OR MAY NOT BE CORRECT.
    }

    public static void main(String[] args) {
        // Optional testing here. Potentially useless information:
        int c = 0x9 - 1 - 0b01;
        // 0x9 means 9 in hexadecimal
        // 1 means 1 in decimal
        // 0b01 means 01 or 1 in binary
        System.out.println("Note to self: Answer follow-up question!");
    }
}


text:
set -u

cat input.txt | $JOSHUA/bin/joshua-decoder -output-format "%S" -mark-oovs false -top-n 1 > output 2> log

# Compare
diff -u output output.expected > diff

if [ $? -eq 0 ]; then
	rm -f output log diff
	exit 0
else
	exit 1
fi


text:
K9s provides a terminal UI to interact with your Kubernetes clusters.
The aim of this project is to make it easier to navigate, observe and manage
your applications in the wild. K9s continually watches Kubernetes
for changes and offers subsequent commands to interact with your observed resources.

## Features

* Information At Your Finger Tips!
  * Tracks in real-time activities of resources running in your Kubernetes cluster.
* Standard or CRD?
  * Handles booths Kubernetes standard resources as well as custom resource definitions.
* Cluster Metrics
  * Tracks real-time metrics associates with resources such as pods, containers and nodes.
* Power Users Welcome!
  * Provides standard cluster management commands such as logs, scaling, port-forwards, restarts…
  * Define your own command shortcuts for quick navigation via command aliases and hotkeys.
  * Plugin support to extend K9s to create your very own cluster commands.
  * Powerful filtering mode to allow user to drill down and view workload related resources.
* Error Zoom
  * Drill down directly to what's wrong with your cluster's resources.
* Skinnable and Customizable
  * Define your very own look and feel via K9s skins.
Customize/Arrange which columns to display on a per resource basis.
* Narrow or Wide?
  * Provides toggles to view minimal or full resource definitions
* MultiResources Views
  * Provides for an overview of your cluster resources via Pulses and XRay views.
* We've got your RBAC!
  * Supports for viewing RBAC rules such as cluster/roles and their associated bindings.
  * Reverse lookup to asserts what a user/group or serviceAccount can do on your clusters.
* Built-in Benchmarking
  * You can benchmark your HTTP services/pods directly from K9s to see how your application fare and adjust your resources request/limit accordingly.
* Resource Graph Traversals
  * K9s provides for easy traversal of Kubernetes resources and their associated resources.


text:
package info.u250.c2d.engine.resources.rules;

import info.u250.c2d.engine.Engine;
import info.u250.c2d.engine.resources.AliasResourceManager.LoadResourceRule;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
/**
 * @author lycying@gmail.com
 */
public class RuleFont  implements LoadResourceRule{
	@Override
	public boolean match(FileHandle file) {
		boolean result = file.extension().equals("fnt");
		if(result) Engine.getAssetManager().load(file.path().replace("\\", "/"),BitmapFont.class);
		return  result;
	}
}


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

class Torrents extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->utility->enforce_login();
		$this->load->model('torrentmodel');
		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->library('atheme');
	}

	public function index()
	{
		redirect('/torrents/browse/');
	}

	public function browse($page = 1) {
		$this->utility->enforce_perm('site_torrents_search');
		if($page < 1)
			$page = 1;
		$off = ($page - 1) * $this->config->item('torrent_perpage');

		$query = array();

		$query = (count($query)) ? array(($this->input->post('match_method') == 'or' ? '$or' : '$and') => $query) : array();
		$data = array();
		$t = $this->torrentmodel->getTorrents($this->config->item('torrent_perpage'), $off, $query);
		$data['torrents'] = $t['data'];
		$data['perpage'] = $this->config->item('torrent_perpage');
		$data['results'] = $t['count'];
		$data['categories'] = $this->config->item('categories');
		$data['ci'] =& get_instance();
		$data['page'] = $page;
		$data['off'] = $off;
		$data['static_server'] = $this->config->item('static_server');
		$data['cats'] = $this->config->item('categories');
		$data['metadata'] = $this->config->item('metadata');

		$this->utility->page_title('Browse Torrents');
		$this->load->view('torrents/browse', $data);

		//new MongoRegex('/^'.preg_quote($name).'$/i')
	}

	public function upload() {
		$this->utility->enforce_perm('site_torrents_upload');
		$this->utility->page_title('Upload');

		$this->form_validation->set_error_delimiters('
', '
');
		$this->form_validation->set_rules('title', 'title', 'required');
		$this->form_validation->set_rules('type', 'category', 'required');
		$this->form_validation->set_rules('tags[]', 'tags', 'required');
		$this->form_validation->set_rules('description', 'description', 'required');
		$this->form_validation->set_rules('file_input', 'file_input', 'callback__file_upload');

		//metadata based rules
		$c = $this->config->item('categories');
		foreach($c[$this->input->post('type')]['metadata'] as $m) {
			$key = $m;
			$m = $this->config->item('metadata');
			$m = $m[$key];

			$rules = (($m['required'] && !($m['type'] == 2)) ? 'required|' : '');
			switch($m['type']) {
				case 0:
					// no additional rules
					break;
				case 1:
					$rules .= 'is_natural|less_than['.(count($m['enum']) + 1).']';
					break;
				case 2:
					//no additional rules
					break;
			}
			$this->form_validation->set_rules('metadata-'.$key.'[]', '\''.$m['display'].'\'', $rules);
		}

		if(!$this->form_validation->run()) {
			$data = array();
			$data['categories'] = $this->config->item('categories');
			$data['announce'] = $this->config->item('announce_url').'/'.$this->utility->current_user('torrent_pass').'/announce';
			$this->load->view('torrents/upload', $data);
		} else {
			//continue processing on the torrent files
			$data = array();
			$data['name'] = $this->input->post('title');
			$data['owner'] = $this->utility->current_user('_id');
			$data['description'] = $this->input->post('description');
			$data['category'] = $this->input->post('type');
			$data['seeders'] = 0;
			$data['leechers'] = 0;
			$data['snatched'] = 0;
			$data['size'] = $this->totalsize;
			$data['files'] = array();
			foreach($this->files as $f) {
				$data['files'][] = array('name' => $f[1], 'size' => $f[0]);
			}
			$data['time'] = time();
			$img = $this->input->post('image');
			$data['image'] = ($this->utility->is_valid_image($img)) ? $img : '';
			$data['comments'] = array();
			$data['info_hash'] = bin2hex($this->infohash);
			$data['freetorrent'] = ($data['size'] < $this->config->item('freeleech_size')) ? 0 : 1;
			$data['tags'] = array_map("trim", array_filter(explode(',', $this->input->post('tags')), 'trim'));
			$data['metadata'] = array();
			$data['data'] = new MongoBinData($this->torrent->enc());
			$cat = $this->config->item('categories');
			$meta_schema = $this->config->item('metadata');
			$cat = $cat[$data['category']];
			foreach($cat['metadata'] as $m) {
				$schema = $meta_schema[$m];
				$val = $this->input->post('metadata-'.$m);
				if($schema['type'] === 0 && $schema['multiple']) {
					$val = array_map("trim", array_filter(explode(',', $val), 'trim'));
				}
				$val = (is_array($val)) ? $val : array($val);
				$data['metadata'][$m] = $val;
			}
			$this->mongo->db->torrents->save($data);

			$logline = $this->utility->current_user('username').' ('.$this->utility->current_user('_id').') has uploaded torrent '.$data['_id'].' "'.$data['name'].'"';

			// log
			$this->utility->log($logline);

			// IRC announce
			$this->atheme->announce($logline);
			$this->atheme->say('#torrents', $logline);

			redirect('/torrents/view/'.$data['_id']);
		}
	}

	public function _file_upload($file) {
		$file = $_FILES['file_input'];

		if($file['error'] > 2 && $file['error'] != 4) {
			$this->form_validation->set_message('_file_upload', 'An unexpected error has occurred. Please try again. Code: '.$file['error']);
			return false;
		}
		if($file['size'] > $this->config->item('torrent_maxsize') || $file['error'] == 1 || $file['error'] == 2) {
			$this->form_validation->set_message('_file_upload', 'Your torrent file may not be larger than '.$this->utility->format_bytes($file['size']).'. Try increasing your piece size.');
			return false;
		}
		if(!is_uploaded_file($file['tmp_name']) || !filesize($file['tmp_name']) || $file['error'] == 4) {
			$this->form_validation->set_message('_file_upload', 'You must select a file to upload!');
			return false;
		}
		if(end(explode('.', $file['name'])) !== "torrent") {
			$this->form_validation->set_message('_file_upload', 'You have not selected a valid torrent file.');
			return false;
		}

		require(APPPATH.'/libraries/torrent.php');
		$this->torrent = new TORRENT(file_get_contents($file['tmp_name']));
		$this->torrent->make_private();
		$this->torrent->set_announce_url('ANNOUNCE_URL');

		list($totalSize, $files) = $this->torrent->file_list();
		$this->totalsize = $totalSize;
		$this->files = $files;

		$this->infohash = pack("H*", sha1($this->torrent->Val['info']->enc()));
		if($this->torrentmodel->getByInfohash($this->infohash)) {
			$this->form_validation->set_message('_file_upload', 'The same torrent has already been uploaded.');
			return false;
		}

		return true;
	}

	public function view($id = -1, $page = 1) {
		$this->utility->enforce_perm('site_torrents_view');
		$this->load->model('usermodel');
		$this->load->library('textformat');
		$torrent = $this->torrentmodel->getData($id, false);

		if($page < 1)
			$page = 1;
		$off = ($page - 1) * $this->config->item('torrent_comments_perpage');

		if(!$torrent) {
			$this->utility->page_title('Non-existant torrent');
			$this->load->view('torrents/view_dne');
		} else {
			$data = array();
			$data['torrent'] = $torrent;
			$data['owner'] = $this->usermodel->getData($torrent['owner']);
			$data['user'] = $this->utility->current_user();
			$data['categories'] = $this->config->item('categories');
			$data['ci'] =& get_instance();
			$data['can_delete_tags'] = $this->utility->check_perm('site_torrents_tags_delete');
			$data['can_add_tags'] = $this->utility->check_perm('site_torrents_tags_add');
			$data['per_page'] = $this->config->item('torrent_comments_perpage');
			$data['comments'] = $this->torrentmodel->getComments($id, $data['per_page'], $off, false);
			$data['results'] = $data['comments']['length'];
			$data['comments'] = $data['comments']['data'];
			$data['page'] = $page;
			$data['static_server'] = $this->config->item('static_server');

			if($this->input->post('action') == 'reply') {
				$this->utility->enforce_perm('site_torrents_comment');
				$this->form_validation->set_error_delimiters('
', '
');
				$this->form_validation->set_rules('text', 'text', 'required|max_length['.$this->config->item('max_bytes_per_post').']');
				if($this->form_validation->run()) {
					$c = $this->torrentmodel->addComment($id, $this->utility->current_user('_id'), $this->input->post('text'));
					redirect('/torrents/view/'.$id.'/'.ceil(($data['results']+1) / 10).'#post'.$c);
				}
			}

			$this->utility->page_title($data['torrent']['name']);
			$this->load->view('torrents/view', $data);
		}
	}

	public function download($id = -1) {
		$this->utility->enforce_perm('site_torrents_download');
		$this->load->model('usermodel');
		require(APPPATH.'/libraries/torrent.php');

		if(!($data = $this->torrentmodel->getData($id)))
			show_404();

		$tor = new TORRENT($data['data']->bin);
		//$tor->set_announce_url($this->config->item('announce_url').'/'.$this->session->userdata('torrent_pass').'/announce');

		if (!$this->utility->user_setting('download_as_txt')) {
			header('Content-Disposition: attachment; filename="'.$this->utility->torrent_name($id, false).'.torrent"');
			header('Content-Type: application/x-bittorrent');
		} else {
			header('Content-Disposition: attachment; filename="'.$this->utility->torrent_name($id, false).'.txt"');
			header('Content-Type: text/plain');
		}
		echo $tor->enc();
		$this->utility->log($this->utility->current_user('username').' ('.$this->utility->current_user('_id').') downloaded torrent '.$id);
		exit();
	}

	public function tag() {
		$action = $this->input->post('action');
		$id = $this->input->post('id');
		$tag = $this->input->post('tag');
		if(!$this->torrentmodel->getData($id)) {
			show_404();
		}
		if(!$tag) {
			redirect('/torrents/view/'.$id);
		}
		if($action == 'add') {
			$this->utility->enforce_perm('site_torrents_tags_add');
			$this->torrentmodel->addTag($id, $tag);
			redirect('/torrents/view/'.$id);
		} else if($action == 'delete') {
			$this->utility->enforce_perm('site_torrents_tags_delete');
			$this->torrentmodel->removeTag($id, $tag);
			redirect('/torrents/view/'.$id);
		} else {
			show_404();
		}
	}
}


text:
import sys

import mock

from neutron.db import migration
from neutron.db.migration import cli
from neutron.tests import base

class TestDbMigration(base.BaseTestCase):
    def test_should_run_plugin_in_list(self):
        self.assertTrue(migration.should_run('foo', ['foo', 'bar']))
        self.assertFalse(migration.should_run('foo', ['bar']))

    def test_should_run_plugin_wildcard(self):
        self.assertTrue(migration.should_run('foo', ['*']))

class TestCli(base.BaseTestCase):
    def setUp(self):
        super(TestCli, self).setUp()
        self.do_alembic_cmd_p = mock.patch.object(cli, 'do_alembic_command')
        self.do_alembic_cmd = self.do_alembic_cmd_p.start()
        self.addCleanup(self.do_alembic_cmd_p.stop)
        self.addCleanup(cli.CONF.reset)

    def _main_test_helper(self, argv, func_name, exp_args=(), exp_kwargs={}):
        with mock.patch.object(sys, 'argv', argv):
            cli.main()
            self.do_alembic_cmd.assert_has_calls(
                [mock.call(mock.ANY, func_name, *exp_args, **exp_kwargs)]
            )

    def test_stamp(self):
        self._main_test_helper(
            ['prog', 'stamp', 'foo'],
            'stamp',
            ('foo',),
            {'sql': False}
        )

        self._main_test_helper(
            ['prog', 'stamp', 'foo', '--sql'],
            'stamp',
            ('foo',),
            {'sql': True}
        )

    def test_current(self):
        self._main_test_helper(['prog', 'current'], 'current')

    def test_history(self):
        self._main_test_helper(['prog', 'history'], 'history')

    def test_check_migration(self):
        self._main_test_helper(['prog', 'check_migration'], 'branches')

    def test_database_sync_revision(self):
        self._main_test_helper(
            ['prog', 'revision', '--autogenerate', '-m', 'message'],
            'revision',
            (),
            {'message': 'message', 'sql': False, 'autogenerate': True}
        )

        self._main_test_helper(
            ['prog', 'revision', '--sql', '-m', 'message'],
            'revision',
            (),
            {'message': 'message', 'sql': True, 'autogenerate': False}
        )

    def test_upgrade(self):
        self._main_test_helper(
            ['prog', 'upgrade', '--sql', 'head'],
            'upgrade',
            ('head',),
            {'sql': True}
        )

        self._main_test_helper(
            ['prog', 'upgrade', '--delta', '3'],
            'upgrade',
            ('+3',),
            {'sql': False}
        )

    def test_downgrade(self):
        self._main_test_helper(
            ['prog', 'downgrade', '--sql', 'folsom'],
            'downgrade',
            ('folsom',),
            {'sql': True}
        )

        self._main_test_helper(
            ['prog', 'downgrade', '--delta', '2'],
            'downgrade',
            ('-2',),
            {'sql': False}
        )


text:
// Copyright (c) 2011, Chute Corporation. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice, this
//       list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//     * Neither the name of the  Chute Corporation nor the names
//       of its contributors may be used to endorse or promote products derived from
//       this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
//  OF THE POSSIBILITY OF SUCH DAMAGE.
//
package com.chute.sdk.v2.api.flags;

import com.chute.sdk.v2.model.AlbumModel;
import com.chute.sdk.v2.model.AssetModel;
import com.chute.sdk.v2.model.FlagModel;
import com.chute.sdk.v2.model.response.ResponseModel;
import com.dg.libs.rest.HttpRequest;
import com.dg.libs.rest.callbacks.HttpCallback;

/**
 * The {@link GCFlags} class is a helper class which contains static methods for
 * manipulating with flags.
 *

 * Included methods:
 *

 *
Get list of flags
 *
Create a flag
 *
Remove a flag
 *

 *
 */
public class GCFlags {

  public static final String TAG = GCFlags.class.getSimpleName();

  /**
   * Default non-args constructor
   */
  public GCFlags() {
  }

  /**
   * Flags a specific asset in an album.
   *

   * The asset will be marked for the current user executing the requests.
   *
   * @param album
   *          Album containing the flagged asset
   * @param asset
   *          The asset to be flagged.
   * @param callback
   *          Instance of {@link HttpCallback} interface. If successful, the
   *          callback returns {@link ResponseModel<FlagModel>}.
   * @return {@link FlagGetRequest}.
   */
  public static HttpRequest flag(
      final AlbumModel album, final AssetModel asset,
      final HttpCallback<ResponseModel<FlagModel>> callback) {
    return new FlagRequest(album, asset, callback);
  }

  /**
   * Pulls a complete count of all flags associated with an asset in a specific
   * album.
   *
   * @param album
   *          Album that holds the flagged asset.
   * @param asset
   *          The flagged asset.
   * @param callback
   *          Instance of {@link HttpCallback} interface. If successful, the
   *          callback returns {@link ResponseModel<FlagModel>}.
   * @return {@link FlagGetRequest}.
   */
  public static HttpRequest get(
      final AlbumModel album, final AssetModel asset,
      final HttpCallback<ResponseModel<FlagModel>> callback) {
    return new FlagGetRequest(album, asset, callback);
  }

  /**
   * Removes flag from an asset in a specific album.
   *
   * @param album
   *          Album holding the flagged asset.
   * @param asset
   *          The asset whose flag is about to be removed.
   * @param callback
   *          Instance of {@link HttpCallback} interface. If successful, the
   *          callback returns {@link ResponseModel<FlagModel>}.
   * @return {@link UnflagRequest}.
   */
  public static HttpRequest unflag(
      final AlbumModel album, final AssetModel asset,
      final HttpCallback<ResponseModel<FlagModel>> callback) {
    return new UnflagRequest(album, asset, callback);

  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: francics <allenfrancics@foxmail.com>
 * Date: 2016/5/15
 * Time: 19:57
 */
namespace wechat\components;

use Yii;

class ResizeImage
{
    public static function resize($username, $src, $width, $height, $level = 75, $mode = 'crop')
    {
        header("content-type: image/jpeg");
        ini_set("gd.jpeg_ignore_warning", true);
        $newDir = $username . '/' . $width . '_' . $height;
        $attachmentDir = Yii::getAlias("@attachment/web/attachment/" . $username . '/' . $width . '_' . $height);
        if (!file_exists($attachmentDir)) {
            mkdir($attachmentDir, 0777, true);
            chmod($attachmentDir, 0777);
        }
        $file = Yii::getAlias("@frontend/web/") . $src;

        $newImg = $attachmentDir . '/' . basename($src);

        if (!file_exists($newImg)) {
            self::resizeMode($file, $newImg, $width, $height, $level, $mode);
        }
        return Yii::$app->params ['prefixUploadUrl'] . $newDir . '/' . basename($src);
    }

    /**
     * 图片切割方式
     * 更多方式参考https://github.com/yurkinx/yii2-image
     * @param string $file
     * @param string $img
     * @param integer $width
     * @param integer $height
     * @param integer $level
     * @param string $type
     * @return boolean
     */
    public static function resizeMode($file, $img, $width, $height, $level, $mode)
    {
        switch ($mode) {
            case 'crop' :
                $image = Yii::$app->image->load($file);
                return $image->resize($width, $height, $image::CROP)->background('#fff')->save($img, $level);
                break;
            case 'horizontal' :
                $image = Yii::$app->image->load($file);
                return $image->resize($width, $height, $image::HORIZONTAL)->background('#fff')->save($img, $level);
                break;
            case 'height' :
                $image = Yii::$app->image->load($file);
                return $image->resize($width, $height, $image::HEIGHT)->background('#fff')->save($img, $level);
                break;
            case 'adapt' :
                $image = Yii::$app->image->load($file);
                return $image->resize($width, $height, $image::ADAPT)->background('#fff')->save($img, $level);
                break;
            default :
                $image = Yii::$app->image->load($file);
                return $image->resize($width, $height, $image::ADAPT)->background('#fff')->save($img, $level);
                break;
        }
    }
}