text:
/*	$NetBSD: ntp_timer.c,v 1.1.1.3.4.1 2014/12/24 00:05:21 riz Exp $	*/

/*
 * ntp_timer.c - event timer support routines
 */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "ntp_machine.h"
#include "ntpd.h"
#include "ntp_stdlib.h"
#include "ntp_calendar.h"
#include "ntp_leapsec.h"

#if defined(HAVE_IO_COMPLETION_PORT)
# include "ntp_iocompletionport.h"
# include "ntp_timer.h"
#endif

#include <stdio.h>
#include <signal.h>
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#ifdef KERNEL_PLL
#include "ntp_syscall.h"
#endif /* KERNEL_PLL */

#ifdef AUTOKEY
#include <openssl/rand.h>
#endif	/* AUTOKEY */

/* TC_ERR represents the timer_create() error return value. */
#ifdef SYS_VXWORKS
#define	TC_ERR	ERROR
#else
#define	TC_ERR	(-1)
#endif

static void check_leapsec(u_int32, const time_t*, int/*BOOL*/);

/*
 * These routines provide support for the event timer.  The timer is
 * implemented by an interrupt routine which sets a flag once every
 * second, and a timer routine which is called when the mainline code
 * gets around to seeing the flag.  The timer routine dispatches the
 * clock adjustment code if its time has come, then searches the timer
 * queue for expiries which are dispatched to the transmit procedure.
 * Finally, we call the hourly procedure to do cleanup and print a
 * message.
 */
volatile int interface_interval;     /* init_io() sets def. 300s */

/*
 * Alarm flag. The mainline code imports this.
 */
volatile int alarm_flag;

/*
 * The counters and timeouts
 */
static  u_long interface_timer;	/* interface update timer */
static	u_long adjust_timer;	/* second timer */
static	u_long stats_timer;	/* stats timer */
static	u_long leapf_timer;	/* Report leapfile problems once/day */
static	u_long huffpuff_timer;	/* huff-n'-puff timer */
static	u_long worker_idle_timer;/* next check for idle intres */
u_long	leapsec;	        /* seconds to next leap (proximity class) */
int     leapdif;                /* TAI difference step at next leap second*/
u_long	orphwait; 		/* orphan wait time */
#ifdef AUTOKEY
static	u_long revoke_timer;	/* keys revoke timer */
static	u_long keys_timer;	/* session key timer */
u_long	sys_revoke = KEY_REVOKE; /* keys revoke timeout (log2 s) */
u_long	sys_automax = NTP_AUTOMAX; /* key list timeout (log2 s) */
#endif	/* AUTOKEY */

/*
 * Statistics counter for the interested.
 */
volatile u_long alarm_overflow;

u_long current_time;		/* seconds since startup */

/*
 * Stats.  Number of overflows and number of calls to transmit().
 */
u_long timer_timereset;
u_long timer_overflows;
u_long timer_xmtcalls;

#if defined(VMS)
static int vmstimer[2]; 	/* time for next timer AST */
static int vmsinc[2];		/* timer increment */
#endif /* VMS */

#ifdef SYS_WINNT
HANDLE WaitableTimerHandle;
#else
static	RETSIGTYPE alarming (int);
#endif /* SYS_WINNT */

#if !defined(VMS)
# if !defined SYS_WINNT || defined(SYS_CYGWIN32)
#  ifdef HAVE_TIMER_CREATE
static timer_t timer_id;
typedef struct itimerspec intervaltimer;
#   define	itv_frac	tv_nsec
#  else
typedef struct itimerval intervaltimer;
#   define	itv_frac	tv_usec
#  endif
intervaltimer itimer;
# endif
#endif

#if !defined(SYS_WINNT) && !defined(VMS)
void	set_timer_or_die(const intervaltimer *);
#endif

#if !defined(SYS_WINNT) && !defined(VMS)
void
set_timer_or_die(
	const intervaltimer *	ptimer
	)
{
	const char *	setfunc;
	int		rc;

# ifdef HAVE_TIMER_CREATE
	setfunc = "timer_settime";
	rc = timer_settime(timer_id, 0, &itimer, NULL);
# else
	setfunc = "setitimer";
	rc = setitimer(ITIMER_REAL, &itimer, NULL);
# endif
	if (-1 == rc) {
		msyslog(LOG_ERR, "interval timer %s failed, %m",
			setfunc);
		exit(1);
	}
}
#endif	/* !SYS_WINNT && !VMS */

/*
 * reinit_timer - reinitialize interval timer after a clock step.
 */
void
reinit_timer(void)
{
#if !defined(SYS_WINNT) && !defined(VMS)
	ZERO(itimer);
# ifdef HAVE_TIMER_CREATE
	timer_gettime(timer_id, &itimer);
# else
	getitimer(ITIMER_REAL, &itimer);
# endif
	if (itimer.it_value.tv_sec < 0 ||
	    itimer.it_value.tv_sec > (1 << EVENT_TIMEOUT))
		itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
	if (itimer.it_value.itv_frac < 0)
		itimer.it_value.itv_frac = 0;
	if (0 == itimer.it_value.tv_sec &&
	    0 == itimer.it_value.itv_frac)
		itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
	itimer.it_interval.tv_sec = (1 << EVENT_TIMEOUT);
	itimer.it_interval.itv_frac = 0;
	set_timer_or_die(&itimer);
# endif /* VMS */
}

/*
 * init_timer - initialize the timer data structures
 */
void
init_timer(void)
{
	/*
	 * Initialize...
	 */
	alarm_flag = FALSE;
	alarm_overflow = 0;
	adjust_timer = 1;
	stats_timer = SECSPERHR;
	leapf_timer = SECSPERDAY;
	huffpuff_timer = 0;
	interface_timer = 0;
	current_time = 0;
	timer_overflows = 0;
	timer_xmtcalls = 0;
	timer_timereset = 0;

#ifndef SYS_WINNT
	/*
	 * Set up the alarm interrupt.	The first comes 2**EVENT_TIMEOUT
	 * seconds from now and they continue on every 2**EVENT_TIMEOUT
	 * seconds.
	 */
# ifndef VMS
#  ifdef HAVE_TIMER_CREATE
	if (TC_ERR == timer_create(CLOCK_REALTIME, NULL, &timer_id)) {
		msyslog(LOG_ERR, "timer_create failed, %m");
		exit(1);
	}
#  endif
	signal_no_reset(SIGALRM, alarming);
	itimer.it_interval.tv_sec =
		itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
	itimer.it_interval.itv_frac = itimer.it_value.itv_frac = 0;
	set_timer_or_die(&itimer);
# else	/* VMS follows */
	vmsinc[0] = 10000000;		/* 1 sec */
	vmsinc[1] = 0;
	lib$emul(&(1<<EVENT_TIMEOUT), &vmsinc, &0, &vmsinc);

	sys$gettim(&vmstimer);	/* that's "now" as abstime */

	lib$addx(&vmsinc, &vmstimer, &vmstimer);
	sys$setimr(0, &vmstimer, alarming, alarming, 0);
# endif	/* VMS */
#else	/* SYS_WINNT follows */
	/*
	 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
	 * Under Windows/NT,
	 */

	WaitableTimerHandle = CreateWaitableTimer(NULL, FALSE, NULL);
	if (WaitableTimerHandle == NULL) {
		msyslog(LOG_ERR, "CreateWaitableTimer failed: %m");
		exit(1);
	}
	else {
		DWORD		Period;
		LARGE_INTEGER	DueTime;
		BOOL		rc;

		Period = (1 << EVENT_TIMEOUT) * 1000;
		DueTime.QuadPart = Period * 10000i64;
		rc = SetWaitableTimer(WaitableTimerHandle, &DueTime,
				      Period, NULL, NULL, FALSE);
		if (!rc) {
			msyslog(LOG_ERR, "SetWaitableTimer failed: %m");
			exit(1);
		}
	}

#endif	/* SYS_WINNT */
}

/*
 * intres_timeout_req(s) is invoked in the parent to schedule an idle
 * timeout to fire in s seconds, if not reset earlier by a call to
 * intres_timeout_req(0), which clears any pending timeout.  When the
 * timeout expires, worker_idle_timer_fired() is invoked (again, in the
 * parent).
 *
 * sntp and ntpd each provide implementations adapted to their timers.
 */
void
intres_timeout_req(
	u_int	seconds		/* 0 cancels */
	)
{
	if (0 == seconds) {
		worker_idle_timer = 0;
		return;
	}
	worker_idle_timer = current_time + seconds;
}

/*
 * timer - event timer
 */
void
timer(void)
{
	struct peer *	p;
	struct peer *	next_peer;
	l_fp		now;
	time_t          tnow;

	/*
	 * The basic timerevent is one second.  This is used to adjust the
	 * system clock in time and frequency, implement the kiss-o'-death
	 * function and the association polling function.
	 */
	current_time++;
	if (adjust_timer <= current_time) {
		adjust_timer += 1;
		adj_host_clock();
#ifdef REFCLOCK
		for (p = peer_list; p != NULL; p = next_peer) {
			next_peer = p->p_link;
			if (FLAG_REFCLOCK & p->flags)
				refclock_timer(p);
		}
#endif /* REFCLOCK */
	}

	/*
	 * Now dispatch any peers whose event timer has expired. Be
	 * careful here, since the peer structure might go away as the
	 * result of the call.
	 */
	for (p = peer_list; p != NULL; p = next_peer) {
		next_peer = p->p_link;

		/*
		 * Restrain the non-burst packet rate not more
		 * than one packet every 16 seconds. This is
		 * usually tripped using iburst and minpoll of
		 * 128 s or less.
		 */
		if (p->throttle > 0)
			p->throttle--;
		if (p->nextdate <= current_time) {
#ifdef REFCLOCK
			if (FLAG_REFCLOCK & p->flags)
				refclock_transmit(p);
			else
#endif	/* REFCLOCK */
				transmit(p);
		}
	}

	/*
	 * Orphan mode is active when enabled and when no servers less
	 * than the orphan stratum are available. A server with no other
	 * synchronization source is an orphan. It shows offset zero and
	 * reference ID the loopback address.
	 */
	if (sys_orphan < STRATUM_UNSPEC && sys_peer == NULL &&
	    current_time > orphwait) {
		if (sys_leap == LEAP_NOTINSYNC) {
			sys_leap = LEAP_NOWARNING;
#ifdef AUTOKEY
			if (crypto_flags)
				crypto_update();
#endif	/* AUTOKEY */
		}
		sys_stratum = (u_char)sys_orphan;
		if (sys_stratum > 1)
			sys_refid = htonl(LOOPBACKADR);
		else
			memcpy(&sys_refid, "LOOP", 4);
		sys_offset = 0;
		sys_rootdelay = 0;
		sys_rootdisp = 0;
	}

	get_systime(&now);
	time(&tnow);

	/*
	 * Leapseconds. Get time and defer to worker if either something
	 * is imminent or every 8th second.
	 */
	if (leapsec > LSPROX_NOWARN || 0 == (current_time & 7))
		check_leapsec(now.l_ui, &tnow,
                                (sys_leap == LEAP_NOTINSYNC));
        if (sys_leap != LEAP_NOTINSYNC) {
                if (leapsec >= LSPROX_ANNOUNCE && leapdif) {
		        if (leapdif > 0)
			        sys_leap = LEAP_ADDSECOND;
		        else
			        sys_leap = LEAP_DELSECOND;
                } else {
                        sys_leap = LEAP_NOWARNING;
                }
	}

	/*
	 * Update huff-n'-puff filter.
	 */
	if (huffpuff_timer <= current_time) {
		huffpuff_timer += HUFFPUFF;
		huffpuff();
	}

#ifdef AUTOKEY
	/*
	 * Garbage collect expired keys.
	 */
	if (keys_timer <= current_time) {
		keys_timer += 1 << sys_automax;
		auth_agekeys();
	}

	/*
	 * Generate new private value. This causes all associations
	 * to regenerate cookies.
	 */
	if (revoke_timer && revoke_timer <= current_time) {
		revoke_timer += 1 << sys_revoke;
		RAND_bytes((u_char *)&sys_private, 4);
	}
#endif	/* AUTOKEY */

	/*
	 * Interface update timer
	 */
	if (interface_interval && interface_timer <= current_time) {
		timer_interfacetimeout(current_time +
		    interface_interval);
		DPRINTF(2, ("timer: interface update\n"));
		interface_update(NULL, NULL);
	}

	if (worker_idle_timer && worker_idle_timer <= current_time)
		worker_idle_timer_fired();

	/*
	 * Finally, write hourly stats and do the hourly
	 * and daily leapfile checks.
	 */
	if (stats_timer <= current_time) {
		stats_timer += SECSPERHR;
		write_stats();
		if (leapf_timer <= current_time) {
			leapf_timer += SECSPERDAY;
			check_leap_file(TRUE, now.l_ui, &tnow);
		} else {
			check_leap_file(FALSE, now.l_ui, &tnow);
		}
	}
}

