text:
package org.apereo.cas.util;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.Writer;

/**
 * Interface to define operations needed to map objects from/to  clobs.
 *
 * @author Misagh Moayyed
 * @param <T> the type parameter
 * @since 4.1.0
 */
public interface StringSerializer<T> extends Serializable {
    /**
     * Create the object type from the given  string.
     *
     * @param data the  string
     * @return the object instance constructed from
     */
    T from(String data);

    /**
     * Create the object type from the given  reader.
     *
     * @param reader the  string
     * @return the object instance constructed from
     */
    T from(Reader reader);

    /**
     * Create the object type from the given  stream.
     *
     * @param stream the  string
     * @return the object instance constructed from
     */
    T from(InputStream stream);

    /**
     * Create the object type from the given  file.
     *
     * @param file the  string
     * @return the object instance constructed from
     */
    T from(File file);

    /**
     * Serialize the given object to its  equivalent to the output stream.
     *
     * @param out    the output stream
     * @param object the object to serialize
     */
    void to(OutputStream out, T object);

    /**
     * Serialize the given object to its  equivalent to the output writer.
     *
     * @param out    the output writer
     * @param object the object to serialize
     */
    void to(Writer out, T object);

    /**
     * Serialize the given object to its  equivalent to the output file.
     *
     * @param out    the output file
     * @param object the object to serialize
     */
    void to(File out, T object);
}


text:
package com.huawei.streaming.cql;

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

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

import com.huawei.streaming.exception.StreamingException;

/**
 * cql语法解析测试公共类
 *
 */
public class DriverTestUtil
{
    private static final Logger LOG = LoggerFactory.getLogger(DriverTestUtil.class);

    private List<String> sqls = new ArrayList<String>();

    private File resultFile;

    private File outputFile;

    private Driver driver;

    /**
     * <默认构造函数>
     *
     */
    public DriverTestUtil(String inputFile, String outputFile, String resultFile)
        throws Exception
    {
        this.resultFile = new File(resultFile);
        this.outputFile = new File(outputFile);
        driver = new Driver();
        sqls.addAll(CQLTestCommons.addFile(new File(inputFile)));
    }

    /**
     * 正常 的功能用例解析
     *
     */
    public void executeAndWrite()
        throws IOException, StreamingException
    {
        for (int i = 0; i < sqls.size(); i++)
        {
            driver.run(sqls.get(i));
        }
        LOG.info("start to write driver run result to result file");
        writeResultFiles(driver.getResult());
    }

    /**
     * 对比测试结果
     *
     */
    public boolean compareResults()
        throws IOException
    {
        return CQLTestCommons.compareFileContent(outputFile, resultFile);
    }