#ifndef SYS_WINNT
/*
 * alarming - tell the world we've been alarmed
 */
static RETSIGTYPE
alarming(
	int sig
	)
{
# ifdef DEBUG
	const char *msg = "alarming: initializing TRUE\n";
# endif

	if (!initializing) {
		if (alarm_flag) {
			alarm_overflow++;
# ifdef DEBUG
			msg = "alarming: overflow\n";
# endif
		} else {
# ifndef VMS
			alarm_flag++;
# else
			/* VMS AST routine, increment is no good */
			alarm_flag = 1;
# endif
# ifdef DEBUG
			msg = "alarming: normal\n";
# endif
		}
	}
# ifdef VMS
	lib$addx(&vmsinc, &vmstimer, &vmstimer);
	sys$setimr(0, &vmstimer, alarming, alarming, 0);
# endif
# ifdef DEBUG
	if (debug >= 4)
		write(1, msg, strlen(msg));
# endif
}
#endif /* SYS_WINNT */

void
timer_interfacetimeout(u_long timeout)
{
	interface_timer = timeout;
}

/*
 * timer_clr_stats - clear timer module stat counters
 */
void
timer_clr_stats(void)
{
	timer_overflows = 0;
	timer_xmtcalls = 0;
	timer_timereset = current_time;
}

static void
check_leapsec(
	u_int32        now  ,
	const time_t * tpiv ,
        int/*BOOL*/    reset)
{
	leap_result_t lsdata;
	u_int32       lsprox;

#ifndef SYS_WINNT  /* WinNT port has its own leap second handling */
# ifdef KERNEL_PLL
	leapsec_electric(pll_control && kern_enable);
# else
	leapsec_electric(0);
# endif
#endif
	if (reset)	{
		lsprox = LSPROX_NOWARN;
		leapsec_reset_frame();
		memset(&lsdata, 0, sizeof(lsdata));
	} else if (leapsec_query(&lsdata, now, tpiv)) {
		/* Full hit. Eventually step the clock, but always
		 * announce the leap event has happened.
		 */
		if (lsdata.warped < 0) {
			step_systime(lsdata.warped);
			msyslog(LOG_NOTICE, "Inserting positive leap second.");
		} else 	if (lsdata.warped > 0) {
			step_systime(lsdata.warped);
			msyslog(LOG_NOTICE, "Inserting negative leap second.");
		}
		report_event(EVNT_LEAP, NULL, NULL);
		lsprox  = LSPROX_NOWARN;
		leapsec = LSPROX_NOWARN;
		sys_tai = lsdata.tai_offs;
	} else {
		lsprox  = lsdata.proximity;
		sys_tai = lsdata.tai_offs;
	}

	/* We guard against panic alarming during the red alert phase.
	 * Strange and evil things might happen if we go from stone cold
	 * to piping hot in one step. If things are already that wobbly,
	 * we let the normal clock correction take over, even if a jump
	 * is involved.
         * Also make sure the alarming events are edge-triggered, that is,
         * ceated only when the threshold is crossed.
         */
	if (  (leapsec > 0 || lsprox < LSPROX_ALERT)
	    && leapsec < lsprox                     ) {
		if (  leapsec < LSPROX_SCHEDULE
                   && lsprox >= LSPROX_SCHEDULE) {
			if (lsdata.dynamic)
				report_event(PEVNT_ARMED, sys_peer, NULL);
			else
				report_event(EVNT_ARMED, NULL, NULL);
		}
		leapsec = lsprox;
	}
	if (leapsec > lsprox) {
		if (  leapsec >= LSPROX_SCHEDULE
                   && lsprox   < LSPROX_SCHEDULE) {
			report_event(EVNT_DISARMED, NULL, NULL);
		}
		leapsec = lsprox;
	}

        if (leapsec >= LSPROX_SCHEDULE)
                leapdif = lsdata.tai_diff;
        else
                leapdif = 0;
}


text:
module AlertsHelper
  def all_alerts
    flash_alerts + model_alerts
  end

  def flash_alerts
    flash.map { |key,val| {type: key, message: val} }
  end

  def model_alerts(model = nil)
    model ||= instance_variable_get("@#{controller_name.singularize}")

    return [] if model.nil?

    model.errors.full_messages.map { |msg| {type: :error, message: msg} }
  end

  def alert_icon(type)
    case type.to_s.to_sym
    when :error, :alert
      'fa fa-exclamation-circle'
    when :warn, :warning
      'fa fa-warning'
    else
      'fa fa-info-circle'
    end
  end

  def alert_class(type)
    case type.to_s.to_sym
    when :error, :alert
      'alert-danger'
    when :warn, :warning
      'alert-warning' # default yellow
    else
      'alert-info'
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
Hudson 1.20 en vroeger gebruikten redundante folders in de werkplaats.
Vb. indien de 'cvs' modulenaam "foo/bar" is, dan werd eerst "foo/bar" gecre�erd.  Om vervolgens alles onder die folder te plaatsen.
Indien u deze optie afvinkt, dan worden deze onnodige tussenliggende folders niet meer aangemaakt.

Merk wel op dat dit invloed heeft op andere plaatsen in uw configuratie, waar u paden opgegeven hebt.  U dient bvb. "build/foo.jar" op te geven i.p.v.  "foo/build/foo.jar".


text:
+++
Title = "Moises Margotto"
Twitter = ""
image = "moises-margotto.jpg"
type = "speaker"
linktitle = "moises-margotto"

+++


text:
'''

@author: Lei Liu
'''
import os.path
import zstacklib.utils.linux as linux
import zstacklib.utils.http as  http
import zstacktestagent.plugins.host as host_plugin
import zstacktestagent.testagent as testagent

import zstackwoodpecker.operations.scenario_operations as scenario_operations
import zstackwoodpecker.operations.deploy_operations as deploy_operations
import zstackwoodpecker.operations.config_operations as config_operations
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.tag_operations as tag_ops

USER_PATH = os.path.expanduser('~')
EXTRA_SUITE_SETUP_SCRIPT = '%s/.zstackwoodpecker/extra_suite_setup_config.sh' % USER_PATH
EXTRA_HOST_SETUP_SCRIPT = '%s/.zstackwoodpecker/extra_host_setup_config.sh' % USER_PATH

def test():
    if test_lib.scenario_config != None and test_lib.scenario_file != None and not os.path.exists(test_lib.scenario_file):
        scenario_operations.deploy_scenario(test_lib.all_scenario_config, test_lib.scenario_file, test_lib.deploy_config)
        test_util.test_skip('Suite Setup Success')
    if test_lib.scenario_config != None and test_lib.scenario_destroy != None:
        scenario_operations.destroy_scenario(test_lib.all_scenario_config, test_lib.scenario_destroy)

    nic_name = "eth0"
    if test_lib.scenario_config != None and test_lib.scenario_file != None and os.path.exists(test_lib.scenario_file):
        nic_name = "zsn0"

    #This vlan creation is not a must, if testing is under nested virt env. But it is required on physical host without enough physcial network devices and your test execution machine is not the same one as Host machine.
    #no matter if current host is a ZStest host, we need to create 2 vlan devs for future testing connection for novlan test cases.
    linux.create_vlan_eth(nic_name, 10)
    linux.create_vlan_eth(nic_name, 11)

    #If test execution machine is not the same one as Host machine, deploy work is needed to separated to 2 steps(deploy_test_agent, execute_plan_without_deploy_test_agent). And it can not directly call SetupAction.run()
    test_lib.setup_plan.deploy_test_agent()
    cmd = host_plugin.CreateVlanDeviceCmd()
    cmd.ethname = nic_name
    cmd.vlan = 10

    cmd2 = host_plugin.CreateVlanDeviceCmd()
    cmd2.ethname = nic_name
    cmd2.vlan = 11
    testHosts = test_lib.lib_get_all_hosts_from_plan()
    if type(testHosts) != type([]):
        testHosts = [testHosts]
    for host in testHosts:
        http.json_dump_post(testagent.build_http_path(host.managementIp_, host_plugin.CREATE_VLAN_DEVICE_PATH), cmd)
        http.json_dump_post(testagent.build_http_path(host.managementIp_, host_plugin.CREATE_VLAN_DEVICE_PATH), cmd2)

    test_lib.setup_plan.execute_plan_without_deploy_test_agent()
    if test_lib.scenario_config != None and test_lib.scenario_file != None and os.path.exists(test_lib.scenario_file):
        mn_ips = deploy_operations.get_nodes_from_scenario_file(test_lib.all_scenario_config, test_lib.scenario_file, test_lib.deploy_config)
        if os.path.exists(EXTRA_SUITE_SETUP_SCRIPT):
            os.system("bash %s '%s'" % (EXTRA_SUITE_SETUP_SCRIPT, mn_ips))
    elif os.path.exists(EXTRA_SUITE_SETUP_SCRIPT):
        os.system("bash %s" % (EXTRA_SUITE_SETUP_SCRIPT))

    deploy_operations.deploy_initial_database(test_lib.deploy_config, test_lib.all_scenario_config, test_lib.scenario_file)
    for host in testHosts:
        os.system("bash %s %s" % (EXTRA_HOST_SETUP_SCRIPT, host.managementIp_))

    mn_ip = res_ops.query_resource(res_ops.MANAGEMENT_NODE)[0].hostName
    if test_lib.ver_ge_zstack_2_0(mn_ip):
        test_lib.lib_set_allow_live_migration_local_storage('true')
    #test_lib.lib_set_primary_storage_imagecache_gc_interval(1)
    test_lib.ensure_recover_script_l2_correct()

    if test_lib.lib_is_storage_network_separate():
        add_ps_network_gateway_sys_tag()

    test_util.test_pass('Suite Setup Success')


text:
/*****************************************************************
IMPORT COMPASS
- If you don't have Compass you can create your own mixins
for CSS3 or use bourbon etc.
******************************************************************/
/******************************************************************
IMPORT SHADOW TYPES
******************************************************************/
/******************************************************************
SHADOW MIXINS
******************************************************************/
/******************************************************************
SHADOW CLASSES
******************************************************************/
/* line 53, ../scss/shadows.scss */
.shadow.lifted { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.lifted:before, .shadow.lifted:after { position: absolute; z-index: -2; content: ""; }
/* line 2, ../scss/_shadow-types.scss */
.shadow.lifted:before, .shadow.lifted:after { bottom: 12px; width: 50%; height: 55%; max-width: 300px; max-height: 100px; -webkit-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7); -moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7); box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7); }
/* line 11, ../scss/_shadow-types.scss */
.shadow.lifted:before { left: 10px; -webkit-transform: rotate(-3deg); -moz-transform: rotate(-3deg); -ms-transform: rotate(-3deg); -o-transform: rotate(-3deg); transform: rotate(-3deg); }
/* line 12, ../scss/_shadow-types.scss */
.shadow.lifted:after { right: 10px; -webkit-transform: rotate(3deg); -moz-transform: rotate(3deg); -ms-transform: rotate(3deg); -o-transform: rotate(3deg); transform: rotate(3deg); }

/* line 53, ../scss/shadows.scss */
.shadow.raised { position: relative; -webkit-box-shadow: 0 15px 10px -10px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 15px 10px -10px rgba(0, 0, 0, 0.5); box-shadow: 0 15px 10px -10px rgba(0, 0, 0, 0.5); }
/* line 19, ../scss/shadows.scss */
.shadow.raised:before, .shadow.raised:after { position: absolute; z-index: -2; content: ""; }
/* line 48, ../scss/_shadow-types.scss */
.shadow.raised:before, .shadow.raised:after { content: none; }