    private void writeResultFiles(CQLResult result)
        throws IOException
    {
        if (null == result)
        {
            return;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < result.getResults().size(); i++)
        {
            String[] resultCols = result.getResults().get(i);
            for (int j = 0; j < resultCols.length; j++)
            {
                sb.append(resultCols[i]);
                if (j != resultCols.length - 1)
                {
                    sb.append("\t");
                }
            }
        }

        CQLTestCommons.appendToFile(resultFile, sb.toString());
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <debug.h>
#include <trace.h>
#include <stdlib.h>
#include <err.h>
#include <trace.h>
#include <stdio.h>
#include <reg.h>
#include <arch.h>
#include <arch/ops.h>
#include <arch/mmu.h>
#include <arch/arm.h>
#include <arch/arm/mmu.h>
#include <arch/mp.h>
#include <kernel/spinlock.h>
#include <kernel/thread.h>
#include <lk/main.h>
#include <lk/init.h>
#include <platform.h>
#include <target.h>
#include <kernel/thread.h>

#define LOCAL_TRACE 0

#if WITH_DEV_TIMER_ARM_CORTEX_A9
#include <dev/timer/arm_cortex_a9.h>
#endif
#if WITH_DEV_INTERRUPT_ARM_GIC
#include <dev/interrupt/arm_gic.h>
#endif
#if WITH_DEV_CACHE_PL310
#include <dev/cache/pl310.h>
#endif

/* initial and abort stacks */
uint8_t abort_stack[ARCH_DEFAULT_STACK_SIZE * SMP_MAX_CPUS] __CPU_ALIGN;

static void arm_basic_setup(void);
static void spinlock_test(void);
static void spinlock_test_secondary(void);

#if WITH_SMP
/* smp boot lock */
spin_lock_t arm_boot_cpu_lock = 1;
volatile int secondaries_to_init = 0;
#endif

void arch_early_init(void)
{
	/* turn off the cache */
	arch_disable_cache(UCACHE);
#if WITH_DEV_CACHE_PL310
	pl310_set_enable(false);
#endif

	arm_basic_setup();

#if WITH_SMP && ARM_CPU_CORTEX_A9
	/* enable snoop control */
	addr_t scu_base = arm_read_cbar();
	*REG32(scu_base) |= (1<<0); /* enable SCU */
#endif

#if ARM_WITH_MMU
	arm_mmu_early_init();

	platform_init_mmu_mappings();
#endif

	/* turn the cache back on */
#if WITH_DEV_CACHE_PL310
	pl310_set_enable(true);
#endif
	arch_enable_cache(UCACHE);
}

void arch_init(void)
{
#if WITH_SMP
	arch_mp_init_percpu();

	LTRACEF("midr 0x%x\n", arm_read_midr());
	LTRACEF("sctlr 0x%x\n", arm_read_sctlr());
	LTRACEF("actlr 0x%x\n", arm_read_actlr());
#if ARM_CPU_CORTEX_A9
	LTRACEF("cbar 0x%x\n", arm_read_cbar());
#endif
	LTRACEF("mpidr 0x%x\n", arm_read_mpidr());
	LTRACEF("ttbcr 0x%x\n", arm_read_ttbcr());
	LTRACEF("ttbr0 0x%x\n", arm_read_ttbr0());
	LTRACEF("dacr 0x%x\n", arm_read_dacr());
#if ARM_CPU_CORTEX_A7
	LTRACEF("l2ctlr 0x%x\n", arm_read_l2ctlr());
	LTRACEF("l2ectlr 0x%x\n", arm_read_l2ectlr());
#endif

#if ARM_CPU_CORTEX_A9
	addr_t scu_base = arm_read_cbar();
	uint32_t scu_config = *REG32(scu_base + 4);
	secondaries_to_init = scu_config & 0x3;
#elif ARM_CPU_CORTEX_A7
	uint32_t l2ctlr = arm_read_l2ctlr();
	secondaries_to_init = (l2ctlr >> 24);
#else
	secondaries_to_init = SMP_MAX_CPUS - 1; /* TODO: get count from somewhere else, or add cpus as they boot */
#endif

	lk_init_secondary_cpus(secondaries_to_init);

	/* in platforms where the cpus have already been started, go ahead and wake up all the
	 * secondary cpus here.
	 */
	dprintf(SPEW, "releasing %d secondary cpu%c\n", secondaries_to_init, secondaries_to_init != 1 ? 's' : ' ');

	/* release the secondary cpus */
	spin_unlock(&arm_boot_cpu_lock);

	/* flush the release of the lock, since the secondary cpus are running without cache on */
	arch_clean_cache_range((addr_t)&arm_boot_cpu_lock, sizeof(arm_boot_cpu_lock));

#if ARM_ARCH_WAIT_FOR_SECONDARIES
	/* wait for secondary cpus to boot before arm_mmu_init below, which will remove
	 * temporary boot mappings
	 * TODO: find a cleaner way to do this than this #define
	 */
	while (secondaries_to_init > 0) {
		__asm__ volatile("wfe");
	}
#endif
#endif // WITH_SMP

	//spinlock_test();

#if ARM_WITH_MMU
	/* finish intializing the mmu */
	arm_mmu_init();
#endif
}

#if WITH_SMP
void arm_secondary_entry(uint asm_cpu_num)
{
	uint cpu = arch_curr_cpu_num();
	if (cpu != asm_cpu_num)
		return;

	arm_basic_setup();

	/* enable the local L1 cache */
	//arch_enable_cache(UCACHE);

	// XXX may not be safe, but just hard enable i and d cache here
	// at the moment cannot rely on arch_enable_cache not dumping the L2
	uint32_t sctlr = arm_read_sctlr();
	sctlr |= (1<<12) | (1<<2); // enable i and dcache
	arm_write_sctlr(sctlr);

	/* run early secondary cpu init routines up to the threading level */
	lk_init_level(LK_INIT_FLAG_SECONDARY_CPUS, LK_INIT_LEVEL_EARLIEST, LK_INIT_LEVEL_THREADING - 1);

	arch_mp_init_percpu();

	LTRACEF("cpu num %d\n", cpu);
	LTRACEF("sctlr 0x%x\n", arm_read_sctlr());
	LTRACEF("actlr 0x%x\n", arm_read_actlr());

	/* we're done, tell the main cpu we're up */
	atomic_add(&secondaries_to_init, -1);
	smp_mb();
	__asm__ volatile("sev");

	lk_secondary_cpu_entry();
}
#endif

static void arm_basic_setup(void)
{
	uint32_t sctlr = arm_read_sctlr();

	/* ARMV7 bits */
	sctlr &= ~(1<<10); /* swp disable */
	sctlr |=  (1<<11); /* enable program flow prediction */
	sctlr &= ~(1<<14); /* random cache/tlb replacement */
	sctlr &= ~(1<<25); /* E bit set to 0 on exception */
	sctlr &= ~(1<<30); /* no thumb exceptions */

	arm_write_sctlr(sctlr);

	uint32_t actlr = arm_read_actlr();
#if ARM_CPU_CORTEX_A9
	actlr |= (1<<2); /* enable dcache prefetch */
#if WITH_DEV_CACHE_PL310
	actlr |= (1<<7); /* L2 exclusive cache */
	actlr |= (1<<3); /* L2 write full line of zeroes */
	actlr |= (1<<1); /* L2 prefetch hint enable */
#endif
#if WITH_SMP
	/* enable smp mode, cache and tlb broadcast */
	actlr |= (1<<6) | (1<<0);
#endif
#endif // ARM_CPU_CORTEX_A9
#if ARM_CPU_CORTEX_A7
#if WITH_SMP
	/* enable smp mode */
	actlr |= (1<<6);
#endif
#endif // ARM_CPU_CORTEX_A7

	arm_write_actlr(actlr);

#if ENABLE_CYCLE_COUNTER && ARM_ISA_ARMV7
	/* enable the cycle count register */
	uint32_t en;
	__asm__ volatile("mrc	p15, 0, %0, c9, c12, 0" : "=r" (en));
	en &= ~(1<<3); /* cycle count every cycle */
	en |= 1; /* enable all performance counters */
	__asm__ volatile("mcr	p15, 0, %0, c9, c12, 0" :: "r" (en));

	/* enable cycle counter */
	en = (1<<31);
	__asm__ volatile("mcr	p15, 0, %0, c9, c12, 1" :: "r" (en));
#endif

#if ARM_WITH_VFP
	/* enable cp10 and cp11 */
	uint32_t val = arm_read_cpacr();
	val |= (3<<22)|(3<<20);
	arm_write_cpacr(val);

	/* set enable bit in fpexc */
	__asm__ volatile("mrc  p10, 7, %0, c8, c0, 0" : "=r" (val));
	val |= (1<<30);
	__asm__ volatile("mcr  p10, 7, %0, c8, c0, 0" :: "r" (val));

	/* make sure the fpu starts off disabled */
	arm_fpu_set_enable(false);
#endif

	/* set the vector base to our exception vectors so we dont need to double map at 0 */
#if ARM_ISA_ARMV7
	arm_write_vbar(KERNEL_BASE + KERNEL_LOAD_OFFSET);
#endif
}

void arch_quiesce(void)
{
#if ENABLE_CYCLE_COUNTER
#if ARM_ISA_ARMV7
	/* disable the cycle count and performance counters */
	uint32_t en;
	__asm__ volatile("mrc	p15, 0, %0, c9, c12, 0" : "=r" (en));
	en &= ~1; /* disable all performance counters */
	__asm__ volatile("mcr	p15, 0, %0, c9, c12, 0" :: "r" (en));

	/* disable cycle counter */
	en = 0;
	__asm__ volatile("mcr	p15, 0, %0, c9, c12, 1" :: "r" (en));
#endif
#if ARM_CPU_ARM1136
	/* disable the cycle count and performance counters */
	uint32_t en;
	__asm__ volatile("mrc	p15, 0, %0, c15, c12, 0" : "=r" (en));
	en &= ~1; /* disable all performance counters */
	__asm__ volatile("mcr	p15, 0, %0, c15, c12, 0" :: "r" (en));
#endif
#endif

	uint32_t actlr = arm_read_actlr();
#if ARM_CPU_CORTEX_A9
	actlr = 0; /* put the aux control register back to default */
#endif // ARM_CPU_CORTEX_A9
	arm_write_actlr(actlr);
}

#if ARM_ISA_ARMV7
/* virtual to physical translation */
status_t arm_vtop(addr_t va, addr_t *pa)
{
	spin_lock_saved_state_t irqstate;

	arch_interrupt_save(&irqstate, SPIN_LOCK_FLAG_INTERRUPTS);

	arm_write_ats1cpr(va & ~(PAGE_SIZE-1));
	uint32_t par = arm_read_par();

	arch_interrupt_restore(irqstate, SPIN_LOCK_FLAG_INTERRUPTS);

	if (par & 1)
		return ERR_NOT_FOUND;

	if (pa) {
		*pa = (par & 0xfffff000) | (va & 0xfff);
	}

	return NO_ERROR;
}
#endif

void arch_chain_load(void *entry, ulong arg0, ulong arg1, ulong arg2, ulong arg3)
{
	LTRACEF("entry %p, args 0x%lx 0x%lx 0x%lx 0x%lx\n", entry, arg0, arg1, arg2, arg3);

	/* we are going to shut down the system, start by disabling interrupts */
	arch_disable_ints();

	/* give target and platform a chance to put hardware into a suitable
	 * state for chain loading.
	 */
	target_quiesce();
	platform_quiesce();

	paddr_t entry_pa;
	paddr_t loader_pa;

#if WITH_KERNEL_VM
	/* get the physical address of the entry point we're going to branch to */
	if (arm_vtop((addr_t)entry, &entry_pa) < 0) {
		panic("error translating entry physical address\n");
	}

	/* add the low bits of the virtual address back */
	entry_pa |= ((addr_t)entry & 0xfff);

	LTRACEF("entry pa 0x%lx\n", entry_pa);

	/* figure out the mapping for the chain load routine */
	if (arm_vtop((addr_t)&arm_chain_load, &loader_pa) < 0) {
		panic("error translating loader physical address\n");
	}

	/* add the low bits of the virtual address back */
	loader_pa |= ((addr_t)&arm_chain_load & 0xfff);

	paddr_t loader_pa_section = ROUNDDOWN(loader_pa, SECTION_SIZE);

	LTRACEF("loader address %p, phys 0x%lx, surrounding large page 0x%lx\n",
			&arm_chain_load, loader_pa, loader_pa_section);

	/* using large pages, map around the target location */
	arch_mmu_map(loader_pa_section, loader_pa_section, (2 * SECTION_SIZE / PAGE_SIZE), 0);
#else
	/* for non vm case, just branch directly into it */
	entry_pa = (paddr_t)entry;
	loader_pa = (paddr_t)&arm_chain_load;
#endif

	LTRACEF("disabling instruction/data cache\n");
	arch_disable_cache(UCACHE);
#if WITH_DEV_CACHE_PL310
	pl310_set_enable(false);
#endif

	/* put the booting cpu back into close to a default state */
	arch_quiesce();

	LTRACEF("branching to physical address of loader\n");

	/* branch to the physical address version of the chain loader routine */
	void (*loader)(paddr_t entry, ulong, ulong, ulong, ulong) __NO_RETURN = (void *)loader_pa;
	loader(entry_pa, arg0, arg1, arg2, arg3);
}

static spin_lock_t lock = 0;

static void spinlock_test(void)
{
	TRACE_ENTRY;

	spin_lock_saved_state_t state;
	spin_lock_irqsave(&lock, state);

	TRACEF("cpu0: i have the lock\n");
	spin(1000000);
	TRACEF("cpu0: releasing it\n");

	spin_unlock_irqrestore(&lock, state);

	spin(1000000);
}

static void spinlock_test_secondary(void)
{
	TRACE_ENTRY;

	spin(500000);
	spin_lock_saved_state_t state;
	spin_lock_irqsave(&lock, state);

	TRACEF("cpu1: i have the lock\n");
	spin(250000);
	TRACEF("cpu1: releasing it\n");

	spin_unlock_irqrestore(&lock, state);
}

/* vim: set ts=4 sw=4 noexpandtab: */


text:
/*
 * (C) 2007-2012 Alibaba Group Holding Limited.
 *
 * 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.
 * Authors:
 *   wuhua <wq163@163.com> , boyan <killme2008@gmail.com>
 */
package com.taobao.metamorphosis.server.network;

import org.easymock.classextension.EasyMock;
import org.junit.Before;
import org.junit.Test;

import com.taobao.metamorphosis.network.BooleanCommand;
import com.taobao.metamorphosis.network.HttpStatus;
import com.taobao.metamorphosis.network.VersionCommand;
import com.taobao.metamorphosis.server.utils.BuildProperties;

public class VersionProcessorUnitTest extends BaseProcessorUnitTest {

    private VersionProcessor processor;

    @Before
    public void setUp() {
        this.mock();
        this.processor = new VersionProcessor(this.commandProcessor);
    }

    @Test
    public void testHandleRequest() throws Exception {
        final int opaque = 1;
        this.conn.response(new BooleanCommand(HttpStatus.Success, BuildProperties.VERSION, opaque));
        EasyMock.expectLastCall();
        this.mocksControl.replay();
        this.processor.handleRequest(new VersionCommand(opaque), this.conn);
        this.mocksControl.verify();
    }
}


text:
:- module(http_request_value,
	  [ http_parse_header_value/3	% +Header, +HeaderValue, -MediaTypes
	  ]).
:- use_module(library(http/dcg_basics)).
:- use_module(library(pairs)).
:- use_module(library(lists)).

/** <module> Analyse values from HTTP request fields

The HTTP server parses some common  fields   in  the request header into
meaningful Prolog terms. Some fields however are not frequently used and
rather hard to parse. This library is intended  to grow in to a complete
library for processing header fields.

@tbd	Clients will frequently use same the value for many of these
	fields.  It is probably worthwhile to maintain a cache of
	translations.
*/

%%	http_parse_header_value(+Field, +Value, -Prolog) is semidet.
%
%	Translate Value in a meaningful Prolog   term. Field denotes the
%	HTTP request field for which we   do  the translation. Supported
%	fields are:
%
%	  * accept
%
%	@error	domain_error(http_request_field, Field) if this
%		library is not prepared to handle this field (yet).

http_parse_header_value(accept, Value, Prolog) :- !,
	http_parse_accept_header(Value, Prolog).
http_parse_header_value(Field, _, _) :-
	domain_error(http_request_field, Field).

%%	http_parse_accept_header(+Header, -Fields) is semidet.
%
%	Parse an =|Accept:|=  header,  returning   a  list  of  accepted
%	media-type sorted by quality. If   multiple media-types have the
%	same quality, the most specific appears   first.  Each member of
%	the list is a term
%
%	    media(Type/Subtype, ListOfParameters, Quality, AcceptExtension)
%
%	Type and/or Subtype is a variable if the specified value is =|*|=.
%
%	@see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

http_parse_accept_header(Header, Media) :-
	atom_codes(Header, Codes),
	phrase(accept(Media0), Codes),
	keysort(Media0, Media1),
	pairs_values(Media1, MediaR),
	reverse(MediaR, Media).

accept([H|T]) -->
	blanks,
	media_range(H),
	blanks,
	(   ","
	->  accept(T)
	;   {T=[]}
	).

media_range(s(Quality,Spec)-media(Type, TypeParams, Quality, AcceptExts)) -->
	media_type(Type),
	blanks,
	(   ";"
	->  blanks,
	    parameters_and_quality(TypeParams, Quality, AcceptExts)
	;   { TypeParams = [],
	      Quality = 1.0,
	      AcceptExts = []
	    }
	),
	{ rank_specialised(Type, TypeParams, Spec) }.

%%	rank_specialised(+Type, +TypeParam, -Key) is det.
%
%	Although the specification linked  above   is  unclear, it seems
%	that  more  specialised  types  must   be  preferred  over  less
%	specialized ones.
%
%	@tbd	Is there an official specification of this?

rank_specialised(Type/SubType, TypeParams, v(VT, VS, VP)) :-
	var_or_given(Type, VT),
	var_or_given(SubType, VS),
	length(TypeParams, VP).

var_or_given(V, Val) :-
	(   var(V)
	->  Val = 0
	;   Val = 1
	).

media_type(Type/SubType) -->
	type(Type), "/", type(SubType).

type(_) -->
	"*", !.
type(Type) -->
	token(Type).

parameters_and_quality(Params, Quality, AcceptExts) -->
	token(Name),
	blanks, "=", blanks,
	(   { Name == q }
	->  float(Quality), blanks,
	    accept_extensions(AcceptExts),
	    { Params = [] }
	;   { Params = [Name=Value|T] },
	    parameter_value(Value),
	    blanks,
	    (	";"
	    ->	blanks,
		parameters_and_quality(T, Quality, AcceptExts)
	    ;	{ T = [],
		  Quality = 1.0,
		  AcceptExts = []
		}
	    )
	).

accept_extensions([H|T]) -->
	";", !,
	blanks, token(Name), blanks,
	(   "="
	->  blanks,
	    (	token(Value)
	    ->	[]
	    ;	quoted_string(Value)
	    ),
	    { H = (Name=Value) }
	;   { H = Name }
	),
	blanks,
	accept_extensions(T).
accept_extensions([]) -->
	[].

parameter_value(Value) -->
	(   token(Value)
	->  []
	;   quoted_string(Value)
	).

%%	token(-Name)// is semidet.
%
%	Process an HTTP header token from the input.

token(Name) -->
	token_char(C1),
	token_chars(Cs),
	{ atom_codes(Name, [C1|Cs]) }.

token_chars([H|T]) -->
	token_char(H), !,
	token_chars(T).
token_chars([]) --> [].

token_char(C) -->
	[C],
	{   \+ ctl(C),
	    \+ separator_code(C)
	}, !.

ctl(C) :- between(0,31,C), !.
ctl(127).

separator_code(0'().
separator_code(0')).
separator_code(0'<).
separator_code(0'>).
separator_code(0'@).
separator_code(0',).
separator_code(0';).
separator_code(0':).
separator_code(0'\\).
separator_code(0'").
separator_code(0'/).
separator_code(0'[).
separator_code(0']).
separator_code(0'?).
separator_code(0'=).
separator_code(0'{).
separator_code(0'}).
separator_code(32).
separator_code(0'\t).

%%	quoted_string(-Text)// is semidet.
%
%	True if input starts with a quoted string representing Text.

quoted_string(Text) -->
	"\"",
	quoted_text(Codes),
	{ atom_codes(Text, Codes) }.

quoted_text([]) -->
	"\"", !.
quoted_text([H|T]) -->
	"\\", !, [H],
	quoted_text(T).
quoted_text([H|T]) -->
	[H], !,
	quoted_text(T).


text:
  Bourecq est
       un village
       situé dans le département des Pas-de-Calais en Nord-Pas-de-Calais. Elle comptait 518 habitants en 2008.

Le parc d'habitations, à Bourecq, était réparti en 2011 en sept appartements et 234 maisons soit
 un marché plutôt équilibré.

Si vous pensez emmenager à Bourecq, vous pourrez aisément trouver une maison à acheter.

À proximité de Bourecq sont localisées les communes de
Lillers située à 3 km, 9 926 habitants,
Saint-Hilaire-Cottes localisée à 1 km, 798 habitants,
Ham-en-Artois à 3 km, 971 habitants,
Mazinghem localisée à 3 km, 396 habitants,
Ecquedecques localisée à 1 km, 470 habitants,
Auchy-au-Bois située à 4 km, 420 habitants,
 entre autres. De plus, Bourecq est située à seulement 29 km de Liévin.

À Bourecq, le prix moyen à la vente d'un appartement se situe à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 416 € du m². À la location la valorisation moyenne se situe à 8,33 € du m² mensuel.

La ville compte quelques  équipements sportifs, elle dispose, entre autres, de un terrain de sport.


text:
using Nexmo.Api.Request;

namespace Nexmo.Api.ClientMethods
{
    public class NumberInsight
    {
        public Credentials Credentials { get; set; }
        public NumberInsight(Credentials creds)
        {
            Credentials = creds;
        }

        /// <summary>
        /// Performs basic semantic checks on given phone number.
        /// </summary>
        /// <param name="request">NI request</param>
        /// <param name="creds">(Optional) Overridden credentials for only this request</param>
        /// <returns></returns>
        public Api.NumberInsight.NumberInsightBasicResponse RequestBasic(Api.NumberInsight.NumberInsightRequest request, Credentials creds = null)
        {
            return Api.NumberInsight.RequestBasic(request, creds ?? Credentials);
        }

        /// <summary>
        /// Identifies the phone number type and, for mobile phone numbers, the network it is registered with.
        /// </summary>
        /// <param name="request">NI standard request</param>
        /// <param name="creds">(Optional) Overridden credentials for only this request</param>
        /// <returns></returns>
        public Api.NumberInsight.NumberInsightStandardResponse RequestStandard(Api.NumberInsight.NumberInsightRequest request, Credentials creds = null)
        {
            return Api.NumberInsight.RequestStandard(request, creds ?? Credentials);
        }

        /// <summary>
        /// Retrieve validity, roaming, and reachability information about a mobile phone number.
        /// </summary>
        /// <param name="request">NI advenced request</param>
        /// <param name="creds">(Optional) Overridden credentials for only this request</param>
        /// <returns></returns>
        public Api.NumberInsight.NumberInsightAdvancedResponse RequestAdvanced(Api.NumberInsight.NumberInsightRequest request, Credentials creds = null)
        {
            return Api.NumberInsight.RequestAdvanced(request, creds ?? Credentials);
        }

        /// <summary>
        /// Retrieve validity, roaming, and reachability information about a mobile phone number via a webhook
        /// </summary>
        /// <param name="request">NI advenced request</param>
        /// <param name="creds">(Optional) Overridden credentials for only this request</param>
        /// <returns></returns>
        public Api.NumberInsight.NumberInsightAsyncRequestResponse RequestAsync(Api.NumberInsight.NumberInsightAsyncRequest request, Credentials creds = null)
        {
            return Api.NumberInsight.RequestAsync(request, creds ?? Credentials);
        }

        /// <summary>
        /// Deserializes a NumberInsight response JSON string
        /// </summary>
        /// <param name="json">NumberInsight response JSON string</param>
        /// <returns></returns>
        public Api.NumberInsight.NumberInsightAdvancedResponse Response(string json)
        {
            return Api.NumberInsight.Response(json);
        }
    }
}


text:
<?php
/**
 * @namespace
 */
namespace Vein\Core\Crud\Helper\Form\Field\Standart\Element;

use Vein\Core\Crud\Grid\Filter as Filter,
    Vein\Core\Crud\Form\Field as Field;

/**
 * Class form fields helper
 *
 * @category   Vein\Core
 * @package    Crud
 * @subpackage Helper
 */
class ManyToOne extends Combobox
{
    public static function _(Field\ArrayToSelect $field)
    {
        $element = $field->getElement();

        $width = $field->getWidth();
        $element->setAttribute('width', $width);

        return $element->render();
    }
}


text:
from django.core.cache import InvalidCacheBackendError
from django.utils.encoding import smart_str, smart_unicode
from cio.backends.base import CacheBackend

class DjangoCacheBackend(CacheBackend):

    def __init__(self, **config):
        """
        Get cache backend. Look for djedi specific cache first, then fallback on default
        """
        super(DjangoCacheBackend, self).__init__(**config)

        try:
            from django.core.cache import get_cache
            cache_name = self.config.get('NAME', 'djedi')
            cache = get_cache(cache_name)
        except (InvalidCacheBackendError, ValueError):
            from django.core.cache import cache

        self._cache = cache

    def clear(self):
        self._cache.clear()

    def _get(self, key):
        return self._cache.get(key)

    def _get_many(self, keys):
        return self._cache.get_many(keys)

    def _set(self, key, value):
        self._cache.set(key, value, timeout=None)  # TODO: Fix eternal timeout like viewlet

    def _set_many(self, data):
        self._cache.set_many(data, timeout=None)  # TODO: Fix eternal timeout like viewlet

    def _delete(self, key):
        self._cache.delete(key)

    def _delete_many(self, keys):
        self._cache.delete_many(keys)

    def _encode_content(self, uri, content):
        """
        Join node uri and content as string and convert to bytes to ensure no pickling in memcached.
        """
        if content is None:
            content = self.NONE
        return smart_str(unicode(uri) + u'|' + content)

    def _decode_content(self, content):
        """
        Split node string to uri and content and convert back to unicode.
        """
        uri, _, content = content.partition('|')
        if content == self.NONE:
            content = None
        else:
            content = smart_unicode(content)
        return uri or None, content


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Marasmius pyropus Pat.

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<executable>
  <category>Cardiac MRI Toolkit</category>
  <title>Inhomogeneity Correction</title>
  <description><![CDATA[Inhomogeneity Correction for the CARMA Afib project.  This algorithm corrects specific types of intensity inhomogeneity.  Under the assumption that the LA blood pool should exhibit uniform intensity with Gaussian noise, we estimate localized intensity variation in the LA by fitting a second-order polynomial to intensity values only within the LA endocardium.  Intensity in the immediately adjacent LA wall is then normalized with respect to this model.  In contrast to the N4ITK MRI Bias correction filter, this filter makes certain assumptions about the MRI (e.g. blood pool uniformity), so it can correct the image in different ways.]]></description>
  <version>0.1.0</version>
  <documentation-url>http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Modules/SlicerModuleInhomogeneity</documentation-url>
  <license>Slicer</license>
  <contributor>Alan Morris (CARMA), Eugene Kholmovski (CARMA), Josh Cates (CARMA), Danny Perry (CARMA), Rob MacLeod (CARMA)</contributor>
  <acknowledgements><![CDATA[This work was supported by ...]]></acknowledgements>
  <parameters>
    IO
    <description>Input/output parameters</description>
    <image>
      <name>dataFileName</name>
      MRI image
      <channel>input</channel>
      <index>0</index>
      <description><![CDATA[MRI input image]]></description>
    </image>
    <image>
      <name>endoFileName</name>
      Blood Pool mask
      <channel>input</channel>
      <index>1</index>
      <description><![CDATA[Blood Pool (Endocardium) binary mask of the MRI]]></description>
    </image>
    <image>
      <name>roiFileName</name>
      ROI mask
      <channel>input</channel>
      <index>2</index>
      <description><![CDATA[Region to apply inhomogeneity correction]]></description>
    </image>
    <image>
      <name>outputFileName</name>
      Corrected Output
      <channel>output</channel>
      <index>3</index>
      <description><![CDATA[Corrected MRI]]></description>
    </image>
  </parameters>
</executable>


text:
namespace ZumoCommunity.MeetupAPI.Data.Enum
{
	public enum AssetType
	{
		Embed = 1,
		Download = 2
	}
}


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ESTADORECLAMOSUGERENCIA;

/**
 * ESTADORECLAMOSUGERENCIASearch represents the model behind the search form about `app\models\ESTADORECLAMOSUGERENCIA`.
 */
class ESTADORECLAMOSUGERENCIASearch extends ESTADORECLAMOSUGERENCIA
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['EST_ID'], 'integer'],
            [['EST_DESCRIPCION'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ESTADORECLAMOSUGERENCIA::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'EST_ID' => $this->EST_ID,
        ]);

        $query->andFilterWhere(['like', 'EST_DESCRIPCION', $this->EST_DESCRIPCION]);

        return $dataProvider;
    }
}


text:
package spiritofmetal

import (
	"reflect"
	"testing"

	"github.com/StalkR/goircbot/lib/metal"
)

func TestSearch(t *testing.T) {
	for _, tt := range []struct {
		name string
		want []metal.Band
	}{
		{
			name: "converge",
			want: []metal.Band{
				metal.Band{Name: "Converge", Genre: "Hardcore", Country: "USA"},
				metal.Band{Name: "Convergence", Genre: "Death Dark", Country: "Austria"},
				metal.Band{Name: "Convergence", Genre: "Melodic Death", Country: "Italy"},
				metal.Band{Name: "Convergence From Within", Genre: "Death Metal", Country: "USA"},
				metal.Band{Name: "S.U.C.", Genre: "Death Grind", Country: "Brazil"},
			},
		},
		{
			name: "sdfgiousdfg",
			want: nil,
		},
	} {
		got, err := Search(tt.name)
		if err != nil {
			t.Errorf("Search(%s): err: %v", tt.name, err)
			continue
		}
		if !reflect.DeepEqual(got, tt.want) {
			t.Errorf("Search(%s): got %s; want %s", tt.name, got, tt.want)
		}
	}
}


text:
from lacore.exceptions import ApiAuthException, BaseAppException
from lacli.exceptions import PauseEvent
from lacli.server.interface.ClientInterface.ttypes import InvalidOperation
from lacli.server.interface.ClientInterface.ttypes import ErrorType
from lacli.log import getLogger
from twisted.python import log as twisted_log
from twisted.internet import defer
from functools import wraps
import errno

def log_hide(**kwargs):
    def decorator(f):
        setattr(f, '__hidden', kwargs)
        return f
    return decorator

def log_call(f):
    @wraps(f)
    @defer.inlineCallbacks
    def w(*args, **kwargs):
        hide = getattr(f, '__hidden', {})
        if len(args) > 0 and hasattr(args[0], "debug"):
            try:
                if int(args[0].debug) > 4:
                    hide = {}  # don't hide anything
            except:
                pass
        hidden = lambda k: k in hide and hide[k] is True
        maybe = lambda k, v: "<...>" if hidden(k) else v
        _as = maybe('_args', args[1:])
        _ks = {(k, maybe(k, v)) for k, v in kwargs.iteritems()}
        getLogger().debug("calling {} with {}, {}".format(f, _as, _ks))
        r = yield f(*args, **kwargs)
        getLogger().debug(
            "return value for {} is {}".format(f, maybe('_ret', r)))
        defer.returnValue(r)
    return w

def tthrow(f):
    """ Decorate a method to raise InvalidOperation instead
        of lacli exceptions
    """
    @wraps(f)
    @defer.inlineCallbacks
    def w(*args, **kwargs):
        r = None
        try:
            r = yield f(*args, **kwargs)
            defer.returnValue(r)
        except ApiAuthException as e:
            twisted_log.err(e)
            raise InvalidOperation(ErrorType.Authentication, e.msg)
        except NotImplementedError as e:
            getLogger().debug("{} is not implemented".format(f, r))
            raise InvalidOperation(ErrorType.NotImplemented, str(e))
        except OSError as e:
            getLogger().debug("{} threw exception".format(f), exc_info=True)
            if e.errno == errno.ENOENT:
                raise InvalidOperation(ErrorType.FileNotFound,
                                       "File not found",
                                       filename=e.filename)
            if e.errno == errno.EACCES:
                raise InvalidOperation(
                    ErrorType.Other, "Access denied or file in use")
            getLogger().debug("unknown exception", exc_info=True)
            raise InvalidOperation(ErrorType.Other, "Unknown error")
        except IOError as e:
            getLogger().debug("{} threw exception".format(f), exc_info=True)
            if e.errno == errno.ENOENT:
                raise InvalidOperation(ErrorType.FileNotFound,
                                       "File not found",
                                       filename=e.filename)
            if e.errno == errno.ENOSPC:
                raise InvalidOperation(ErrorType.Other,
                                       "No space left on device")
            getLogger().debug("unknown exception", exc_info=True)
            raise InvalidOperation(ErrorType.Other, "")
        except ValueError as e:
            getLogger().debug("{} threw exception".format(f), exc_info=True)
            raise InvalidOperation(ErrorType.Validation, str(e))
        except BaseAppException as e:
            getLogger().debug("application exception", exc_info=True)
            twisted_log.err(e)
            raise InvalidOperation(ErrorType.Other, str(e))
        except PauseEvent:
            pass
        except Exception as e:
            getLogger().debug("unknown exception", exc_info=True)
            twisted_log.err(e)
            raise InvalidOperation(ErrorType.Other, "Unknown error")
    return log_call(w)


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Soumyajit De, Bjoern Esser
 */
#ifndef TRACE_SAMPLER_H_
#define TRACE_SAMPLER_H_

#include <shogun/lib/config.h>
#include <shogun/base/SGObject.h>
#include <shogun/base/Parameter.h>

namespace shogun
{
template<class T> class SGVector;

/** @brief Abstract template base class that provides an interface for sampling
 * the trace of a linear operator using an abstract sample method
 */
class CTraceSampler : public CSGObject
{
public:
	/** default constructor */
	CTraceSampler()
	: CSGObject()
	{
		init();

		SG_GCDEBUG("%s created (%p)\n", this->get_name(), this)
	}

	/**
	 * constructor
	 *
	 * @param dimension the dimension of the sample vectors
	 */
	CTraceSampler(index_t dimension)
	: CSGObject()
	{
		init();

		m_dimension=dimension;

		SG_GCDEBUG("%s created (%p)\n", this->get_name(), this)
	}

	/** destructor */
	virtual ~CTraceSampler()
	{
		SG_GCDEBUG("%s destroyed (%p)\n", this->get_name(), this)
	}

	/**
	 * abstract method that generates the samples
	 *
	 * @param idx the index which determines which sample to draw
	 * @return the sample vector
	 */
	virtual SGVector<float64_t> sample(index_t idx) const = 0;

	/**
	 * abstract method for initializing the sampler, number of samples etc,
	 * must be called before sample
	 */
	virtual void precompute() = 0;

	/** @return the number of samples */
	virtual const index_t get_num_samples() const
	{
		return m_num_samples;
	}

	/** @return the number of samples */
	virtual const index_t get_dimension() const
	{
		return m_dimension;
	}

	/** @return object name */
	virtual const char* get_name() const
	{
		return "TraceSampler";
	}

protected:
	/** the dimension of the sample vectors */
	index_t m_dimension;

	/** the number of samples this sampler will generate, set by implementation */
	index_t m_num_samples;

private:
	/** initialize with default values and register params */
	void init()
	{
		m_num_samples=0;
		m_dimension=0;

		SG_ADD(&m_num_samples, "num_samples",
			"Number of samples this sampler can generate");

		SG_ADD(&m_dimension, "sample_dimension",
			"Dimension of samples this sampler can generate");
	}
};

}

#endif // TRACE_SAMPLER_H_


text:
namespace extensions {
class ShellAppWindow;
}

namespace views {
class WebView;
}

namespace athena {

class AppActivityRegistry;

// The activity object for a hosted V2 application.
class AppActivity : public Activity,
                    public ActivityViewModel,
                    public content::WebContentsObserver {
 public:
  explicit AppActivity(extensions::ShellAppWindow* app_window);
  virtual ~AppActivity();

  // Activity:
  virtual athena::ActivityViewModel* GetActivityViewModel() OVERRIDE;
  virtual void SetCurrentState(Activity::ActivityState state) OVERRIDE;
  virtual ActivityState GetCurrentState() OVERRIDE;
  virtual bool IsVisible() OVERRIDE;
  virtual ActivityMediaState GetMediaState() OVERRIDE;
  virtual aura::Window* GetWindow() OVERRIDE;

  // ActivityViewModel:
  virtual void Init() OVERRIDE;
  virtual SkColor GetRepresentativeColor() const OVERRIDE;
  virtual base::string16 GetTitle() const OVERRIDE;
  virtual bool UsesFrame() const OVERRIDE;
  virtual views::View* GetContentsView() OVERRIDE;
  virtual void CreateOverviewModeImage() OVERRIDE;
  virtual gfx::ImageSkia GetOverviewModeImage() OVERRIDE;

 protected:
  // content::WebContentsObserver:
  virtual void TitleWasSet(content::NavigationEntry* entry,
                           bool explicit_set) OVERRIDE;
  virtual void DidUpdateFaviconURL(
      const std::vector<content::FaviconURL>& candidates) OVERRIDE;
  virtual void DidStartNavigationToPendingEntry(
        const GURL& url,
        content::NavigationController::ReloadType reload_type) OVERRIDE;

 private:
  // Register this activity with its application.
  void RegisterActivity();

  scoped_ptr<extensions::ShellAppWindow> app_window_;
  views::WebView* web_view_;

  // The current state for this activity.
  ActivityState current_state_;

  // The image which will be used in overview mode.
  gfx::ImageSkia overview_mode_image_;

  // If known the registry which holds all activities for the associated app.
  // This object is owned by |AppRegistry| and will be a valid pointer as long
  // as this object lives.
  AppActivityRegistry* app_activity_registry_;

  DISALLOW_COPY_AND_ASSIGN(AppActivity);
};

}  // namespace athena

#endif  // ATHENA_CONTENT_APP_ACTIVITY_H_


text:
Automated build of node.js with Docker
===========
[![Docker Repository on Quay](https://quay.io/repository/jacksoncage/node/status "Docker Repository on Quay")](https://quay.io/repository/jacksoncage/node)

### Startup environment variables
Docker will make of the following environment variables when starting `start.sh`. Default values are:

	EXECUTER node
	APP start

### Use the pre built image
The pre built image can be downloaded using docker directly. After that you do not need to use this command again, you will have the image on your machine.

	$ docker pull jacksoncage/node

### Build the docker image by yourself
If you prefer you can easily build the docker image by yourself. After this the image is ready for use on your machine and can be used for multiple starts.

	$ cd node-docker
	$ docker build -t jacksoncage/node .

### Start the container
The container has all pre requisites set up to run any node.js application.

	$ docker run -i -d -p 8080 -v `pwd`/www:/var/www:ro -v /etc/localtime:/etc/localtime jacksoncage/node

Can also be run with `nodemon` as `EXECUTER`

	$ docker run -i -d -p 8080 -e EXECUTER=nodemon -e APP=app.js -v `pwd`/www:/var/www:ro -v /etc/localtime:/etc/localtime jacksoncage/node

Give it a short coffee break before trying the browser on url http://localhost:8080.

#### Start the container and keep control
The command above starts the container in deamon mode (-d) and runs in the background. If you want to start it by yourself just to see what happens use this command:

	$ docker run -i -t -p 8080 -v `pwd`/www:/var/www:ro jacksoncage/node bash

Notice the two changes made here, first we replaced the deamon switch (-d) with the tty switch (-t) which pipes the std in and std out to your terminal.

You now end up as a root user in the docker container and can do simple things like ls, cd and more. More complex things can be achieved after a `apt-get install` of one or more software(s) of choice.

### Get the container ip and port
The first command inspects your created container and get the IPv4 address. Second command docker exported port for 8080.

    $ docker inspect <container_id> | grep IPAddress | cut -d '"' -f 4
    $ docker port <container_id> 8080 | cut -d ":" -f2

Now go to `<your container's ip>:<container's port>` in your browser

### Stop the container
Stopping a running container is possible via the docker api. If only one instance of this container is running this command will stop it:

	docker stop `docker ps |grep jacksoncage/node |cut -d\  -f1`


text:
define( [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/_base/Deferred',
            'dojo/store/JsonRest',
            'dojo/store/util/QueryResults',
            'JBrowse/Digest/Crc32'
        ],
        function(
            declare,
            array,
            Deferred,
            dojoJSONRest,
            QueryResults,
            digest
        ) {

return declare( null, {

    constructor: function( args ) {
        // make sure url has a trailing slash
        var url = /\/$/.test( args.url ) ? args.url : args.url + '/';
        this.bucketStore = new dojoJSONRest({
            target: url
        });

        this.meta = {};

        this.browser = args.browser;

        // this.ready is a Deferred that will be resolved when we have
        // read the meta.json file with the params of this hashstore
        this.ready = this._readMeta();
    },

    _readMeta: function() {
        var thisB = this;
        return this.bucketStore.get( 'meta.json' )
            .then( function( meta ) {
                dojo.mixin( thisB.meta, meta || {} );
                thisB.meta.hash_hex_characters = Math.ceil( thisB.meta.hash_bits / 4 );
            });
    },

    query: function( query, options ) {
        return this.get( (query.name || '').toString() )
                   .then( function( value ) {
                              return QueryResults( (value||{}).exact || [] );
                          });
    },

    get: function( key ) {
        return this._getBucket(key)
                   .then( function( bucket ) {
                        return bucket[key];
                    });
    },

    _getBucket: function( key ) {
        var thisB = this;
        var bucketP = new Deferred();
        this.ready.then( function() {
            var bucketIdent = thisB._hash( key );
            thisB.bucketStore.get( thisB._hexToDirPath( bucketIdent ) )
                 .then(function(d) { bucketP.resolve(d); } );
        });

        return bucketP;
    },

    _hexToDirPath: function( hex ) {
        // zero-pad the hex string to be 8 chars if necessary
        while( hex.length < 8 )
            hex = '0'+hex;
        hex = hex.substr( 8-this.meta.hash_hex_characters );
        var dirpath = [];
        for( var i = 0; i < hex.length; i += 3 ) {
            dirpath.push( hex.substring( i, i+3 ) );
        }
        return dirpath.join('/') + '.json';
    },

    _hash: function( data ) {
        return digest.objectFingerprint( data )
                     .toString(16)
                     .toLowerCase()
                     .replace('-','n');
    },

    getIdentity: function( object ) {
        return object.id;
    }
});
});


text:
package minion

type OnlineClient struct {
	Name  string
	Proxy *MinionProxy
}

type OnlineClients map[*OnlineClient]bool

func (o OnlineClients) Remove(client *OnlineClient) {
	delete(o, client)
}

func (o OnlineClients) Add(client *OnlineClient) {
	o[client] = true
}


text:
""" Benstalkd Worker class

An easy way to develop scripts for handling jobs put on a beanstalkd work queue server.

Beanstalk is a simple, fast workqueue service. Its interface is generic,
but was originally designed for reducing the latency of page views in high-volume
web applications by running time-consuming tasks asynchronously.

More about beanstlkd: http://kr.github.com/beanstalkd/

Basic Usage:

    from beanstalkw import Worker

    class MyWorker(Worker):
        def on_job(self, job):
            pass

    MyWorker(host='...', port='...', tube='...').run()

Check test.py for an working example.

"""

__license__ = '''
Copyright (C) 2010 Andrei Savu

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

import threading
import logging
import time

from beanstalkc import Connection, SocketError

class Job(object):
    """ Wrapper around a job object. Adds done() method as synonym to delete() """
    def __init__(self, obj):
        self.obj = obj

    def __getattr__(self, name):
        return getattr(self.obj, name)

    def done(self):
        return self.obj.delete()

class Worker(object):
    log = logging.getLogger()

    def __init__(self, tube='default', host='localhost', port=11300):
        self.tube = tube
        self.host, self.port = host, port

        try:
            self._connect()

        except SocketError:
            self.log.error('start failed. unable to connect to queue.')
            self.reconnect()

    def _connect(self):
       self.conn = Connection(self.host, self.port)
       self._watch_only(self.tube)

    def _watch_only(self, tube):
        for t in self.conn.watching():
            if t != tube: self.conn.ignore(t)
        self.conn.watch(tube)

    def reconnect(self):
        while True:
            self.log.info('trying to reconnect to work queue.')
            try:
                self._connect()

                self.log.info('reconnected to queue host=%s port=%d.' % (self.host, self.port))
                break

            except SocketError:
                self.log.error('reconnect failed. waiting 10 seconds before retrying.')
                time.sleep(10)

    def run(self):
        """ Worker main loop. Reserve job and execute. """
        try:
            while True:
                self.cycle()
        except KeyboardInterrupt:
            self.log.info('got exit request. bye bye!')
            pass

    def cycle(self):
        try:
            self.log.info('waiting for jobs.')

            job = self.conn.reserve()

            if job is not None:
                self.log.info('got job with id #%d' % job.jid)
                self.on_job(Job(job))

        except SocketError:
            self.reconnect()

        except Exception, e:
            self.log.exception('got unexpected exception when running job')
            pass # nothing else to do. the worker should keep running

    def on_job(self, job):
        """ Handles a new job

        When a new job arrives this method is called. You should override
        this method in the class implementing the worker.
        """
        pass

class AsyncWorker(Worker, threading.Thread):

    def __init__(self, *args, **kwargs):
        Worker.__init__(self, *args, **kwargs)
        threading.Thread.__init__(self)


text:
<?php

/**
 * Imports macros.
 *
 * <pre>
 *   {% from 'forms.html' import forms %}
 * </pre>
 */
class Twig_TokenParser_From extends Twig_TokenParser
{

    /**
     * Parses a token and returns a node.
     *
     * @param Twig_Token $token A Twig_Token instance
     *
     * @return Twig_NodeInterface A Twig_NodeInterface instance
     */
    public function parse( Twig_Token $token )
    {

        $macro = $this->parser->getExpressionParser()->parseExpression();
        $stream = $this->parser->getStream();
        $stream->expect( 'import' );

        $targets = array();
        do {
            $name = $stream->expect( Twig_Token::NAME_TYPE )->getValue();

            $alias = $name;
            if ($stream->nextIf( 'as' )) {
                $alias = $stream->expect( Twig_Token::NAME_TYPE )->getValue();
            }

            $targets[$name] = $alias;

            if (!$stream->nextIf( Twig_Token::PUNCTUATION_TYPE, ',' )) {
                break;
            }
        } while (true);

        $stream->expect( Twig_Token::BLOCK_END_TYPE );

        $node = new Twig_Node_Import( $macro,
            new Twig_Node_Expression_AssignName( $this->parser->getVarName(), $token->getLine() ), $token->getLine(),
            $this->getTag() );

        foreach ($targets as $name => $alias) {
            $this->parser->addImportedSymbol( 'function', $alias, 'get'.$name, $node->getNode( 'var' ) );
        }

        return $node;
    }

    /**
     * Gets the tag name associated with this token parser.
     *
     * @return string The tag name
     */
    public function getTag()
    {

        return 'from';
    }
}


text:
Code outline:

- `main.py` sets up the options and the top-level call to TRPO.
- `trpo.py` contains the TRPO agent, describing how it gets paths, computes
  advantages, etc.
- `utils_trpo.py` contains two particular utils ...
- `fxn_approx.py` contains linear and neural network value functions.


text:
package org.apache.any23.cli;

import org.junit.Ignore;
import org.junit.Test;

/**
 * Test case for {@link MicrodataParser} CLI.
 *
 * @author Michele Mostarda (mostarda@fbk.eu)
 */
public class MicrodataParserTest extends ToolTestBase {

    public MicrodataParserTest() {
        super(MicrodataParser.class);
    }

    @Test
    public void testRunOnFile() throws Exception {
        runToolCheckExit0("file:"+copyResourceToTempFile("/microdata/microdata-nested.html").getAbsolutePath());
    }

    @Ignore("ANY23-140 - Revise Any23 tests to remove fetching of web content")
    @Test
    public void testRunOnHTTPResource() throws Exception {
        runToolCheckExit0("http://www.imdb.com/title/tt1375666/");
    }

}


text:
package org.diirt.vtype;

/**
 * Alarm information. Represents the severity and name of the highest alarm
 * associated with the channel.
 *
 * @author carcassi
 */
public interface Alarm {

    /**
     * Returns the alarm severity, which describes the quality of the
     * value returned. Never null.
     *
     * @return the alarm severity
     */
    AlarmSeverity getAlarmSeverity();

    /**
     * Returns a brief text representation of the highest currently active alarm.
     * Never null.
     *
     * @return the alarm status
     */
    String getAlarmName();
}


text:
# mkdir-bluebird
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![Dependency Status][david-dm-image]][david-dm-url] [![NSP Status][nsp-image]][nsp-url]

promise wrapper for node's fs.mkdir() that ignores `EEXIST` by default.

wraps node's [`fs.mkdir()`][fs-mkdir], in a [bluebird][bluebird] promise that resolves with `true` if successful or rejects with the `Error` returned by `fs.mkdir()`; both results need to be handled by the code calling this function.

## table of contents
* [installation](#installation)
* [usage](#usage)
    * [mkdir( path[, mode][, ignore] )](#mkdir-path-mode-ignore-)
    * [default](#default)
    * [set ignore to false](#set-ignore-to-false)
    * [using node's path module](#using-nodes-path-module)
* [license](#license)

## installation
```javascript
npm install mkdir-bluebird
```

## usage
### mkdir( path[, mode][, ignore] )
```javascript
@param {string|buffer} path
@param {number} [mode = 0o777]
@param {boolean} [ignore = true] ignore `EEXIST` directory errors returned by `fs.mkdir()`
@returns {Promise}
```

### default
ignores `EEXIST` directory errors returned by `fs.mkdir()`
```javascript
var mkdir = require( 'mkdir-bluebird' );

mkdir( 'test-dir' )
  .then(
    /**
     * @param {boolean} result
     */
    function( result ) {
      // handle success
    }
  )
  .catch(
    /**
     * @param {Error} err
     */
    function( err ) {
      // handle error
    }
  );
```

### set ignore to `false`
acknowledges `EEXIST` directory errors returned by `fs.mkdir()`
```javascript
var mkdir = require( 'mkdir-bluebird' );

mkdir( 'test-dir', null, false )
  .then(
    /**
     * @param {boolean} result
     */
    function( result ) {
      // handle success
    }
  )
  .catch(
    /**
     * @param {Error} err
     */
    function( err ) {
      // handle error
    }
  );
```

### using node's path module
the path `__dirname/test` must exist in order to create the directory `test-dir` in it
```javascript
var mkdir = require( 'mkdir-bluebird' );
var path = require( 'path' );
var dirpath = path.join( __dirname, 'test', 'test-dir' );

mkdir( dirpath )
  .then(
    /**
     * @param {boolean} result
     */
    function( result ) {
      // handle success
    }
  )
  .catch(
    /**
     * @param {Error} err
     */
    function( err ) {
      // handle error
    }
  );
```

## license
[MIT License][mit-license]

[coveralls-image]: https://coveralls.io/repos/github/dan-nl/mkdir-bluebird/badge.svg?branch=master
[coveralls-url]: https://coveralls.io/github/dan-nl/mkdir-bluebird?branch=master
[david-dm-image]: https://david-dm.org/dan-nl/mkdir-bluebird.svg
[david-dm-url]: https://david-dm.org/dan-nl/mkdir-bluebird
[bluebird]: https://www.npmjs.com/package/bluebird
[fs-mkdir]: https://nodejs.org/api/fs.html#fs_fs_mkdir_path_mode_callback
[mit-license]: https://raw.githubusercontent.com/dan-nl/mkdir-bluebird/master/license.txt
[npm-image]: https://img.shields.io/npm/v/mkdir-bluebird.svg
[npm-url]: https://www.npmjs.com/package/mkdir-bluebird
[nsp-image]: https://nodesecurity.io/orgs/githubdan-nl/projects/159c1d65-8122-4061-8a2b-deda0739ceab/badge
[nsp-url]: https://nodesecurity.io/orgs/githubdan-nl/projects/159c1d65-8122-4061-8a2b-deda0739ceab
[travis-image]: https://travis-ci.org/dan-nl/mkdir-bluebird.svg?branch=master
[travis-url]: https://travis-ci.org/dan-nl/mkdir-bluebird


text:
package jframe.pay.wx.http.client;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

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

import com.alibaba.fastjson.JSON;

import jframe.pay.domain.DevType;
import jframe.pay.domain.PayException;
import jframe.pay.domain.dao.OrderWx;
import jframe.pay.wx.domain.WxConfig;
import jframe.pay.wx.domain.WxFields;
import jframe.pay.wx.http.ClientRequestHandler;
import jframe.pay.wx.http.PackageRequestHandler;
import jframe.pay.wx.http.PrepayIdRequestHandler;
import jframe.pay.wx.http.RequestHandler;
import jframe.pay.wx.http.ResponseHandler;
import jframe.pay.wx.http.util.WxCore;
import jframe.pay.wx.http.util.WxUtil;

/**
 * 微信接口方法
 *
 * @author dzh
 * @date Sep 25, 2014 8:38:27 PM
 * @since 1.0
 */
public class WxService implements WxFields {

    static Logger LOG = LoggerFactory.getLogger(WxService.class);

    /**
     * 生成预支付订单
     *
     * @param req
     * @return
     */
    public static boolean genPrePay(Map<String, String> req, Map<String, Object> rsp) throws Exception {
        String out_trade_no = WxUtil.genTradeNo();
        req.put(WxFields.F_orderNo, out_trade_no);
        // 设置package订单参数
        PackageRequestHandler packageReqHandler = new PackageRequestHandler(); // 生成package的请求类
        packageReqHandler.setKey(WxConfig.getConf(WxConfig.KEY_PARTNER_KEY));
        packageReqHandler.setParameter(WxFields.F_bank_type, "WX");// 银行渠道
        packageReqHandler.setParameter(WxFields.F_body, req.get(WxFields.F_payDesc)); // 商品描述
        packageReqHandler.setParameter(WxFields.F_notify_url, WxConfig.getConf(WxConfig.KEY_NOTIFY_URL)); // 接收财付通通知的URL
        packageReqHandler.setParameter(WxFields.F_partner, WxConfig.getConf(WxConfig.KEY_PARTNER)); // 商户号
        packageReqHandler.setParameter(WxFields.F_out_trade_no, out_trade_no); // 商家订单号
        packageReqHandler.setParameter(WxFields.F_total_fee, req.get(WxFields.F_payAmount)); // 商品金额,以分为单位
        packageReqHandler.setParameter(WxFields.F_spbill_create_ip, req.get(WxFields.F_remoteIp)); // 订单生成的机器IP,指用户浏览器端IP
        packageReqHandler.setParameter(WxFields.F_fee_type, "1"); // 币种,1人民币 66
        packageReqHandler.setParameter(WxFields.F_input_charset, WxConfig.getConf(WxConfig.KEY_CHARSET)); // 字符编码
        // 获取package包
        String packageValue = packageReqHandler.getRequestURL();

        // 设置获取prepayid支付参数
        String noncestr = WxUtil.getNonceStr();
        String timestamp = WxUtil.getTimeStamp();
        // 获取prepayid的请求类
        PrepayIdRequestHandler prepayReqHandler = new PrepayIdRequestHandler();
        prepayReqHandler.setParameter(WxFields.F_appid, WxConfig.getConf(WxConfig.KEY_APP_ID));
        prepayReqHandler.setParameter(WxFields.F_appkey, WxConfig.getConf(WxConfig.KEY_APP_KEY));
        prepayReqHandler.setParameter(WxFields.F_noncestr, noncestr);
        prepayReqHandler.setParameter(WxFields.F_package, packageValue);
        prepayReqHandler.setParameter(WxFields.F_timestamp, timestamp);
        prepayReqHandler.setParameter(WxFields.F_traceid, "");

        // 生成获取预支付签名
        String sign = prepayReqHandler.createSHA1Sign();
        // 增加非参与签名的额外参数
        prepayReqHandler.setParameter(WxFields.F_app_signature, sign);
        prepayReqHandler.setParameter(WxFields.F_sign_method, WxConfig.getConf(WxConfig.KEY_SIGN_METHOD));
        String gateUrl = WxConfig.getConf(WxConfig.KEY_GATE_URL) + "?access_token=" + req.get(WxFields.F_token);
        prepayReqHandler.setGateUrl(gateUrl);

        // 获取prepayId
        String prepayid = prepayReqHandler.sendPrepay();
        if (null != prepayid && !"".equals(prepayid)) {
            // packageValue = "Sign=" + packageValue; 返回客户端支付参数的请求类
            ClientRequestHandler clientHandler = new ClientRequestHandler();
            clientHandler.setParameter(WxFields.F_appid, WxConfig.getConf(WxConfig.KEY_APP_ID));
            clientHandler.setParameter(WxFields.F_appkey, WxConfig.getConf(WxConfig.KEY_APP_KEY));
            clientHandler.setParameter(WxFields.F_noncestr, noncestr);
            // if
            // (req.get(WxFields.F_devType).equals(DevType.ANDRIOD.toString()))
            // {
            // clientHandler.setParameter(WxFields.F_package, "Sign=" +
            // packageValue);
            // } else if
            // (req.get(WxFields.F_devType).equals(DevType.IOS.toString())) {
            // clientHandler.setParameter(WxFields.F_package, "Sign=WXPay");
            // } else {
            // throw new PayException("Invalid devType -> " +
            // req.get(WxFields.F_devType) + "when genPrePay");
            // }
            clientHandler.setParameter(WxFields.F_package, "Sign=" + packageValue);

            clientHandler.setParameter(WxFields.F_partnerid, WxConfig.getConf(WxConfig.KEY_PARTNER));
            clientHandler.setParameter(WxFields.F_prepayid, prepayid);
            clientHandler.setParameter(WxFields.F_timestamp, timestamp);
            sign = clientHandler.createSHA1Sign();

            // 这些是手机端需要的参数
            rsp.put(WxFields.F_appid, WxConfig.getConf(WxConfig.KEY_APP_ID));
            rsp.put(WxFields.F_partnerid, WxConfig.getConf(WxConfig.KEY_PARTNER));
            rsp.put(WxFields.F_prepayid, prepayid);
            rsp.put(WxFields.F_noncestr, noncestr);
            rsp.put(WxFields.F_timestamp, timestamp);
            rsp.put(WxFields.F_packageValue, packageValue);
            rsp.put(WxFields.F_payDesc, req.get(WxFields.F_payDesc));
            rsp.put(WxFields.F_sign, sign);

            return true;
        }
        return false;
    }

    public static boolean backPay(Map<String, String> req, Map<String, Object> rsp) {
        // 创建支付应答对象
        ResponseHandler resHandler = new ResponseHandler(req);
        resHandler.setKey(WxConfig.getConf(WxConfig.KEY_PARTNER_KEY));
        // 判断签名
        if (resHandler.isTenpaySign()) {
            // 通知id
            String notify_id = resHandler.getParameter(WxFields.F_notify_id);
            // 创建请求对象
            RequestHandler queryReq = new RequestHandler();
            // 通信对象
            TenpayHttpClient httpClient = new TenpayHttpClient();
            // 应答对象
            ClientResponseHandler queryRes = new ClientResponseHandler();

            // 通过通知ID查询,确保通知来至财付通
            queryReq.init();
            queryReq.setKey(WxConfig.getConf(WxConfig.KEY_PARTNER_KEY));
            queryReq.setGateUrl("https://gw.tenpay.com/gateway/verifynotifyid.xml");
            queryReq.setParameter(WxFields.F_partner, WxConfig.getConf(WxConfig.KEY_PARTNER));
            queryReq.setParameter("notify_id", notify_id);

            // 通信对象
            httpClient.setTimeOut(5);
            // 设置请求内容
            try {
                httpClient.setReqContent(queryReq.getRequestURL());
            } catch (UnsupportedEncodingException e) {
                LOG.error(e.getMessage());
                rsp.put(WxFields.F_result, WxFields.V_Fail);
                return false;
            }
            // 后台调用
            if (httpClient.call()) {
                // 设置结果参数
                try {
                    queryRes.setContent(httpClient.getResContent());
                } catch (Exception e) {
                    LOG.error(e.getMessage());
                    rsp.put(WxFields.F_result, WxFields.V_Fail);
                    return false;
                }
                queryRes.setKey(WxConfig.getConf(WxConfig.KEY_PARTNER_KEY));
                rsp.putAll(queryRes.getAllParameters());
                // 获取返回参数
                String retcode = queryRes.getParameter("retcode");
                String trade_state = queryRes.getParameter("trade_state");
                String trade_mode = queryRes.getParameter("trade_mode");
                // 判断签名及结果
                if (queryRes.isTenpaySign() && "0".equals(retcode) && "0".equals(trade_state)
                        && "1".equals(trade_mode)) {
                    rsp.put(WxFields.F_result, WxFields.V_Success);
                    rsp.put(WxFields.F_transactionId, queryRes.getParameter("transaction_id"));
                    return true;
                } else {
                    // 错误时,返回结果未签名,记录retcode、retmsg看失败详情。
                    // System.out.println("查询验证签名失败或业务错误");
                    // System.out.println("retcode:"
                    // + queryRes.getParameter("retcode") + " retmsg:"
                    // + queryRes.getParameter("retmsg"));

                }

            } else {
                // System.out.println("后台调用通信失败");
                // System.out.println(httpClient.getResponseCode());
                // System.out.println(httpClient.getErrInfo());
            }
        } else {
            // System.out.println("通知签名验证失败");
        }
        return false;
    }

    /**
     * 请求地址: https://api.weixin.qq.com/pay/orderquery?access_token=xxxxxx
     *
     * 请求数据: { "appid" : "wwwwb4f85f3a797777", "package" :
     * "out_trade_no=11122&partner=1900090055&sign=4e8d0df3da0c3d0df38f",
     * "timestamp" : "1369745073", "app_signature" :
     * "53cca9d47b883bd4a5c85a9300df3da0cb48565c", "sign_method" : "sha1" }
     *
     * 响应格式: { "errcode": 0, "errmsg": "ok", "order_info": { "ret_code": 0,
     * "ret_msg": "", "input_charset": "GBK", "trade_state": "0", "trade_mode":
     * "1", "partner": "1234567890", "bank_type": "CMB_FP", "bank_billno":
     * "201405273540085997", "total_fee": "1", "fee_type": "1",
     * "transaction_id": "1218614901201405273313473135", "out_trade_no":
     * "JfuKdiBig4zZnE4n", "is_split": "false", "is_refund": "false", "attach":
     * "", "time_end": "20140527194139", "transport_fee": "0", "product_fee":
     * "1", "discount": "0", "rmb_total_fee": "" } }
     *
     * 参考: http://www.cnblogs.com/txw1958/p/wxpay-order-query.html
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public static String queryPrePay(Map<String, String> req) throws Exception {
        String orderNo = req.get(WxFields.F_orderNo);
        String timestamp = req.get(WxFields.F_timestamp);
        String token = req.get(WxFields.F_token);
        // packageValue
        PackageRequestHandler packageReqHandler = new PackageRequestHandler();
        packageReqHandler.setKey(WxConfig.getConf(WxConfig.KEY_PARTNER_KEY));
        packageReqHandler.setParameter(WxFields.F_out_trade_no, orderNo);
        packageReqHandler.setParameter(WxFields.F_partner, WxConfig.getConf(WxConfig.KEY_PARTNER));
        String packageValue = packageReqHandler.getRequestURL();

        // app_signature
        PrepayIdRequestHandler reqHandler = new PrepayIdRequestHandler();
        reqHandler.setParameter(WxFields.F_appid, WxConfig.getConf(WxConfig.KEY_APP_ID));
        reqHandler.setParameter(WxFields.F_appkey, WxConfig.getConf(WxConfig.KEY_APP_KEY));
        reqHandler.setParameter(WxFields.F_package, packageValue);
        // yyyyMMddHHmmss
        reqHandler.setParameter(WxFields.F_timestamp, timestamp);
        String appsign = reqHandler.createSHA1Sign();

        // postdata
        Map<String, String> postData = new HashMap<String, String>();
        postData.put(WxFields.F_appid, WxConfig.getConf(WxConfig.KEY_APP_ID));
        postData.put(WxFields.F_package, packageValue);
        postData.put(WxFields.F_timestamp, timestamp);
        postData.put(WxFields.F_app_signature, appsign);
        postData.put(WxFields.F_sign_method, WxFields.V_SHA1);

        // 通信对象
        TenpayHttpClient httpClient = new TenpayHttpClient();
        httpClient.setTimeOut(5);
        httpClient.callHttpPost("https://api.weixin.qq.com/pay/orderquery?access_token=" + token,
                JSON.toJSONString(postData));
        return httpClient.getResContent();
    }

    /**
     * TODO 根据收到的请求数据,解析成map
     *
     * @param content
     * @param req
     * @throws Exception
     */
    public static void verifyResponse(String content, Map<String, String> req) {
        try {
            req = WxCore.parseQString(content);
        } catch (UnsupportedEncodingException e) {
            LOG.error("Parse wx response error {}", content);
        }
    }

    /**
     * 退款
     *
     * @param pay
     * @param respMap
     * @return
     * @throws Exception
     */
    public static boolean refund(OrderWx pay, Map<String, String> rspMap) throws Exception {
        String out_refund_no = WxUtil.genTradeNo();
        rspMap.put("out_refund_no", out_refund_no);

        // 商户号
        String partner = WxConfig.getConf(WxConfig.KEY_PARTNER);

        // 密钥
        String key = WxConfig.getConf(WxConfig.KEY_PARTNER_KEY);

        // 创建查询请求对象
        RequestHandler reqHandler = new RequestHandler();
        // 通信对象
        TenpayHttpClient httpClient = new TenpayHttpClient();
        // 应答对象
        ClientResponseHandler resHandler = new ClientResponseHandler();

        // -----------------------------
        // 设置请求参数
        // -----------------------------
        reqHandler.init();
        reqHandler.setKey(key);
        reqHandler.setGateUrl("https://mch.tenpay.com/refundapi/gateway/refund.xml");

        // -----------------------------
        // 设置接口参数
        // -----------------------------
        reqHandler.setParameter("service_version", "1.1");
        reqHandler.setParameter("partner", partner);
        reqHandler.setParameter("out_trade_no", pay.orderNo);
        reqHandler.setParameter("transaction_id", pay.transactionId);
        reqHandler.setParameter("out_refund_no", out_refund_no);
        reqHandler.setParameter("total_fee", String.valueOf(pay.payAmount));
        reqHandler.setParameter("refund_fee", String.valueOf(pay.payAmount));
        reqHandler.setParameter("op_user_id", partner);
        // 操作员密码,MD5处理
        reqHandler.setParameter("op_user_passwd", key);

        reqHandler.setParameter("recv_user_id", pay.recvUserId);
        reqHandler.setParameter("recv_user_name", pay.recvUserName);
        // -----------------------------
        // 设置通信参数
        // -----------------------------
        // 设置请求返回的等待时间
        httpClient.setTimeOut(5);
        // 设置ca证书
        // httpClient.setCaInfo(new File("e:/cacert.pem"));

        // 设置个人(商户)证书
        // httpClient.setCertInfo(new File("e:/1900000109.pfx"), "1900000109");

        // 设置发送类型POST
        httpClient.setMethod("POST");

        // 设置请求内容
        String requestUrl = reqHandler.getRequestURL();
        httpClient.setReqContent(requestUrl);
        String rescontent = "null";

        // 后台调用
        if (httpClient.call()) {
            // 设置结果参数
            rescontent = httpClient.getResContent();
            resHandler.setContent(rescontent);
            resHandler.setKey(key);

            // 获取返回参数
            String retcode = resHandler.getParameter("retcode");

            // 判断签名及结果
            if (resHandler.isTenpaySign() && "0".equals(retcode)) {
                /*
                 * 退款状态 refund_status 4,10:退款成功。 3,5,6:退款失败。 8,9,11:退款处理中。 1,2:
                 * 未确定,需要商户原退款单号重新发起。
                 * 7:转入代发,退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败,资金回流到商户的现金帐号
                 * ,需要商户人工干预,通过线下或者财付通转账的方式进行退款。
                 */
                String refund_status = resHandler.getParameter("refund_status");
                String out_trade_no = resHandler.getParameter("out_trade_no");
                rspMap.put("refund_status", refund_status);
                rspMap.put(WxFields.F_orderNo, out_trade_no);
                return true;
            } else {
                // 错误时,返回结果未签名,记录retcode、retmsg看失败详情。
                rspMap.put(WxFields.F_rspCode, resHandler.getParameter("retcode"));
                rspMap.put(WxFields.F_rspDesc, resHandler.getParameter("retmsg"));
            }
        } else {
            LOG.error("后台调用通信失败 http rspCode->{} errInfo->{}", httpClient.getResponseCode(), httpClient.getErrInfo());
            // 有可能因为网络原因,请求已经处理,但未收到应答。
        }

        return false;
        // 获取debug信息,建议把请求、应答内容、debug信息,通信返回码写入日志,方便定位问题
        // System.out.println("http res:" + httpClient.getResponseCode() + "," +
        // httpClient.getErrInfo());
        // System.out.println("req url:" + requestUrl);
        // System.out.println("req debug:" + reqHandler.getDebugInfo());
        // System.out.println("res content:" + rescontent);
        // System.out.println("res debug:" + resHandler.getDebugInfo());
    }
}


text:
<Alloy>
	<Window>

		<Require src="menu"/>

		Window 2
		Press the menu button
	</Window>
</Alloy>


text:
package com.example.a77528.coolweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by 77528 on 2017/8/23.
 */

public class Now {
    @SerializedName("tmp")
    public String temperature;
    @SerializedName("cond")
    public More more;
    public class More{
        @SerializedName("txt")
        public String info;
    }
}


text:
package config

import (
	"os"
	"testing"

	. "gopkg.in/check.v1"
)

func TestOptions(t *testing.T) {
	TestingT(t)
}

type OptionsSuite struct{}

var _ = Suite(&OptionsSuite{})

func (s *OptionsSuite) TestOptionFromKey(c *C) {
	os.Setenv("one", "")
	config := map[string]interface{}{
		"one": "from key",
	}

	val, err := ReadOption(Option{Key: "one", Env: "one"}, config)

	c.Assert(err, IsNil)
	c.Assert(val, Equals, "from key")
}

func (s *OptionsSuite) TestOptionFromEnv(c *C) {
	os.Setenv("one", "from env")
	config := map[string]interface{}{
		"one": "from key",
	}

	val, err := ReadOption(Option{Key: "one", Env: "one"}, config)

	c.Assert(err, IsNil)
	c.Assert(val, Equals, "from env")
}

func (s *OptionsSuite) TestMissingOption(c *C) {
	os.Setenv("one", "")
	config := map[string]interface{}{}

	val, err := ReadOption(Option{Key: "one", Env: "one"}, config)

	c.Assert(err, ErrorMatches, "Missing option \"one\"")
	c.Assert(val, Equals, "")
}

func (s *OptionsSuite) TestReturnsAllOptions(c *C) {
	config := map[string]interface{}{
		"one": "from key",
		"two": "from key",
	}

	val, err := ReadOptions([]Option{
		Option{Key: "one"},
		Option{Key: "two"},
	}, config)

	c.Assert(err, IsNil)
	c.Assert(val, DeepEquals, map[string]string{
		"one": "from key",
		"two": "from key",
	})
}

func (s *OptionsSuite) TestReturnsFirstError(c *C) {
	config := map[string]interface{}{
		"exists": "from key",
	}

	val, err := ReadOptions([]Option{
		Option{Key: "missing"},
		Option{Key: "exists"},
	}, config)

	c.Assert(err, ErrorMatches, "Missing option \"missing\"")
	c.Assert(val, IsNil)
}


text:
Java implementation of several data structures because why not? 🤘

<img src="http://treasure.diylol.com/uploads/post/image/397244/resized_philosoraptor-meme-generator-algorithms-and-data-structures-dafaaaqqqqqqq-bc310a.jpg" width=500 height=500>


text:
import time
import subprocess
import traceback

_PROCESSES = []

def start_process(popen_args = None, popen_kargs = None):
    if popen_args is None:
        popen_args = ()
    if popen_kargs is None:
        popen_kargs = {}
    process = subprocess.Popen(*popen_args, **popen_kargs)
    _PROCESSES.append(process)
    return process

def clean_created():
    copy = _PROCESSES[:]
    for process in copy:
        _PROCESSES.remove(process)

    for process in copy:
        if process.poll() is None:
            try:
                process.terminate()
            except:
                traceback.print_exc()

    counter = 20
    while counter > 0 and len([ p for p in copy if p.poll() is None ]) > 0:
        counter -= 1
        time.sleep(0.05)

    for process in copy:
        if process.poll() is None:
            try:
                process.kill()
            except:
                traceback.print_exc()


text:
package com.android.settings.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

/**
 * Copied from setup wizard.
 */
public class LinkTextView extends TextView {

    private LinkAccessibilityHelper mAccessibilityHelper;

    public LinkTextView(Context context) {
        this(context, null);
    }

    public LinkTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mAccessibilityHelper = new LinkAccessibilityHelper(this);
        setAccessibilityDelegate(mAccessibilityHelper);
    }

    @Override
    protected boolean dispatchHoverEvent(@NonNull MotionEvent event) {
        if (mAccessibilityHelper.dispatchHoverEvent(event)) {
            return true;
        }
        return super.dispatchHoverEvent(event);
    }
}


text:
/*
 * Location Intelligence APIs
 *
 * Incorporate our extensive geodata into everyday applications, business processes and workflows.
 *
 * OpenAPI spec version: 8.5.0
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * 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.
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace pb.locationIntelligence.Model
{
    /// <summary>
    /// Type
    /// </summary>
    [DataContract]
    public partial class Type :  IEquatable<Type>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Type" /> class.
        /// </summary>
        /// <param name="Code">Code.</param>
        /// <param name="Value">Value.</param>
        public Type(string Code = null, string Value = null)
        {
            this.Code = Code;
            this.Value = Value;
        }

        /// <summary>
        /// Gets or Sets Code
        /// </summary>
        [DataMember(Name="code", EmitDefaultValue=false)]
        public string Code { get; set; }
        /// <summary>
        /// Gets or Sets Value
        /// </summary>
        [DataMember(Name="value", EmitDefaultValue=false)]
        public string Value { get; set; }
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class Type {\n");
            sb.Append("  Code: ").Append(Code).Append("\n");
            sb.Append("  Value: ").Append(Value).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as Type);
        }

        /// <summary>
        /// Returns true if Type instances are equal
        /// </summary>
        /// <param name="other">Instance of Type to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(Type other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.Code == other.Code ||
                    this.Code != null &&
                    this.Code.Equals(other.Code)
                ) &&
                (
                    this.Value == other.Value ||
                    this.Value != null &&
                    this.Value.Equals(other.Value)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                if (this.Code != null)
                    hash = hash * 59 + this.Code.GetHashCode();
                if (this.Value != null)
                    hash = hash * 59 + this.Value.GetHashCode();
                return hash;
            }
        }
    }

}


text:
package com.amazonaws.services.redshiftserverless.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.redshiftserverless.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * NamespaceMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class NamespaceMarshaller {

    private static final MarshallingInfo<String> ADMINUSERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("adminUsername").build();
    private static final MarshallingInfo<java.util.Date> CREATIONDATE_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("creationDate").timestampFormat("iso8601").build();
    private static final MarshallingInfo<String> DBNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("dbName").build();
    private static final MarshallingInfo<String> DEFAULTIAMROLEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("defaultIamRoleArn").build();
    private static final MarshallingInfo<List> IAMROLES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("iamRoles").build();
    private static final MarshallingInfo<String> KMSKEYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("kmsKeyId").build();
    private static final MarshallingInfo<List> LOGEXPORTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("logExports").build();
    private static final MarshallingInfo<String> NAMESPACEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("namespaceArn").build();
    private static final MarshallingInfo<String> NAMESPACEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("namespaceId").build();
    private static final MarshallingInfo<String> NAMESPACENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("namespaceName").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("status").build();

    private static final NamespaceMarshaller instance = new NamespaceMarshaller();

    public static NamespaceMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Namespace namespace, ProtocolMarshaller protocolMarshaller) {

        if (namespace == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(namespace.getAdminUsername(), ADMINUSERNAME_BINDING);
            protocolMarshaller.marshall(namespace.getCreationDate(), CREATIONDATE_BINDING);
            protocolMarshaller.marshall(namespace.getDbName(), DBNAME_BINDING);
            protocolMarshaller.marshall(namespace.getDefaultIamRoleArn(), DEFAULTIAMROLEARN_BINDING);
            protocolMarshaller.marshall(namespace.getIamRoles(), IAMROLES_BINDING);
            protocolMarshaller.marshall(namespace.getKmsKeyId(), KMSKEYID_BINDING);
            protocolMarshaller.marshall(namespace.getLogExports(), LOGEXPORTS_BINDING);
            protocolMarshaller.marshall(namespace.getNamespaceArn(), NAMESPACEARN_BINDING);
            protocolMarshaller.marshall(namespace.getNamespaceId(), NAMESPACEID_BINDING);
            protocolMarshaller.marshall(namespace.getNamespaceName(), NAMESPACENAME_BINDING);
            protocolMarshaller.marshall(namespace.getStatus(), STATUS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
%w{git openssl-devel sqlite-devel}.each do |pkg|
  package pkg do
    action :install
  end
end

# ディレクトリがある場合、配置しない
git "/home/#{node['ruby-env']['user']}/.rbenv" do
  # GitHubから最新のリポジトリを取得
  repository node['ruby-env']['rbenv_url']
  action :sync
  user node['ruby-env']['user']
  group node['ruby-env']['group']
end

# rbenv実行に.bash_profileを書き換え
template ".bash_profile" do
  source ".bash_profile.erb"
  path "/home/#{node['ruby-env']['user']}/.bash_profile"
  mode 0644
  owner node['ruby-env']['user']
  group node['ruby-env']['group']
  # bash_profile内を検索してrbenvがある場合、書き換えない
  not_if "grep rbenv ~/.bash_profile", :environment => { :'HOME' => "/home/#{node['ruby-env']['user']}" }
end

# .rbenv/pluginsを作成後、ruby-buildを配置する
directory "/home/#{node['ruby-env']['user']}/.rbenv/plugins" do
  owner node['ruby-env']['user']
  group node['ruby-env']['group']
  mode 0755
  action :create
end

# .rbenv/pluginsを作成
git "/home/#{node['ruby-env']['user']}/.rbenv/plugins/ruby-build" do
  repository node['ruby-env']['ruby-build_url']
  action :sync
  user node['ruby-env']['user']
  group node['ruby-env']['group']
end

# rbenv install 2.1.2コマンドを実行
execute "rbenv install #{node['ruby-env']['version']}" do
  command "/home/#{node['ruby-env']['user']}/.rbenv/bin/rbenv install #{node['ruby-env']['version']}"
  user node['ruby-env']['user']
  group node['ruby-env']['group']
  environment 'HOME' => "/home/#{node['ruby-env']['user']}"
  not_if { File.exists?("/home/#{node['ruby-env']['user']}/.rbenv/versions/#{node['ruby-env']['version']}") }
end


text:
<?php
Xi_Loader::loadClass('Zend_Controller_Response_Http');

/**
 * @category    Xi
 * @package     Xi_Controller
 * @subpackage  Xi_Controller_Response
 * @author      Eevert Saukkokoski <eevert.saukkokoski@brainalliance.com>
 */
class Xi_Controller_Response extends Zend_Controller_Response_Http
{
}


text:
Partial Class Extensions
    Inherits System.Web.UI.Page

    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
        GridView1.Columns.Item(9).Visible = True

    End Sub

    Protected Sub FormView1_ItemUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewUpdatedEventArgs) Handles FormView1.ItemUpdated
        GridView1.DataBind()
    End Sub

    Protected Sub FormView1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) Handles FormView1.ItemInserted
        GridView1.DataBind()
    End Sub
End Class


text:
package io.truthencode.ddo.enumeration

import enumeratum.{Enum, EnumEntry}
import io.truthencode.ddo.support.StringUtils.Extensions

import scala.collection.immutable

/**
 * Created by adarr on 1/16/2017.
 */
object EnumExtensions {

  // private def findEnum[E <: EnumEntry: Enum[E]](v: E) = implicitly[Enum[E]]
  private def findEnum[E <: EnumEntry: Enum, A <: Enum[_ <: EnumEntry]](v: E) = implicitly[Enum[E]]

//  final implicit class EnumCompanionOps[E <: EnumEntry:Enum[E],A <: Enum[E]](
  implicit final class EnumCompanionOps[A <: Enum[_ <: EnumEntry]](
    val comp: A
  ) {
    def exists(id: String): Boolean = {
      comp.namesToValuesMap.contains(id)
    }

    /**
     * Attempts to locate a matching enumeration based on a list of potential values.
     *
     * @param names
     *   List of string values to try. i.e. Red, blue, bLaCk for a color.
     * @param ignoreCase
     *   toggles case sensitivity in search.
     * @return
     *   Returns the first Enum value found matching any of the given supplied names.
     */
    def withNames(
      names: List[String],
      ignoreCase: Boolean = false
    ): Option[immutable.IndexedSeq[_ <: EnumEntry]] = {
      val sanitized: List[String] = names.map { x =>
        x.filterAlphaNumeric
      }
      for {
        sc <- Some(comp.values.filter { x =>
          (ignoreCase && sanitized
            .exists(n => n.equalsIgnoreCase(x.toString))) || sanitized.contains(
            x.toString
          )
        }) if sc.nonEmpty
      } yield sc
    }

    def withName(
      name: String,
      ignoreCase: Boolean = false
    ): Option[_ <: EnumEntry] = {
      if (ignoreCase) {
        comp.withNameInsensitiveOption(name)
      } else {
        comp.withNameOption(name)
      }
    }

    /**
     * A list of enum values matching the BitMask
     *
     * @param flag
     *   Bit value to compare
     * @return
     *   All matching values
     */
    def fromMask(flag: Int): Option[Seq[EnumEntry]] = {
      //  comp.bitValues.filter {x => (x._2 & flag != 0)}
      //  val zz :E = comp.values.head
      //  val it = comp.bitValues.
      for {
        sc <- Some(bitValues.filter { x =>
          (x._2.toInt & flag) != 0
        }.keys) if sc.nonEmpty
      } yield sc.toSeq
    }

    def bitValues: Map[EnumEntry, Double] = comp.valuesToIndex.map { x =>
      x._1 -> Math.pow(2.0, x._2)
    }

    def fromWords(words: String): Option[EnumEntry] = {
      words.wordsToAcronym match {
        case Some(x) => comp.withNameOption(x.toPascalCase)
        case _ => None
      }
    }

  }
  implicit final class E2[E <: EnumEntry: Enum](val e: E) {
    def foo = {
      //    e.bitValues
    }
  }

}


text:
import { tress } from "tress";

function someAsyncFunction(job: any, callback: (err: any, data?: any) => void): void {
	const p = Promise.resolve(job)
		.then((value) => callback(null, value))
		.catch(callback);
}

function createWorker() {
	// Create a queue object with worker and concurrency 2
	const q = tress((job, done) => {
		someAsyncFunction(job, (err, data) => {
			if (err) {
				done(err);
			} else {
				done(null, data);
			}
		});
	}, 2);
}

function createWorkerAndUseCallbacks() {
	// Create a queue object with worker and concurrency 2
	const q = tress((job, done) => {
		someAsyncFunction(job, (err, data) => {
			if (err) {
				done(err);
			} else {
				done(null, data);
			}
		});
	}, 2);

	q.drain = () => { console.log("drain"); };
	q.empty = () => { console.log("empty"); };
	q.error = (err, job, args) => { console.log(`Error: ${err}, on job ${job} with args: ${args}`); };
	q.retry = function (args) { console.log(`Retry job ${this} with args: ${args}`); };
	q.saturated = () => { console.log("saturated"); };
	q.success = function (args) { console.log(`Success on job ${this} with args: ${args}`); };
	q.unsaturated = () => { console.log("unsaturated"); };
}

function createWorkerAndUseMethods() {
	// Create a queue object with worker and concurrency 2
	const q = tress((job, done) => {
		someAsyncFunction(job, (err, data) => {
			if (err) {
				done(err);
			} else {
				done(null, data);
			}
		});
	}, 2);

	// true if there are items waiting or being processed
	const isRunnig: boolean = !q.idle();

	// Empty remaining jobs
	q.kill();

	// Number of items waiting to be processed
	const waitingAmount: number = q.length();

	// Load new arrays from data object to arrays of waiting, failed, and finished jobs
	q.load({
		failed: [{ name: "John Doe" }],
		finished: [{ name: "John Doe" }],
		waiting: [{ name: "John Doe" }]
	});
	// Pause the processing of jobs
	q.pause();
	// Add a new job to the queue
	q.push({ name: "John Doe" });
	// Add a new job to the queue, with callback
	q.push({ name: "John Doe" }, function (args) { console.log(`Push callback for job ${this} with args: ${args}`); });
	// Add a few jobs to the queue
	q.push([{ name: "John Doe" }, { name: "John Doe" }, { name: "John Doe" }]);
	// Add a few jobs to the queue, with callback
	q.push([{ name: "John Doe" }, { name: "John Doe" }, { name: "John Doe" }],
		function (args) { console.log(`Push callback for job ${this} with args: ${args}`); });
	q.resume();

	// Number of items currently being processed
	const runningAmount: number = q.running();

	// Run a callback with object, that contains arrays of waiting, failed, and finished jobs
	q.save((queues) => console.log(`Failed: ${queues.failed}, finished: ${queues.finished}, waiting: ${queues.waiting}`));

	// The the array of items currently being processed
	const workers = q.workersList();
	// Whether status is "waiting"
	const isWaiting: boolean = q.status(workers[0]) === "waiting";

	// Add a new job to the front of the queue
	q.unshift({ name: "John Doe" });
	// Add a new job to the front of the queue, with callback
	q.unshift({ name: "John Doe" }, function (args) { console.log(`Unshift callback for job ${this} with args: ${args}`); });
	// Add a few jobs to the front of the queue
	q.unshift([{ name: "John Doe" }, { name: "John Doe" }, { name: "John Doe" }]);
	// Add a few jobs to the front of the queue, with callback
	q.unshift([{ name: "John Doe" }, { name: "John Doe" }, { name: "John Doe" }],
		function (args) { console.log(`Unshift callback for job ${this} with args: ${args}`); });
}

function createWorkerAndUseProperties() {
	// Create a queue object with worker and concurrency 2
	const q = tress((job, done) => {
		someAsyncFunction(job, (err, data) => {
			if (err) {
				done(err);
			} else {
				done(null, data);
			}
		});
	}, 2);

	// Array of jobs currently being processed (readonly)
	const active = q.active;

	// A minimum threshold buffer in order to say that the queue is unsaturated
	const buffer: number = q.buffer;
	q.buffer = 100;

	// This property for alter the concurrency/delay on-the-fly
	const concurrency: number = q.concurrency;
	q.concurrency = 100;

	// Array of failed jobs (the done callback was called from worker with error in first argument) (readonly)
	const failed = q.failed;

	// Array of correctly finished jobs (the done callback was called from worker with null or undefined (or any other false equivalent) in first argument) (readonly)
	const finished = q.finished;

	// A boolean for determining whether the queue is in a paused state. (readonly)
	const paused: boolean = q.paused;

	// false untill any items have been pushed and processed by the queue. Then becomes true and never changes in queue lifecycle (readonly)
	const started: boolean = q.started;

	// Array of queued jobs (readonly)
	const waiting = q.waiting;
}


text:
package ru.tmtool.commons.priority

/**
 * User: Sergey Kozlov skozlov@poidem.ru
 * Date: 31.07.2014
 * Time: 16:02
 */

trait Priority{
	final lazy val priority = minPriority + normalizedPriority
	final lazy val maxPriority = minPriority + prioritiesCount - 1
	val prioritiesCount: Int
	val minPriority = 0
	val normalizedPriority: Int
}


text:
<?php

class Google_Service_YouTube_LiveStream extends Google_Model
{
  protected $cdnType = 'Google_Service_YouTube_CdnSettings';
  protected $cdnDataType = '';
  protected $contentDetailsType = 'Google_Service_YouTube_LiveStreamContentDetails';
  protected $contentDetailsDataType = '';
  public $etag;
  public $id;
  public $kind;
  protected $snippetType = 'Google_Service_YouTube_LiveStreamSnippet';
  protected $snippetDataType = '';
  protected $statusType = 'Google_Service_YouTube_LiveStreamStatus';
  protected $statusDataType = '';

  public function setCdn(Google_Service_YouTube_CdnSettings $cdn)
  {
    $this->cdn = $cdn;
  }
  public function getCdn()
  {
    return $this->cdn;
  }
  public function setContentDetails(Google_Service_YouTube_LiveStreamContentDetails $contentDetails)
  {
    $this->contentDetails = $contentDetails;
  }
  public function getContentDetails()
  {
    return $this->contentDetails;
  }
  public function setEtag($etag)
  {
    $this->etag = $etag;
  }
  public function getEtag()
  {
    return $this->etag;
  }
  public function setId($id)
  {
    $this->id = $id;
  }
  public function getId()
  {
    return $this->id;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setSnippet(Google_Service_YouTube_LiveStreamSnippet $snippet)
  {
    $this->snippet = $snippet;
  }
  public function getSnippet()
  {
    return $this->snippet;
  }
  public function setStatus(Google_Service_YouTube_LiveStreamStatus $status)
  {
    $this->status = $status;
  }
  public function getStatus()
  {
    return $this->status;
  }
}


text:
<?php

namespace Fasttrack\Exceptions;

class BadRequestException extends \Exception {
  public function __construct($message = 'Request is malformed', $code = 0, Exception $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}