/* line 53, ../scss/shadows.scss */
.shadow.perspective { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.perspective:before, .shadow.perspective:after { position: absolute; z-index: -2; content: ""; }
/* line 16, ../scss/_shadow-types.scss */
.shadow.perspective:before { left: 80px; bottom: 5px; width: 50%; height: 35%; max-width: 200px; max-height: 50px; -webkit-box-shadow: -80px 0 8px rgba(0, 0, 0, 0.4); -moz-box-shadow: -80px 0 8px rgba(0, 0, 0, 0.4); box-shadow: -80px 0 8px rgba(0, 0, 0, 0.4); -webkit-transform: skew(50deg, 0); -moz-transform: skew(50deg, 0); -ms-transform: skew(50deg, 0); -o-transform: skew(50deg, 0); transform: skew(50deg, 0); -webkit-transform-origin: 0 100%; -moz-transform-origin: 0 100%; -ms-transform-origin: 0 100%; -o-transform-origin: 0 100%; transform-origin: 0 100%; }
/* line 26, ../scss/_shadow-types.scss */
.shadow.perspective:after { display: none; content: none; }

/* line 53, ../scss/shadows.scss */
.shadow.perspective-right { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.perspective-right:before, .shadow.perspective-right:after { position: absolute; z-index: -2; content: ""; }
/* line 30, ../scss/_shadow-types.scss */
.shadow.perspective-right:before { right: 80px; bottom: 5px; width: 50%; height: 35%; max-width: 200px; max-height: 50px; -webkit-box-shadow: 80px 0 8px rgba(0, 0, 0, 0.4); -moz-box-shadow: 80px 0 8px rgba(0, 0, 0, 0.4); box-shadow: 80px 0 8px rgba(0, 0, 0, 0.4); -webkit-transform: skew(-50deg, 0); -moz-transform: skew(-50deg, 0); -ms-transform: skew(-50deg, 0); -o-transform: skew(-50deg, 0); transform: skew(-50deg, 0); -webkit-transform-origin: 0 100%; -moz-transform-origin: 0 100%; -ms-transform-origin: 0 100%; -o-transform-origin: 0 100%; transform-origin: 0 100%; }
/* line 40, ../scss/_shadow-types.scss */
.shadow.perspective-right:after { display: none; content: none; }

/* line 53, ../scss/shadows.scss */
.shadow.curved { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.curved:before, .shadow.curved:after { position: absolute; z-index: -2; content: ""; }
/* line 54, ../scss/_shadow-types.scss */
.shadow.curved:before { top: 1px; bottom: 0; left: 12px; right: 12px; -webkit-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-border-radius: 150px/10px; border-radius: 150px/10px; }

/* line 53, ../scss/shadows.scss */
.shadow.curved-top { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.curved-top:before, .shadow.curved-top:after { position: absolute; z-index: -2; content: ""; }
/* line 54, ../scss/_shadow-types.scss */
.shadow.curved-top:before { top: 1px; bottom: 0; left: 12px; right: 12px; -webkit-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-border-radius: 150px/10px; border-radius: 150px/10px; }
/* line 67, ../scss/_shadow-types.scss */
.shadow.curved-top:before { bottom: 50%; }

/* line 53, ../scss/shadows.scss */
.shadow.curved-bottom { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.curved-bottom:before, .shadow.curved-bottom:after { position: absolute; z-index: -2; content: ""; }
/* line 54, ../scss/_shadow-types.scss */
.shadow.curved-bottom:before { top: 1px; bottom: 0; left: 12px; right: 12px; -webkit-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-border-radius: 150px/10px; border-radius: 150px/10px; }
/* line 75, ../scss/_shadow-types.scss */
.shadow.curved-bottom:before { top: 50%; }

/* line 53, ../scss/shadows.scss */
.shadow.curved-vertical { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.curved-vertical:before, .shadow.curved-vertical:after { position: absolute; z-index: -2; content: ""; }
/* line 81, ../scss/_shadow-types.scss */
.shadow.curved-vertical:before { top: 10px; bottom: 10px; left: 0; right: 0%; -webkit-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-border-radius: 10px/100px; border-radius: 10px/100px; }

/* line 53, ../scss/shadows.scss */
.shadow.curved-vertical-left { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.curved-vertical-left:before, .shadow.curved-vertical-left:after { position: absolute; z-index: -2; content: ""; }
/* line 81, ../scss/_shadow-types.scss */
.shadow.curved-vertical-left:before { top: 10px; bottom: 10px; left: 0; right: 0%; -webkit-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-border-radius: 10px/100px; border-radius: 10px/100px; }
/* line 94, ../scss/_shadow-types.scss */
.shadow.curved-vertical-left:before { right: 50%; }

/* line 53, ../scss/shadows.scss */
.shadow.curved-vertical-right { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow.curved-vertical-right:before, .shadow.curved-vertical-right:after { position: absolute; z-index: -2; content: ""; }
/* line 81, ../scss/_shadow-types.scss */
.shadow.curved-vertical-right:before { top: 10px; bottom: 10px; left: 0; right: 0%; -webkit-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); box-shadow: 0 0 13px 4px rgba(0, 0, 0, 0.5); -moz-border-radius: 10px/100px; border-radius: 10px/100px; }
/* line 102, ../scss/_shadow-types.scss */
.shadow.curved-vertical-right:before { left: 50%; }

/* line 63, ../scss/shadows.scss */
.shadow:not(.lifted):not(.raised):not(.perspective):not(.perspective-right):not(.curved):not(.curved-top):not(.curved-bottom):not(.curved-vertical):not(.curved-vertical-left):not(.curved-vertical-right) { position: relative; }
/* line 19, ../scss/shadows.scss */
.shadow:not(.lifted):not(.raised):not(.perspective):not(.perspective-right):not(.curved):not(.curved-top):not(.curved-bottom):not(.curved-vertical):not(.curved-vertical-left):not(.curved-vertical-right):before, .shadow:not(.lifted):not(.raised):not(.perspective):not(.perspective-right):not(.curved):not(.curved-top):not(.curved-bottom):not(.curved-vertical):not(.curved-vertical-left):not(.curved-vertical-right):after { position: absolute; z-index: -2; content: ""; }
/* line 2, ../scss/_shadow-types.scss */
.shadow:not(.lifted):not(.raised):not(.perspective):not(.perspective-right):not(.curved):not(.curved-top):not(.curved-bottom):not(.curved-vertical):not(.curved-vertical-left):not(.curved-vertical-right):before, .shadow:not(.lifted):not(.raised):not(.perspective):not(.perspective-right):not(.curved):not(.curved-top):not(.curved-bottom):not(.curved-vertical):not(.curved-vertical-left):not(.curved-vertical-right):after { bottom: 12px; width: 50%; height: 55%; max-width: 300px; max-height: 100px; -webkit-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7); -moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7); box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7); }
/* line 11, ../scss/_shadow-types.scss */
.shadow:not(.lifted):not(.raised):not(.perspective):not(.perspective-right):not(.curved):not(.curved-top):not(.curved-bottom):not(.curved-vertical):not(.curved-vertical-left):not(.curved-vertical-right):before { left: 10px; -webkit-transform: rotate(-3deg); -moz-transform: rotate(-3deg); -ms-transform: rotate(-3deg); -o-transform: rotate(-3deg); transform: rotate(-3deg); }
/* line 12, ../scss/_shadow-types.scss */
.shadow:not(.lifted):not(.raised):not(.perspective):not(.perspective-right):not(.curved):not(.curved-top):not(.curved-bottom):not(.curved-vertical):not(.curved-vertical-left):not(.curved-vertical-right):after { right: 10px; -webkit-transform: rotate(3deg); -moz-transform: rotate(3deg); -ms-transform: rotate(3deg); -o-transform: rotate(3deg); transform: rotate(3deg); }


text:
import * as React from "react";
import Slider from "react-slick";

const preload: (src: string) => void = ((): ((src: string) => void) => {
  const preloaded: { [src: string]: boolean } = {};

  return (src: string): void => {
    if (preloaded[src]) {
      return;
    }
    const img = new Image();
    img.onload = (): void => {
      preloaded[src] = true;
      console.log("Preloaded image '" + src + "'");
    };
    img.src = src;
  };
})();

interface GalleryImageDesc {
  name?: string;
  caption: string;
  source: string;
  preview?: string;
  url?: string;
  quiz?: boolean;
}

export interface FullGalleryImageDesc extends GalleryImageDesc {
  preview: string;
  quiz: boolean;
  width: number;
  height: number;
  url: string;
}

export interface GalleryProps {
  onClick: (imgDesc: FullGalleryImageDesc) => void;
  onScroll: (imgNum: number) => void;
}

export class Gallery extends React.Component<GalleryProps> {
  getImages(): FullGalleryImageDesc[] {
    function quiz(obj: GalleryImageDesc): GalleryImageDesc {
      obj.preview = "question_mark_small.jpg";
      obj.quiz = true;
      return obj;
    }
    return [
      {
        name: "cats",
        caption: "By Jetske",
        source: "https://www.flickr.com/photos/jetske/5827857531/",
      },
      {
        name: "tree",
        caption: "By Moyan Brenn",
        source: "https://www.flickr.com/photos/aigle_dore/15061080128/",
      },
      {
        name: "mondrian",
        caption: "By Rael Garcia Arnes",
        source: "https://www.flickr.com/photos/raelga/4408707212/",
      },
      {
        name: "nyc",
        caption: "By Chris Isherwood",
        source: "https://www.flickr.com/photos/isherwoodchris/3096255994/",
      },
      {
        name: "girl",
        caption: "By Elvin",
        source: "https://www.flickr.com/photos/25228175@N08/5896000539/",
      },
      {
        name: "royal_stewart",
        caption: "The Royal Stewart tartan",
        source: "https://en.wikipedia.org/wiki/Royal_Stewart_tartan",
      },
      {
        url: "example-images/randbitmap-rdo_medium.png",
        preview: "example-images/randbitmap-rdo_small.png",
        caption: "Random data",
        source: "https://www.random.org/bitmaps/",
      },
      {
        name: "girih_pattern",
        caption: "Girih pattern by İnfoCan",
        source:
          "https://en.wikipedia.org/wiki/Girih#/media/File:Samarkand_Shah-i_Zinda_Tuman_Aqa_complex_cropped2.jpg",
      },
      {
        caption: "Made with the KC-O-M",
        url: "example-images/keep-calm-and-use-svd_medium.png",
        preview: "example-images/keep-calm-and-use-svd_small.png",
        source: "http://www.keepcalm-o-matic.co.uk/",
      },
      {
        name: "skater_boy",
        caption: "By Chris Goldberg",
        source: "https://flic.kr/p/keMZvg",
      },
      quiz({
        // Taj Mahal
        name: "quiz1",
        caption: "By Francisco Martins",
        source: "https://flic.kr/p/4bpEpb",
      }),
      quiz({
        // Rubik's Cube
        name: "quiz2",
        caption: "By Eleonora Gorini",
        source: "https://flic.kr/p/5yWPDc",
      }),
      quiz({
        // Airplane
        name: "quiz3",
        caption: "By melfoody",
        source: "https://flic.kr/p/enTNR5",
      }),
      quiz({
        // The Starry Night
        name: "quiz4",
        caption: "By VvG",
        source: "https://goo.gl/oH2BLt",
      }),
      quiz({
        // indian_peafowl
        name: "quiz5",
        caption: "By Sergiu Bacioiu",
        source: "https://flic.kr/p/7TdBUA",
      }),
    ].map((obj: GalleryImageDesc, i: number) => {
      return {
        name: obj.name ?? "image-" + i,
        width: 150,
        height: 150,
        url: obj.url ?? "example-images/" + obj.name + "_medium.jpg",
        preview: obj.preview ?? "example-images/" + obj.name + "_small.jpg",
        caption: obj.caption,
        source: obj.source,
        quiz: !!obj.quiz,
      };
    });
  }
  renderImage(img: FullGalleryImageDesc): JSX.Element {
    const onClick = (evt: React.MouseEvent<HTMLElement>): void => {
      evt.preventDefault();
      if (this.props.onClick) {
        this.props.onClick(img);
      }
    };
    const onMouseOver = (): void => {
      preload(img.url);
    };
    return (

          {img.caption}

    );
  }
  render(): JSX.Element {
    return (
      <Slider
        className="gallery"
        slidesToShow={5}
        slidesToScroll={5}
        draggable={false}
        infinite={false}
        afterChange={this.props.onScroll}
      >
        {this.getImages().map(this.renderImage.bind(this))}
      </Slider>
    );
  }
}


text:
scala-automation-web-signin
-----------------------------
The purpose of this module is to login to the Guardian website through an API, rather than through the web interface. It is to be used in conjuction with test automation.

To use this just edit your build.sbt as follows:

libraryDependencies ++= Seq(
  "com.gu" %% "scala-automation-web-signin" % "1.xxx"
)

Then add the following to your scala test configuration (see the [Scala Test Automation Framework](https://github.com/guardian/scala-automation)):

```
"idApiRoot" : "https://idapi.code.dev-theguardian.com"
"loginEmail": "your guardian account login email"
"loginPassword": "your guardian account password"
```

Then simply use the ```com.gu.automation.support.LogIn``` class to login. By default it will use the above configuration parameters from the root but if you need, you can put them in an object as seen by the linked example below.

See the (currently commented out) example code in [LoggingInTest](src/test/scala/com/gu/automation/signin/LoggingInTest.scala)


text:
ShaderBindingInfo::ShaderBindingInfo()
{
	samplersCount = 0;
	texturesCount = 0;
	buffersCount = 0;
}


text:
import {EntityManagerInterface, RepositoryInterface} from "../entityManager/common";
import {Observable} from "rxjs/Rx";
import {Resolve} from "@angular/router";
import {CRUDListResolver} from "./CRUDListResolver";
import {EventEmitter} from "@angular/core";
import {HttpException} from "../exceptions/exceptions";

export interface CRUDInteractorOptionsArgsInterface {
  RepositoryClass?:any;
  EntityClass:any;
}

export interface CRUDEvent {
  type:string;
  message:string;
}

export class CRUDInteractor<T> {

  events:EventEmitter<CRUDEvent> = new EventEmitter<CRUDEvent>();
  private _repository:RepositoryInterface;
  get repository():RepositoryInterface {
    if (!this._repository) {
      this._repository = this.em.getRepository(this.options.RepositoryClass || this.options.EntityClass);
    }
    return this._repository;
  }

  constructor(public em:EntityManagerInterface, protected options:CRUDInteractorOptionsArgsInterface) {

  }

  findItems(criteria?:any):Promise<T[]> {
    return this.repository.getByCriteria(criteria)
      .then((items:T[])=> {
        return items;
      }).catch((e:HttpException)=> {
        this.events.emit({
          type: 'error',
          message: 'Internal Error. Probably Connection Issue'
        });
        return Promise.reject(e);
      });
  }

  getItemByIndentity(id:string):Promise<T> {
    return this.repository.getById(id)
      .catch((e:HttpException)=> {
      this.events.emit({
        type: 'error',
        message: 'Internal Error. Probably Connection Issue'
      });
      return Promise.reject(e);
    })
  }

  removeItem(item:T):Promise<any> {
    return this.repository.delete(item)
      .then((i)=> {
        this.events.emit({
          type: 'success',
          message: 'Removed successfully'
        });
        return i;
      }).catch((e:HttpException)=> {
        this.events.emit({
          type: 'error',
          message: e.toString()
        });
        return Promise.reject(e);
      });
  }

  saveItem(item:T):Promise<any> {
    return this.repository.save(item)
      .then((i)=> {
        this.events.emit({
          type: 'success',
          message: 'Saved successfully'
        });
        return i;
      }).catch((e:HttpException)=> {
        this.events.emit({
          type: 'error',
          message: e.toString()
        });
        return Promise.reject(e);
      });
  }

  createEntity() {
    return new this.options.EntityClass();
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
using NUnit.Framework;

namespace Azure.Core.Tests
{
    [TestFixture(typeof(HttpClientTransport), true)]
    [TestFixture(typeof(HttpClientTransport), false)]
#if NETFRAMEWORK
    [TestFixture(typeof(HttpWebRequestTransport), true)]
    [TestFixture(typeof(HttpWebRequestTransport), false)]
#endif
    public class TransportFunctionalTests : PipelineTestBase
    {
        private readonly Type _transportType;

        public TransportFunctionalTests(Type transportType, bool isAsync) : base(isAsync)
        {
             _transportType = transportType;
        }

        private HttpPipelineTransport GetTransport()
        {
            return (HttpPipelineTransport) Activator.CreateInstance(_transportType);
        }

        public static object[] ContentWithLength =>
            new object[]
            {
                new object[] { RequestContent.Create(new byte[10]), 10 },
                new object[] { RequestContent.Create(new byte[10], 5, 5), 5 },
                new object[] { RequestContent.Create(new ReadOnlyMemory<byte>(new byte[10])), 10 },
                new object[] { RequestContent.Create(new ReadOnlyMemory<byte>(new byte[10]).Slice(5)), 5 },
                new object[] { RequestContent.Create(new ReadOnlySequence<byte>(new byte[10])), 10 },
            };

        [TestCaseSource(nameof(ContentWithLength))]
        public async Task ContentLengthIsSetForArrayContent(RequestContent content, int expectedLength)
        {
            long contentLength = 0;

            using TestServer testServer = new TestServer(
                context => contentLength = context.Request.ContentLength.Value);

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = content;

            await ExecuteRequest(request, transport);

            Assert.AreEqual(expectedLength, contentLength);
        }

        [Test]
        public async Task SettingHeaderOverridesDefaultContentLength()
        {
            long contentLength = 0;
            using TestServer testServer = new TestServer(
                context => contentLength = context.Request.ContentLength.Value);

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = RequestContent.Create(new byte[10]);
            request.Headers.Add("Content-Length", "50");

            try
            {
                await ExecuteRequest(request, transport);
            }
            catch (Exception)
            {
                // Sending the request would fail because of length mismatch
            }

            Assert.AreEqual(50, contentLength);
        }

        [Test]
        public async Task HostHeaderSetFromUri()
        {
            HostString? host = null;
            string uri = null;
            using TestServer testServer = new TestServer(
                context =>
                {
                    uri = context.Request.GetDisplayUrl();
                    host = context.Request.GetTypedHeaders().Host;
                });

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Get;
            request.Uri.Reset(testServer.Address);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(testServer.Address.ToString(), uri);
            Assert.AreEqual(testServer.Address.Host + ":" + testServer.Address.Port, host.ToString());
        }

        [Test]
        public async Task SettingHeaderOverridesDefaultHost()
        {
            HostString? host = null;
            string uri = null;
            using TestServer testServer = new TestServer(
                context =>
                {
                    uri = context.Request.GetDisplayUrl();
                    host = context.Request.GetTypedHeaders().Host;
                });

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Get;
            request.Uri.Reset(testServer.Address);
            request.Headers.Add("Host", "example.org");

            await ExecuteRequest(request, transport);

            Assert.AreEqual("http://example.org/", uri);
            Assert.AreEqual("example.org", host.ToString());
        }

        [Theory]
        [TestCase(200)]
        [TestCase(300)]
        [TestCase(400)]
        [TestCase(500)]
        public async Task ReturnsStatusAndReasonMethod(int code)
        {
            using TestServer testServer = new TestServer(
                context =>
                {
                    context.Response.StatusCode = code;
                });

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Uri.Reset(testServer.Address);

            var response = await ExecuteRequest(request, transport);

            Assert.AreEqual(code, response.Status);
        }

        public static object[][] Methods => new[]
        {
            new object[] { RequestMethod.Delete, "DELETE", false },
            new object[] { RequestMethod.Get, "GET", false },
            new object[] { RequestMethod.Patch, "PATCH", false },
            new object[] { RequestMethod.Post, "POST", true },
            new object[] { RequestMethod.Put, "PUT", true },
            new object[] { RequestMethod.Head, "HEAD", false },
            new object[] { new RequestMethod("custom"), "CUSTOM", false },
        };

        [Theory]
        [TestCaseSource(nameof(Methods))]
        public async Task CanGetAndSetMethod(RequestMethod method, string expectedMethod, bool content = false)
        {
            string httpMethod = null;
            using TestServer testServer = new TestServer(
                context =>
                {
                    httpMethod = context.Request.Method.ToString();
                });

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = method;
            request.Uri.Reset(testServer.Address);

            if (content)
            {
                request.Content = RequestContent.Create(Array.Empty<byte>());
            }

            Assert.AreEqual(method, request.Method);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(expectedMethod, httpMethod);
        }

        public static object[] AllHeadersWithValuesAndType =>
            HeadersWithValuesAndType.Concat(SpecialHeadersWithValuesAndType).ToArray();

         public static object[] HeadersWithValuesAndType =>
            new object[]
            {
                new object[] { "Allow", "adcde", true },
                new object[] { "Accept", "adcde", true },
                new object[] { "Referer", "adcde", true },
                new object[] { "User-Agent", "adcde", true },
                new object[] { "Content-Disposition", "adcde", true },
                new object[] { "Content-Encoding", "adcde", true },
                new object[] { "Content-Language", "en-US", true },
                new object[] { "Content-Location", "adcde", true },
                new object[] { "Content-MD5", "adcde", true },
                new object[] { "Content-Range", "adcde", true },
                new object[] { "Content-Type", "text/xml", true },
                new object[] { "Expires", "11/12/19", true },
                new object[] { "Last-Modified", "11/12/19", true },
                new object[] { "Custom-Header", "11/12/19", false },
            };

         public static object[] SpecialHeadersWithValuesAndType =>
             new object[]
             {
                 new object[] { "Range", "bytes=0-", false },
                 new object[] { "Range", "bytes=0-100", false },
                 new object[] { "Content-Length", "16", true },
                 new object[] { "Date", "Tue, 12 Nov 2019 08:00:00 GMT", false }
             };

         [TestCaseSource(nameof(AllHeadersWithValuesAndType))]
         public async Task CanGetAndAddRequestHeaders(string headerName, string headerValue, bool contentHeader)
         {
            StringValues httpHeaderValues;

             using TestServer testServer = new TestServer(
                 context =>
                 {
                     Assert.True(context.Request.Headers.TryGetValue(headerName, out httpHeaderValues));
                 });

             var transport = GetTransport();
             Request request = CreateRequest(transport, testServer);

             request.Headers.Add(headerName, headerValue);

             if (contentHeader)
             {
                 request.Content = RequestContent.Create(new byte[16]);
             }

             Assert.True(request.Headers.TryGetValue(headerName, out var value));
             Assert.AreEqual(headerValue, value);

             Assert.True(request.Headers.TryGetValue(headerName.ToUpper(), out value));
             Assert.AreEqual(headerValue, value);

             CollectionAssert.AreEqual(new[]
             {
                 new HttpHeader(headerName, headerValue),
             }, request.Headers);

             await ExecuteRequest(request, transport);

             Assert.AreEqual(headerValue, string.Join(",", httpHeaderValues));
         }

         [TestCaseSource(nameof(AllHeadersWithValuesAndType))]
         public async Task CanGetAndAddRequestHeadersUppercase(string headerName, string headerValue, bool contentHeader)
         {
             await CanGetAndAddRequestHeaders(headerName.ToUpperInvariant(), headerValue, contentHeader);
         }

        [TestCaseSource(nameof(HeadersWithValuesAndType))]
        public void TryGetReturnsCorrectValuesWhenNotFound(string headerName, string headerValue, bool contentHeader)
        {
            var transport = GetTransport();
            Request request = transport.CreateRequest();

            Assert.False(request.Headers.TryGetValue(headerName, out string value));
            Assert.IsNull(value);

            Assert.False(request.Headers.TryGetValues(headerName, out IEnumerable<string> values));
            Assert.IsNull(values);
        }

        [TestCaseSource(nameof(HeadersWithValuesAndType))]
        public async Task CanAddMultipleValuesToRequestHeader(string headerName, string headerValue, bool contentHeader)
        {
            var anotherHeaderValue = headerValue + "1";
            var joinedHeaderValues = headerValue + "," + anotherHeaderValue;

            StringValues httpHeaderValues;

            using TestServer testServer = new TestServer(
                context =>
                {
                    Assert.True(context.Request.Headers.TryGetValue(headerName, out httpHeaderValues));
                });

            var transport = GetTransport();
            Request request = CreateRequest(transport, testServer);

            request.Headers.Add(headerName, headerValue);
            request.Headers.Add(headerName, anotherHeaderValue);

            Assert.True(request.Headers.Contains(headerName));

            Assert.True(request.Headers.TryGetValue(headerName, out var value));
            Assert.AreEqual(joinedHeaderValues, value);

            Assert.True(request.Headers.TryGetValues(headerName, out IEnumerable<string> values));
            CollectionAssert.AreEqual(new[] { headerValue, anotherHeaderValue }, values);

            CollectionAssert.AreEqual(new[]
            {
                new HttpHeader(headerName, joinedHeaderValues),
            }, request.Headers);

            await ExecuteRequest(request, transport);

            StringAssert.Contains(headerValue, httpHeaderValues.ToString());
            StringAssert.Contains(anotherHeaderValue, httpHeaderValues.ToString());
        }

        [TestCaseSource(nameof(HeadersWithValuesAndType))]
        public async Task CanGetAndSetResponseHeaders(string headerName, string headerValue, bool contentHeader)
        {
            using TestServer testServer = new TestServer(
                context =>
                {
                    context.Response.Headers.Add(headerName, headerValue);
                });

            var transport = GetTransport();
            Request request = CreateRequest(transport, testServer);

            Response response = await ExecuteRequest(request, transport);

            Assert.True(response.Headers.Contains(headerName));

            Assert.True(response.Headers.TryGetValue(headerName, out var value));
            Assert.AreEqual(headerValue, value);

            Assert.True(response.Headers.TryGetValues(headerName, out IEnumerable<string> values));
            CollectionAssert.AreEqual(new[] { headerValue }, values);

            CollectionAssert.Contains(response.Headers, new HttpHeader(headerName, headerValue));
        }

        [TestCaseSource(nameof(HeadersWithValuesAndType))]
        public async Task CanGetAndSetMultiValueResponseHeaders(string headerName, string headerValue, bool contentHeader)
        {
            var anotherHeaderValue = headerValue + "1";
            var joinedHeaderValues = headerValue + "," + anotherHeaderValue;

            using TestServer testServer = new TestServer(
                context =>
                {
                    context.Response.Headers.Add(headerName,
                        new StringValues(new[]
                        {
                            headerValue,
                            anotherHeaderValue
                        }));
                });

            var transport = GetTransport();
            Request request = CreateRequest(transport, testServer);

            Response response = await ExecuteRequest(request, transport);

            Assert.True(response.Headers.Contains(headerName));

            Assert.True(response.Headers.TryGetValue(headerName, out var value));
            Assert.AreEqual(joinedHeaderValues, value);

            Assert.True(response.Headers.TryGetValues(headerName, out IEnumerable<string> values));
            CollectionAssert.AreEqual(new[] { headerValue, anotherHeaderValue }, values);

            CollectionAssert.Contains(response.Headers, new HttpHeader(headerName, joinedHeaderValues));
        }

        [TestCaseSource(nameof(HeadersWithValuesAndType))]
        public async Task CanRemoveHeaders(string headerName, string headerValue, bool contentHeader)
        {
            using TestServer testServer = new TestServer(
                context =>
                {
                    Assert.False(context.Request.Headers.TryGetValue(headerName, out _));
                });

            var transport = GetTransport();
            Request request = CreateRequest(transport, testServer);

            request.Headers.Add(headerName, headerValue);
            Assert.True(request.Headers.Remove(headerName));
            Assert.False(request.Headers.Remove(headerName));

            Assert.False(request.Headers.TryGetValue(headerName, out _));
            Assert.False(request.Headers.TryGetValue(headerName.ToUpper(), out _));
            Assert.False(request.Headers.Contains(headerName.ToUpper()));

            await ExecuteRequest(request, transport);
        }

        [TestCaseSource(nameof(AllHeadersWithValuesAndType))]
        public async Task CanSetRequestHeaders(string headerName, string headerValue, bool contentHeader)
        {

            StringValues httpHeaderValues;

            using TestServer testServer = new TestServer(
                context =>
                {
                    Assert.True(context.Request.Headers.TryGetValue(headerName, out httpHeaderValues));
                });

            var transport = GetTransport();
            Request request = CreateRequest(transport, testServer);

            request.Headers.Add(headerName, "Random value");
            request.Headers.SetValue(headerName, headerValue);

            if (contentHeader)
            {
                request.Content = RequestContent.Create(new byte[16]);
            }

            Assert.True(request.Headers.TryGetValue(headerName, out var value));
            Assert.AreEqual(headerValue, value);

            Assert.True(request.Headers.TryGetValue(headerName.ToUpper(), out value));
            Assert.AreEqual(headerValue, value);

            CollectionAssert.AreEqual(new[]
            {
                new HttpHeader(headerName, headerValue),
            }, request.Headers);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(headerValue, string.Join(",", httpHeaderValues));
        }

        [Test]
        public async Task CanGetAndSetContent()
        {
            byte[] requestBytes = null;
            using TestServer testServer = new TestServer(
                context =>
                {
                    using var memoryStream = new MemoryStream();
                    context.Request.Body.CopyTo(memoryStream);
                    requestBytes = memoryStream.ToArray();
                });

            var bytes = Encoding.ASCII.GetBytes("Hello world");
            var content = RequestContent.Create(bytes);
            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = content;

            Assert.AreEqual(content, request.Content);

            await ExecuteRequest(request, transport);

            CollectionAssert.AreEqual(bytes, requestBytes);
        }

        [Test]
        public async Task CanGetAndSetContentStream()
        {
            byte[] requestBytes = null;
            using TestServer testServer = new TestServer(
                context =>
                {
                    using var memoryStream = new MemoryStream();
                    context.Request.Body.CopyTo(memoryStream);
                    requestBytes = memoryStream.ToArray();
                });

            var stream = new MemoryStream();
            stream.SetLength(10*1024);
            var content = RequestContent.Create(stream);
            var transport = GetTransport();

            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = content;

            Assert.AreEqual(content, request.Content);

            await ExecuteRequest(request, transport);

            CollectionAssert.AreEqual(stream.ToArray(), requestBytes);
            Assert.AreEqual(10*1024, requestBytes.Length);
        }

        [Test]
        public async Task ContentLength0WhenNoContent()
        {
            StringValues contentLengthHeader = default;
            using TestServer testServer = new TestServer(
                context =>
                {
                    Assert.True(context.Request.Headers.TryGetValue("Content-Length", out contentLengthHeader));
                });

            var transport = GetTransport();

            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(contentLengthHeader.ToString(), "0");
        }

        [Test]
        public async Task RequestAndResponseHasRequestId()
        {
            using TestServer testServer = new TestServer(context => { });
            var transport = GetTransport();
            Request request = transport.CreateRequest();
            Assert.IsNotEmpty(request.ClientRequestId);
            Assert.True(Guid.TryParse(request.ClientRequestId, out _));
            request.Method = RequestMethod.Get;
            request.Uri.Reset(testServer.Address);

            Response response = await ExecuteRequest(request, transport);
            Assert.AreEqual(request.ClientRequestId, response.ClientRequestId);
        }

        [Test]
        public async Task RequestIdCanBeOverriden()
        {
            using TestServer testServer = new TestServer(context => { });
            var transport = GetTransport();
            Request request = transport.CreateRequest();

            request.ClientRequestId = "123";
            request.Method = RequestMethod.Get;
            request.Uri.Reset(testServer.Address);

            Response response = await ExecuteRequest(request, transport);
            Assert.AreEqual(request.ClientRequestId, response.ClientRequestId);
        }

        [Test]
        public async Task ReasonPhraseIsExposed()
        {
            using TestServer testServer = new TestServer(context =>
            {
                context.Response
                    .HttpContext
                    .Features
                    .Get<IHttpResponseFeature>()
                    .ReasonPhrase = "Custom ReasonPhrase";
            });

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Get;
            request.Uri.Reset(testServer.Address);

            Response response = await ExecuteRequest(request, transport);

            Assert.AreEqual("Custom ReasonPhrase", response.ReasonPhrase);
        }

        [Test]
        public async Task StreamRequestContentCanBeSentMultipleTimes()
        {
            var requests = new List<long?>();

            using TestServer testServer = new TestServer(context =>
            {
                requests.Add(context.Request.ContentLength);
            });

            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);

            request.Content = RequestContent.Create(new MemoryStream(new byte[] { 1, 2, 3 }));

            await ExecuteRequest(request, transport);
            await ExecuteRequest(request, transport);

            Assert.AreEqual(new long [] {3, 3}, requests);
        }

        [Test]
        public async Task RequestContentIsNotDisposedOnSend()
        {
            using TestServer testServer = new TestServer(context =>{});

            DisposeTrackingContent disposeTrackingContent = new DisposeTrackingContent();
            var transport = GetTransport();

            using (Request request = transport.CreateRequest())
            {
                request.Content = disposeTrackingContent;
                request.Method = RequestMethod.Post;
                request.Uri.Reset(testServer.Address);

                await ExecuteRequest(request, transport);
                Assert.False(disposeTrackingContent.IsDisposed);
            }

            Assert.True(disposeTrackingContent.IsDisposed);
        }
        [Test]
        public void GetIsDefaultMethod()
        {
            var transport = GetTransport();
            var request = transport.CreateRequest();
            Assert.AreEqual("GET", request.Method.Method);
        }

        [Test]
        public void ClientRequestIdSetterThrowsOnNull()
        {
            var transport = GetTransport();
            var request = transport.CreateRequest();
            Assert.Throws<ArgumentNullException>(() => request.ClientRequestId = null);
        }

        [NonParallelizable]
        [Theory]
        [TestCase("HTTP_PROXY", "http://microsoft.com")]
        [TestCase("ALL_PROXY", "http://microsoft.com")]
        public async Task ProxySettingsAreReadFromEnvironment(string envVar, string url)
        {
            try
            {
                using (TestServer testServer = new TestServer(async context =>
                {
                    context.Response.Headers["Via"] = "Test-Proxy";
                    byte[] buffer = Encoding.UTF8.GetBytes("Hello");
                    await context.Response.Body.WriteAsync(buffer, 0, buffer.Length);
                }))
                {
                    Environment.SetEnvironmentVariable(envVar, testServer.Address.ToString());

                    var transport = GetTransport();
                    Request request = transport.CreateRequest();
                    request.Uri.Reset(new Uri(url));
                    Response response = await ExecuteRequest(request, transport);
                    Assert.True(response.Headers.TryGetValue("Via", out var via));
                    Assert.AreEqual("Test-Proxy", via);
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable(envVar, null);
            }
        }

        [Test]
        public async Task ResponseHeadersAreSplit()
        {
            using (TestServer testServer = new TestServer(
                async context =>
                {
                    context.Response.Headers.Add("Sync-Token", new[] { "A", "B" });
                    byte[] buffer = Encoding.UTF8.GetBytes("Hello");
                    await context.Response.Body.WriteAsync(buffer, 0, buffer.Length);
                }))
            {
                var transport = GetTransport();
                Request request = transport.CreateRequest();
                request.Uri.Reset(testServer.Address);
                Response response = await ExecuteRequest(request, transport);
                Assert.True(response.Headers.TryGetValues("Sync-Token", out System.Collections.Generic.IEnumerable<string> tokens));
                Assert.AreEqual(2, tokens.Count());
                CollectionAssert.AreEqual(new[] { "A", "B" }, tokens);
            }
        }

        [Test]
        public async Task ResponseHeadersAreNotSplit()
        {
            using (TestServer testServer = new TestServer(
                async context =>
                {
                    context.Response.Headers.Add("Sync-Token", "A,B");
                    byte[] buffer = Encoding.UTF8.GetBytes("Hello");
                    await context.Response.Body.WriteAsync(buffer, 0, buffer.Length);
                }))
            {
                var transport = GetTransport();
                Request request = transport.CreateRequest();
                request.Uri.Reset(testServer.Address);
                Response response = await ExecuteRequest(request, transport);
                Assert.True(response.Headers.TryGetValues("Sync-Token", out System.Collections.Generic.IEnumerable<string> tokens));
                Assert.AreEqual(1, tokens.Count());
                CollectionAssert.AreEqual(new[] { "A,B" }, tokens);
            }
        }

        [Test]
        public void TransportExceptionsAreWrapped()
        {
            using (TestServer testServer = new TestServer(
                context =>
                {
                    context.Abort();
                    return Task.CompletedTask;
                }))
            {
                var transport = GetTransport();
                Request request = transport.CreateRequest();
                request.Uri.Reset(testServer.Address);
                RequestFailedException exception = Assert.ThrowsAsync<RequestFailedException>(async () => await ExecuteRequest(request, transport));
                Assert.IsNotEmpty(exception.Message);
                Assert.AreEqual(0, exception.Status);
            }
        }

        [Test]
        public async Task ThrowsTaskCanceledExceptionWhenCancelled()
        {
            var testDoneTcs = new CancellationTokenSource();
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);

            using TestServer testServer = new TestServer(
                async context =>
                {
                    tcs.SetResult(null);
                    await Task.Delay(Timeout.Infinite, testDoneTcs.Token);
                });

            var cts = new CancellationTokenSource();
            var transport = GetTransport();
            Request request = transport.CreateRequest();
            request.Uri.Reset(testServer.Address);

            var task = Task.Run(async () => await ExecuteRequest(request, transport, cts.Token));

            // Wait for server to receive a request
            await tcs.Task;

            cts.Cancel();

            Assert.ThrowsAsync(Is.InstanceOf<TaskCanceledException>(), async () => await task);
            testDoneTcs.Cancel();
        }

        [Test]
        public async Task StreamReadingExceptionsAreIOExceptions()
        {
            var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
            using (TestServer testServer = new TestServer(
                async context =>
                {
                    context.Response.ContentLength = 20;
                    await context.Response.WriteAsync("Hello");
                    await tcs.Task;

                    context.Abort();
                }))
            {
                var transport = GetTransport();
                Request request = transport.CreateRequest();
                request.Uri.Reset(testServer.Address);
                Response response = await ExecuteRequest(request, transport);

                tcs.SetResult(null);

                Assert.ThrowsAsync<IOException>(async () => await response.ContentStream.CopyToAsync(new MemoryStream()));
            }
        }

        private static Request CreateRequest(HttpPipelineTransport transport, TestServer server, byte[] bytes = null)
        {
            Request request = transport.CreateRequest();
            request.Method = RequestMethod.Post;
            request.Uri.Reset(server.Address);
            request.Content = RequestContent.Create(bytes ?? Array.Empty<byte>());
            return request;
        }

        public class DisposeTrackingContent : RequestContent
        {
            public override Task WriteToAsync(Stream stream, CancellationToken cancellation)
            {
                return Task.CompletedTask;
            }

            public override void WriteTo(Stream stream, CancellationToken cancellation)
            {
            }

            public override bool TryComputeLength(out long length)
            {
                length = 0;
                return false;
            }

            public override void Dispose()
            {
                IsDisposed = true;
            }

            public bool IsDisposed { get; set; }
        }
    }
}


text:
                Online

                    Написать

                + Пригласить
друга

Пригласить друга

    <form ng-submit="sendInvite()">
        <fieldset>

                От кого
                <input id="from" type="text" ng-model="invite.from">

                Имя друга
                <input id="name" type="text" ng-model="invite.name">

                Телефон друга
                <input id="phone" type="tel" ng-model="invite.phone">

                Почта друга
                <input id="mail" type="email" ng-model="invite.email">

                <button class="btn btn-blue" type="button" ng-click="sendInvite()">Отправить</button>
                <button class="btn btn-white" type="button" ng-click="invite.popup=false">Отмена</button>

        </fieldset>
    </form>


text:
package com.sunrise22.galaxy.entry;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AppSessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();// managed by context

		Set<HttpSession> sessions = (HashSet<HttpSession>)application.getAttribute("session");
		if (sessions == null) {
			sessions = new HashSet<HttpSession>();

			application.setAttribute("sessions", sessions);
		}
		sessions.add(session);
		log.debug("创建session 连接数:" + sessions.size());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();

		Set<HttpSession> sessions = (HashSet<HttpSession>)application.getAttribute("session");
		sessions.remove(session);
		log.debug("移除session-连接数:" + sessions.size());
	}

	private static final Log log = LogFactory.getLog(AppSessionListener.class);

}


text:
"""
The managers for the custom Account object and permissions.
"""

import datetime
from django.utils import timezone
from django.contrib.auth.models import UserManager
from evennia.typeclasses.managers import (TypedObjectManager, TypeclassManager)
__all__ = ("AccountManager",)

#
# Account Manager
#

class AccountDBManager(TypedObjectManager, UserManager):
    """
    This AccountManager implements methods for searching
    and manipulating Accounts directly from the database.

    Evennia-specific search methods (will return Characters if
    possible or a Typeclass/list of Typeclassed objects, whereas
    Django-general methods will return Querysets or database objects):

    dbref (converter)
    dbref_search
    get_dbref_range
    object_totals
    typeclass_search
    num_total_accounts
    get_connected_accounts
    get_recently_created_accounts
    get_recently_connected_accounts
    get_account_from_email
    get_account_from_uid
    get_account_from_name
    account_search (equivalent to evennia.search_account)
    #swap_character

    """

    def num_total_accounts(self):
        """
        Get total number of accounts.

        Returns:
            count (int): The total number of registered accounts.

        """
        return self.count()

    def get_connected_accounts(self):
        """
        Get all currently connected accounts.

        Returns:
            count (list): Account objects with currently
                connected sessions.

        """
        return self.filter(db_is_connected=True)

    def get_recently_created_accounts(self, days=7):
        """
        Get accounts recently created.

        Args:
            days (int, optional): How many days in the past "recently" means.

        Returns:
            accounts (list): The Accounts created the last `days` interval.

        """
        end_date = timezone.now()
        tdelta = datetime.timedelta(days)
        start_date = end_date - tdelta
        return self.filter(date_joined__range=(start_date, end_date))

    def get_recently_connected_accounts(self, days=7):
        """
        Get accounts recently connected to the game.

        Args:
            days (int, optional): Number of days backwards to check

        Returns:
            accounts (list): The Accounts connected to the game in the
                last `days` interval.

        """
        end_date = timezone.now()
        tdelta = datetime.timedelta(days)
        start_date = end_date - tdelta
        return self.filter(last_login__range=(
            start_date, end_date)).order_by('-last_login')

    def get_account_from_email(self, uemail):
        """
        Search account by
        Returns an account object based on email address.

        Args:
            uemail (str): An email address to search for.

        Returns:
            account (Account): A found account, if found.

        """
        return self.filter(email__iexact=uemail)

    def get_account_from_uid(self, uid):
        """
        Get an account by id.

        Args:
            uid (int): Account database id.

        Returns:
            account (Account): The result.

        """
        try:
            return self.get(id=uid)
        except self.model.DoesNotExist:
            return None

    def get_account_from_name(self, uname):
        """
        Get account object based on name.

        Args:
            uname (str): The Account name to search for.

        Returns:
            account (Account): The found account.

        """
        try:
            return self.get(username__iexact=uname)
        except self.model.DoesNotExist:
            return None

    def search_account(self, ostring, exact=True, typeclass=None):
        """
        Searches for a particular account by name or
        database id.

        Args:
            ostring (str or int): A key string or database id.
            exact (bool, optional): Only valid for string matches. If
                `True`, requires exact (non-case-sensitive) match,
                otherwise also match also keys containing the `ostring`
                (non-case-sensitive fuzzy match).
            typeclass (str or Typeclass, optional): Limit the search only to
                accounts of this typeclass.

        """
        dbref = self.dbref(ostring)
        if dbref or dbref == 0:
            # bref search is always exact
            matches = self.filter(id=dbref)
            if matches:
                return matches
        query = {"username__iexact" if exact else "username__icontains": ostring}
        if typeclass:
            # we accept both strings and actual typeclasses
            if callable(typeclass):
                typeclass = u"%s.%s" % (typeclass.__module__, typeclass.__name__)
            else:
                typeclass = u"%s" % typeclass
            query["db_typeclass_path"] = typeclass
        if exact:
            return self.filter(**query)
        else:
            return self.filter(**query)
    # back-compatibility alias
    account_search = search_account

class AccountManager(AccountDBManager, TypeclassManager):
    pass


text:
/**
 * @author Hypocrisy(虚伪)
 * Created by Hypocrisy on 5/25/2015.
 */
import java.util.InputMismatchException;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.next();
        int x = Integer.parseInt(s);
        Solution solution = new Solution();

        int y = solution.reverse(x);
        System.out.println(y);
    }
    public int reverse(int x) {
        long xReverse = 0;

        int sign = 0;
        if(x < 0) {
            sign = 1;
        }

        int bits = (new Integer(x)).toString().length() - sign;

        while(bits>0) {
            int bit = x%10; //取余数是保持符号的
            xReverse += (bit * (Math.pow(10, bits - 1)));
            x /= 10;
            --bits;
        }

        if(xReverse > Integer.MAX_VALUE || xReverse < Integer.MIN_VALUE) {
            xReverse = 0;
        }
        return (int)xReverse;
    }
}


text:
<?php

namespace frostealth\yii2\aws\s3\interfaces\commands;

/**
 * Interface ExecutableCommand
 *
 * @package frostealth\yii2\aws\s3\interfaces\commands
 */
interface ExecutableCommand extends Command
{
    /**
     * @return mixed
     */
    public function execute();
}


text:
	text-align: center;
	margin-top: 5px;
}

#amplitude-player {
	box-shadow: 0 2px 12px 8px rgba(0, 0, 0, 0.1);
	margin-bottom: 20px;
}

#control-container {
	margin-top: 25px;
}

.song-album,
.song-artist {
	display: block;
	overflow: hidden;
	text-overflow: ellipsis;
}

#shuffle.amplitude-shuffle-off {
	background: url("../open-iconic/svg/random.svg");
}

#shuffle.amplitude-shuffle-on {
	background: url("../svg/transfer_2r.svg");
}

#previous {
	background: url("../open-iconic/svg/media-step-backward.svg");
}

#play-pause.amplitude-playing {
	background: url("../open-iconic/svg/media-pause.svg");
}

#play-pause.amplitude-paused {
	background: url("../open-iconic/svg/media-play.svg");
}

#next {
	background: url("../open-iconic/svg/media-step-forward.svg");
}

#repeat {
	background: url("../open-iconic/svg/loop.svg");
}

#previous, #play-pause, #next, #repeat, #shuffle {
	background-size: contain !important;
	width: 64px;
	height: 64px;
}

main {
	display: flex;
	flex-flow: column wrap;
	justify-content: center;
	align-items: center;
}

#control-container {
	display: flex;
	flex-flow: row wrap;
	justify-content: center;
	align-items: center;
}

div.space {
	width: 16px;
}

#central-control-container {
	display: flex;
	flex-flow: row nowrap;
	justify-content: center;
	align-items: center;
}

.song-artist-album {
	display: flex;
	flex-flow: column nowrap;
	justify-content: center;
	align-items: center;
}


text:
var toggleControlPanel = function() {
    var panel = document.getElementById('control-panel');

    if (panel.className.indexOf('hidden') == 0) {
        panel.className = '';
    } else {
        panel.className = 'hidden';
    };
};

window.onload = function() {
    var visualizer = new Visualizer(document.getElementById('visualizer'));
    visualizer.init();

    document.getElementById('toggleButton').addEventListener('click', function(evt) {
        evt.preventDefault();
        toggleControlPanel();
    });
};


text:
<!--
Description: item description contains script (maps to content)
Expect:      not bozo and entries[0]['summary'] == 'safe description'
-->
<rss version="2.0">
<channel>
<item>
<description>safe<script type="text/javascript">location.href='http:/'+'/example.com/';</script> description</description>
</item>
</channel>
</rss>


text:
'use strict';

var services = angular.module('app.services');

services.factory('Menus', ['$resource', function($resource) {
    return $resource('admin/menu/:name', {
        name: '@name',
        defaultMenu: '@defaultMenu'
    });
}]);

//Global service for global variables
services.factory('Global', [

    function() {
        var _this = this;
        _this._data = {
            user: window.user,
            authenticated: false,
            isAdmin: false
        };
        if (window.user && window.user.roles) {
            _this._data.authenticated = window.user.roles.length;
            _this._data.isAdmin = ~window.user.roles.indexOf('admin');
        }
        return _this._data;
    }
]);


text:
@class NSSet, NSString;

@interface IDEIndexCodeCompletionContext : NSObject
{
    unsigned long long _contexts;
    unsigned int _containerKind;
    NSString *_containerUSR;
    BOOL _containerIsIncomplete;
    NSString *_partialSelector;
    NSSet *_includedFiles;
}

@property(copy) NSSet *includedFiles; // @synthesize includedFiles=_includedFiles;
@property(copy) NSString *partialSelector; // @synthesize partialSelector=_partialSelector;
@property BOOL containerIsIncomplete; // @synthesize containerIsIncomplete=_containerIsIncomplete;
@property(copy) NSString *containerResolution; // @synthesize containerResolution=_containerUSR;
@property unsigned int containerKind; // @synthesize containerKind=_containerKind;
@property unsigned long long contexts; // @synthesize contexts=_contexts;

@end


text:
layout: default
published: true
---

      <time datetime="{{ page.date | date: "%-d %b %Y" }}" class="post-meta__date date">{{ page.date | date: "%-d %b %Y" }}</time> • on {% for tag in page.tags %}{{ tag }} {% endfor %}

{{ page.title }}

    {{ content }}


text:
import Component from '@glimmer/component';

export default class SideBar extends Component {
  constructor() {
    super(...arguments);
    this.items = [
      { route: 'gettingstarted', text: 'Getting Started' },
      { route: 'simple', text: 'Simple' },
      { route: 'async', text: 'Async' },
      { route: 'hoveredactions', text: 'Hovered Actions' },
      { route: 'expand', text: 'Expand' },
      { route: 'multiselection', text: 'Multi Selection' },
      { route: 'noderefresh', text: 'Node Refresh' },
    ];
  }
}


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.database.core.view;

import com.google.firebase.database.core.Path;
import com.google.firebase.database.snapshot.ChildKey;
import com.google.firebase.database.snapshot.IndexedNode;
import com.google.firebase.database.snapshot.Node;

/**
 * A cache node only stores complete children. Additionally it holds a flag whether the node can be
 * considered fully initialized in the sense that we know at one point in time this represented a
 * valid state of the world, e.g. initialized with data from the server, or a complete overwrite by
 * the client. The filtered flag also tracks whether a node potentially had children removed due to
 * a filter.
 */
public class CacheNode {
  private final IndexedNode indexedNode;
  private final boolean fullyInitialized;
  private final boolean filtered;

  public CacheNode(IndexedNode node, boolean fullyInitialized, boolean filtered) {
    this.indexedNode = node;
    this.fullyInitialized = fullyInitialized;
    this.filtered = filtered;
  }

  /**
   * Returns whether this node was fully initialized with either server data or a complete overwrite
   * by the client
   */
  public boolean isFullyInitialized() {
    return this.fullyInitialized;
  }

  /**
   * Returns whether this node is potentially missing children due to a filter applied to the node
   */
  public boolean isFiltered() {
    return this.filtered;
  }

  public boolean isCompleteForPath(Path path) {
    if (path.isEmpty()) {
      return this.isFullyInitialized() && !this.filtered;
    } else {
      ChildKey childKey = path.getFront();
      return isCompleteForChild(childKey);
    }
  }

  public boolean isCompleteForChild(ChildKey key) {
    return (this.isFullyInitialized() && !this.filtered) || indexedNode.getNode().hasChild(key);
  }

  public Node getNode() {
    return this.indexedNode.getNode();
  }

  public IndexedNode getIndexedNode() {
    return this.indexedNode;
  }
}


text:
package cn.wuxia.common.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import org.apache.commons.lang3.math.NumberUtils;

public class NumberUtil extends NumberUtils {

    /**
     * @param num1
     * @param num2
     * @return num1*num2
     */
    public static Number multiply(Number num1, Number num2) {
        BigDecimal val1 = new BigDecimal(num1.doubleValue());
        BigDecimal val2 = new BigDecimal(num2.doubleValue());
        return val1.multiply(val2);
    }

    /**
     * @param num1
     * @param num2 value by which this BigDecimal is to be divided.
     * @param scale scale scale of the BigDecimal quotient to be returned.
     * @return num1/ num2
     */
    public static Number divide(Number num1, Number num2, int scale) {
        return divide(num1, num2, BigDecimal.ROUND_HALF_UP, scale);
    }

    /**
     * @param num1
     * @param num2 value by which this BigDecimal is to be divided.
     * @param roundType rounding mode to apply.
     * @param scale scale of the BigDecimal quotient to be returned.
     * @return num1/ num2
     */
    public static Number divide(Number num1, Number num2, int roundingMode, int scale) {
        if (num1.intValue() == 0 || num2.intValue() == 0) {
            return new BigDecimal(0);
        } else if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }

        BigDecimal val1 = new BigDecimal(String.valueOf(num1));
        BigDecimal val2 = new BigDecimal(String.valueOf(num2));
        BigDecimal val3 = null;

        if (roundingMode != 0) {
            val3 = val1.divide(val2, scale, roundingMode);
        }

        return val3;
    }

    /**
     * @description : For equality
     * @param a
     * @param b
     * @return
     */
    public static boolean equals(Number a, Number b) {
        if (a == null && b == null)
            return true;

        if (a != null && b != null) {
            int result = Double.compare(a.doubleValue(), b.doubleValue());
            if (result == 0)
                return true;
        }
        return false;
    }

    /**
     * -1 为 a < b, 0 为a == b, 1 为 a > b
     *
     * @param a
     * @param b
     * @return
     */
    public static int compare(Number a, Number b) {
        double c = a == null ? 0 : a.doubleValue();
        double d = b == null ? 0 : b.doubleValue();
        return Double.compare(c, d);
    }

    /**
     * @description : 数字格式的对象转换为Integer
     * @author songlin.li
     * @param obj
     * @return
     */
    public static Integer toInteger(Object obj) {
        if (obj == null) {
            return null;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).intValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).intValue();
        } else {
            return NumberUtils.toInt(obj.toString());
        }
    }

    /**
     * @description : 数字格式的对象转换为Integer
     * @author songlin.li
     * @param obj
     * @return
     */
    public static Integer toInteger(Object obj, Integer defaultValue) {
        if (obj == null) {
            return defaultValue;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).intValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).intValue();
        } else {
            return NumberUtils.toInt(obj.toString());
        }
    }

    /**
     * @description : 数字格式的对象转换为Long
     * @author songlin.li
     * @param obj
     * @return
     */
    public static Long toLong(Object obj) {
        if (obj == null) {
            return null;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).longValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).longValue();
        } else {
            return toLong(obj.toString(), 0);
        }
    }

    public static Long toLong(Object obj, Long defaultValue) {
        if (obj == null) {
            return defaultValue;
        } else {
            return toLong(obj);
        }
    }

    /**
     * @description : 数字格式的对象转换为Double
     * @author songlin.li
     * @param obj
     * @return
     */
    public static Double toDouble(Object obj) {
        if (obj == null) {
            return null;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).doubleValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).doubleValue();
        } else {
            return NumberUtils.toDouble(obj.toString());
        }
    }

    public static Double toDouble(Object obj, Double defaultValue) {
        if (obj == null) {
            return defaultValue;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).doubleValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).doubleValue();
        } else {
            return NumberUtils.toDouble(obj.toString());
        }
    }

    /**
     * @description : 数字格式的对象转换为Float
     * @author songlin.li
     * @param obj
     * @return
     */
    public static Float toFloat(Object obj) {
        if (obj == null) {
            return null;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).floatValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).floatValue();
        } else {
            return NumberUtils.toFloat(obj.toString());
        }
    }

    public static Float toFloat(Object obj, Float defaultValue) {
        if (obj == null) {
            return defaultValue;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).floatValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).floatValue();
        } else {
            return NumberUtils.toFloat(obj.toString());
        }
    }

    public static String formatFinancing(Number n) {
        DecimalFormat df = new DecimalFormat("###,###.##");
        String financingNum = df.format(n);
        if (StringUtil.indexOf(financingNum, ".") < 0) {
            return financingNum + ".00";
        }
        return financingNum;
    }

    public static void main(String[] args) {
        System.out.println(divide(11111, 0.9, 5, 2));
        int a = (int) (11111 / 0.9);
        System.out.println(formatFinancing(10110.123123));
        System.out.println(formatFinancing(new BigDecimal(0.10)));
        System.out.println(formatFinancing(8.010));

        System.out.println(801/200);

        int x = 100;
        int y = 200;
        if(x%y != 0)
            System.out.println(x/y+1);
        else
            System.out.println(x/y);
    }
}


text:
Closes #

Describe your proposed changes here.

<!-- Checkboxes below this note can be erased if not applicable to your Pull Request. -->

- [ ] [CHANGELOG.md](https://github.com/influxdata/influxdb/blob/master/CHANGELOG.md) updated with a link to the PR (not the Issue)
- [ ] [Well-formatted commit messages](https://www.conventionalcommits.org/en/v1.0.0-beta.3/)
- [ ] Rebased/mergeable
- [ ] Tests pass
- [ ] http/swagger.yml updated (if modified Go structs or API)
- [ ] Documentation updated or issue created (provide link to issue/pr)
- [ ] Signed [CLA](https://influxdata.com/community/cla/) (if not already signed)


text:
'use strict';

var _regeneratorRuntime = require('babel-runtime/regenerator')['default'];

var Vec3 = require('vec3').Vec3;

module.exports.server = function (serv) {
  serv.playSound = function (sound, world, position) {
    var _ref = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];

    var whitelist = _ref.whitelist;
    var _ref$blacklist = _ref.blacklist;
    var blacklist = _ref$blacklist === undefined ? [] : _ref$blacklist;
    var _ref$radius = _ref.radius;
    var radius = _ref$radius === undefined ? 32 * 32 : _ref$radius;
    var _ref$volume = _ref.volume;
    var volume = _ref$volume === undefined ? 1.0 : _ref$volume;
    var _ref$pitch = _ref.pitch;
    var pitch = _ref$pitch === undefined ? 1.0 : _ref$pitch;

    var players = typeof whitelist != 'undefined' ? typeof whitelist instanceof Array ? whitelist : [whitelist] : serv.getNearby({
      world: world,
      position: position.scaled(32).floored(),
      radius: radius // 32 blocks, fixed position
    });
    players.filter(function (player) {
      return blacklist.indexOf(player) == -1;
    }).forEach(function (player) {
      var pos = (position || player.position.scaled(1 / 32)).scaled(8).floored();
      player._client.write('named_sound_effect', {
        soundName: sound,
        x: pos.x,
        y: pos.y,
        z: pos.z,
        volume: volume,
        pitch: Math.round(pitch * 63)
      });
    });
  };

  serv.playNoteBlock = function (pitch, world, position) {
    var _ref2 = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];

    var _ref2$instrument = _ref2.instrument;
    var instrument = _ref2$instrument === undefined ? 'harp' : _ref2$instrument;
    var _ref2$particle = _ref2.particle;
    var particle = _ref2$particle === undefined ? true : _ref2$particle;

    if (particle) {
      serv.emitParticle(23, world, position.clone().add(new Vec3(0.5, 1.5, 0.5)), {
        count: 1,
        size: new Vec3(0, 0, 0)
      });
    }
    serv.playSound('note.' + instrument, world, position, { pitch: serv.getNote(pitch) });
  };

  serv.getNote = function (note) {
    return 0.5 * Math.pow(Math.pow(2, 1 / 12), note);
  };
};

module.exports.player = function (player, serv) {
  var _this = this;

  player.playSound = function (sound) {
    var opt = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

    opt.whitelist = player;
    serv.playSound(sound, player.world, null, opt);
  };

  player.on('placeBlock_cancel', function callee$1$0(_ref3, cancel) {
    var reference = _ref3.reference;
    var id, data;
    return _regeneratorRuntime.async(function callee$1$0$(context$2$0) {
      while (1) switch (context$2$0.prev = context$2$0.next) {
        case 0:
          if (!player.crouching) {
            context$2$0.next = 2;
            break;
          }

          return context$2$0.abrupt('return');

        case 2:
          context$2$0.next = 4;
          return _regeneratorRuntime.awrap(player.world.getBlockType(reference));

        case 4:
          id = context$2$0.sent;

          if (!(id != 25)) {
            context$2$0.next = 7;
            break;
          }

          return context$2$0.abrupt('return');

        case 7:
          cancel(false);
          if (!player.world.blockEntityData[reference.toString()]) player.world.blockEntityData[reference.toString()] = {};
          data = player.world.blockEntityData[reference.toString()];

          if (typeof data.note == 'undefined') data.note = -1;
          data.note++;
          data.note %= 25;
          serv.playNoteBlock(data.note, player.world, reference);

        case 14:
        case 'end':
          return context$2$0.stop();
      }
    }, null, _this);
  });

  player.on('dig_cancel', function callee$1$0(_ref4, cancel) {
    var position = _ref4.position;
    var id, data;
    return _regeneratorRuntime.async(function callee$1$0$(context$2$0) {
      while (1) switch (context$2$0.prev = context$2$0.next) {
        case 0:
          context$2$0.next = 2;
          return _regeneratorRuntime.awrap(player.world.getBlockType(position));

        case 2:
          id = context$2$0.sent;

          if (!(id != 25)) {
            context$2$0.next = 5;
            break;
          }

          return context$2$0.abrupt('return');

        case 5:
          cancel(false);
          if (!player.world.blockEntityData[position.toString()]) player.world.blockEntityData[position.toString()] = {};
          data = player.world.blockEntityData[position.toString()];

          if (typeof data.note == 'undefined') data.note = 0;
          serv.playNoteBlock(data.note, player.world, position);

        case 10:
        case 'end':
          return context$2$0.stop();
      }
    }, null, _this);
  });

  player.commands.add({
    base: 'playsound',
    info: 'to play sound for yourself',
    usage: '/playsound <sound_name> [volume] [pitch]',
    op: true,
    parse: function parse(str) {
      var results = str.match(/([^ ]+)(?: ([^ ]+))?(?: ([^ ]+))?/);
      if (!results) return false;
      return {
        sound_name: results[1],
        volume: results[2] ? parseFloat(results[2]) : 1.0,
        pitch: results[3] ? parseFloat(results[3]) : 1.0
      };
    },
    action: function action(_ref5) {
      var sound_name = _ref5.sound_name;
      var volume = _ref5.volume;
      var pitch = _ref5.pitch;

      player.chat('Playing "' + sound_name + '" (volume: ' + volume + ', pitch: ' + pitch + ')');
      player.playSound(sound_name, { volume: volume, pitch: pitch });
    }
  });

  player.commands.add({
    base: 'playsoundforall',
    info: 'to play sound for everyone',
    usage: '/playsoundforall <sound_name> [volume] [pitch]',
    op: true,
    parse: function parse(str) {
      var results = str.match(/([^ ]+)(?: ([^ ]+))?(?: ([^ ]+))?/);
      if (!results) return false;
      return {
        sound_name: results[1],
        volume: results[2] ? parseFloat(results[2]) : 1.0,
        pitch: results[3] ? parseFloat(results[3]) : 1.0
      };
    },
    action: function action(_ref6) {
      var sound_name = _ref6.sound_name;
      var volume = _ref6.volume;
      var pitch = _ref6.pitch;

      player.chat('Playing "' + sound_name + '" (volume: ' + volume + ', pitch: ' + pitch + ')');
      serv.playSound(sound_name, player.world, player.position.scaled(1 / 32), { volume: volume, pitch: pitch });
    }
  });
};

module.exports.entity = function (entity, serv) {
  entity.playSoundAtSelf = function (sound) {
    var opt = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

    serv.playSound(sound, entity.world, entity.position.scaled(1 / 32), opt);
  };
};
//# sourceMappingURL=../../maps/lib/plugins/sound.js.map