text:
#include <asm/irq.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/profile.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/threads.h>
#include <linux/spinlock.h>
#include <linux/kernel_stat.h>
#include <hwregs/reg_map.h>
#include <hwregs/reg_rdwr.h>
#include <hwregs/intr_vect.h>
#include <hwregs/intr_vect_defs.h>

#define CPU_FIXED -1

/* IRQ masks (refer to comment for crisv32_do_multiple) */
#if TIMER0_INTR_VECT - FIRST_IRQ < 32
#define TIMER_MASK (1 << (TIMER0_INTR_VECT - FIRST_IRQ))
#undef TIMER_VECT1
#else
#define TIMER_MASK (1 << (TIMER0_INTR_VECT - FIRST_IRQ - 32))
#define TIMER_VECT1
#endif
#ifdef CONFIG_ETRAX_KGDB
#if defined(CONFIG_ETRAX_KGDB_PORT0)
#define IGNOREMASK (1 << (SER0_INTR_VECT - FIRST_IRQ))
#elif defined(CONFIG_ETRAX_KGDB_PORT1)
#define IGNOREMASK (1 << (SER1_INTR_VECT - FIRST_IRQ))
#elif defined(CONFIG_ETRAX_KGB_PORT2)
#define IGNOREMASK (1 << (SER2_INTR_VECT - FIRST_IRQ))
#elif defined(CONFIG_ETRAX_KGDB_PORT3)
#define IGNOREMASK (1 << (SER3_INTR_VECT - FIRST_IRQ))
#endif
#endif

DEFINE_SPINLOCK(irq_lock);

struct cris_irq_allocation
{
  int cpu; /* The CPU to which the IRQ is currently allocated. */
  cpumask_t mask; /* The CPUs to which the IRQ may be allocated. */
};

struct cris_irq_allocation irq_allocations[NR_REAL_IRQS] =
  { [0 ... NR_REAL_IRQS - 1] = {0, CPU_MASK_ALL} };

static unsigned long irq_regs[NR_CPUS] =
{
  regi_irq,
#ifdef CONFIG_SMP
  regi_irq2,
#endif
};

#if NR_REAL_IRQS > 32
#define NBR_REGS 2
#else
#define NBR_REGS 1
#endif

unsigned long cpu_irq_counters[NR_CPUS];
unsigned long irq_counters[NR_REAL_IRQS];

/* From irq.c. */
extern void weird_irq(void);

/* From entry.S. */
extern void system_call(void);
extern void nmi_interrupt(void);
extern void multiple_interrupt(void);
extern void gdb_handle_exception(void);
extern void i_mmu_refill(void);
extern void i_mmu_invalid(void);
extern void i_mmu_access(void);
extern void i_mmu_execute(void);
extern void d_mmu_refill(void);
extern void d_mmu_invalid(void);
extern void d_mmu_access(void);
extern void d_mmu_write(void);

/* From kgdb.c. */
extern void kgdb_init(void);
extern void breakpoint(void);

/* From traps.c.  */
extern void breakh_BUG(void);

/*
 * Build the IRQ handler stubs using macros from irq.h.
 */
#ifdef CONFIG_CRIS_MACH_ARTPEC3
BUILD_TIMER_IRQ(0x31, 0)
#else
BUILD_IRQ(0x31)
#endif
BUILD_IRQ(0x32)
BUILD_IRQ(0x33)
BUILD_IRQ(0x34)
BUILD_IRQ(0x35)
BUILD_IRQ(0x36)
BUILD_IRQ(0x37)
BUILD_IRQ(0x38)
BUILD_IRQ(0x39)
BUILD_IRQ(0x3a)
BUILD_IRQ(0x3b)
BUILD_IRQ(0x3c)
BUILD_IRQ(0x3d)
BUILD_IRQ(0x3e)
BUILD_IRQ(0x3f)
BUILD_IRQ(0x40)
BUILD_IRQ(0x41)
BUILD_IRQ(0x42)
BUILD_IRQ(0x43)
BUILD_IRQ(0x44)
BUILD_IRQ(0x45)
BUILD_IRQ(0x46)
BUILD_IRQ(0x47)
BUILD_IRQ(0x48)
BUILD_IRQ(0x49)
BUILD_IRQ(0x4a)
#ifdef CONFIG_ETRAXFS
BUILD_TIMER_IRQ(0x4b, 0)
#else
BUILD_IRQ(0x4b)
#endif
BUILD_IRQ(0x4c)
BUILD_IRQ(0x4d)
BUILD_IRQ(0x4e)
BUILD_IRQ(0x4f)
BUILD_IRQ(0x50)
#if MACH_IRQS > 32
BUILD_IRQ(0x51)
BUILD_IRQ(0x52)
BUILD_IRQ(0x53)
BUILD_IRQ(0x54)
BUILD_IRQ(0x55)
BUILD_IRQ(0x56)
BUILD_IRQ(0x57)
BUILD_IRQ(0x58)
BUILD_IRQ(0x59)
BUILD_IRQ(0x5a)
BUILD_IRQ(0x5b)
BUILD_IRQ(0x5c)
BUILD_IRQ(0x5d)
BUILD_IRQ(0x5e)
BUILD_IRQ(0x5f)
BUILD_IRQ(0x60)
BUILD_IRQ(0x61)
BUILD_IRQ(0x62)
BUILD_IRQ(0x63)
BUILD_IRQ(0x64)
BUILD_IRQ(0x65)
BUILD_IRQ(0x66)
BUILD_IRQ(0x67)
BUILD_IRQ(0x68)
BUILD_IRQ(0x69)
BUILD_IRQ(0x6a)
BUILD_IRQ(0x6b)
BUILD_IRQ(0x6c)
BUILD_IRQ(0x6d)
BUILD_IRQ(0x6e)
BUILD_IRQ(0x6f)
BUILD_IRQ(0x70)
#endif

/* Pointers to the low-level handlers. */
static void (*interrupt[MACH_IRQS])(void) = {
	IRQ0x31_interrupt, IRQ0x32_interrupt, IRQ0x33_interrupt,
	IRQ0x34_interrupt, IRQ0x35_interrupt, IRQ0x36_interrupt,
	IRQ0x37_interrupt, IRQ0x38_interrupt, IRQ0x39_interrupt,
	IRQ0x3a_interrupt, IRQ0x3b_interrupt, IRQ0x3c_interrupt,
	IRQ0x3d_interrupt, IRQ0x3e_interrupt, IRQ0x3f_interrupt,
	IRQ0x40_interrupt, IRQ0x41_interrupt, IRQ0x42_interrupt,
	IRQ0x43_interrupt, IRQ0x44_interrupt, IRQ0x45_interrupt,
	IRQ0x46_interrupt, IRQ0x47_interrupt, IRQ0x48_interrupt,
	IRQ0x49_interrupt, IRQ0x4a_interrupt, IRQ0x4b_interrupt,
	IRQ0x4c_interrupt, IRQ0x4d_interrupt, IRQ0x4e_interrupt,
	IRQ0x4f_interrupt, IRQ0x50_interrupt,
#if MACH_IRQS > 32
	IRQ0x51_interrupt, IRQ0x52_interrupt, IRQ0x53_interrupt,
	IRQ0x54_interrupt, IRQ0x55_interrupt, IRQ0x56_interrupt,
	IRQ0x57_interrupt, IRQ0x58_interrupt, IRQ0x59_interrupt,
	IRQ0x5a_interrupt, IRQ0x5b_interrupt, IRQ0x5c_interrupt,
	IRQ0x5d_interrupt, IRQ0x5e_interrupt, IRQ0x5f_interrupt,
	IRQ0x60_interrupt, IRQ0x61_interrupt, IRQ0x62_interrupt,
	IRQ0x63_interrupt, IRQ0x64_interrupt, IRQ0x65_interrupt,
	IRQ0x66_interrupt, IRQ0x67_interrupt, IRQ0x68_interrupt,
	IRQ0x69_interrupt, IRQ0x6a_interrupt, IRQ0x6b_interrupt,
	IRQ0x6c_interrupt, IRQ0x6d_interrupt, IRQ0x6e_interrupt,
	IRQ0x6f_interrupt, IRQ0x70_interrupt,
#endif
};

void
block_irq(int irq, int cpu)
{
	int intr_mask;
        unsigned long flags;

	spin_lock_irqsave(&irq_lock, flags);
	/* Remember, 1 let thru, 0 block. */
	if (irq - FIRST_IRQ < 32) {
		intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
			rw_mask, 0);
		intr_mask &= ~(1 << (irq - FIRST_IRQ));
		REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
			0, intr_mask);
	} else {
		intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
			rw_mask, 1);
		intr_mask &= ~(1 << (irq - FIRST_IRQ - 32));
		REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
			1, intr_mask);
	}
        spin_unlock_irqrestore(&irq_lock, flags);
}

void
unblock_irq(int irq, int cpu)
{
	int intr_mask;
        unsigned long flags;

        spin_lock_irqsave(&irq_lock, flags);
	/* Remember, 1 let thru, 0 block. */
	if (irq - FIRST_IRQ < 32) {
		intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
			rw_mask, 0);
		intr_mask |= (1 << (irq - FIRST_IRQ));
		REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
			0, intr_mask);
	} else {
		intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
			rw_mask, 1);
		intr_mask |= (1 << (irq - FIRST_IRQ - 32));
		REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
			1, intr_mask);
	}
        spin_unlock_irqrestore(&irq_lock, flags);
}

/* Find out which CPU the irq should be allocated to. */
static int irq_cpu(int irq)
{
	int cpu;
        unsigned long flags;

        spin_lock_irqsave(&irq_lock, flags);
        cpu = irq_allocations[irq - FIRST_IRQ].cpu;

	/* Fixed interrupts stay on the local CPU. */
	if (cpu == CPU_FIXED)
        {
		spin_unlock_irqrestore(&irq_lock, flags);
		return smp_processor_id();
        }

	/* Let the interrupt stay if possible */
	if (cpumask_test_cpu(cpu, &irq_allocations[irq - FIRST_IRQ].mask))
		goto out;

	/* IRQ must be moved to another CPU. */
	cpu = cpumask_first(&irq_allocations[irq - FIRST_IRQ].mask);
	irq_allocations[irq - FIRST_IRQ].cpu = cpu;
out:
	spin_unlock_irqrestore(&irq_lock, flags);
	return cpu;
}

void crisv32_mask_irq(int irq)
{
	int cpu;

	for (cpu = 0; cpu < NR_CPUS; cpu++)
		block_irq(irq, cpu);
}

void crisv32_unmask_irq(int irq)
{
	unblock_irq(irq, irq_cpu(irq));
}

static void enable_crisv32_irq(struct irq_data *data)
{
	crisv32_unmask_irq(data->irq);
}

static void disable_crisv32_irq(struct irq_data *data)
{
	crisv32_mask_irq(data->irq);
}

static int set_affinity_crisv32_irq(struct irq_data *data,
				    const struct cpumask *dest, bool force)
{
	unsigned long flags;

	spin_lock_irqsave(&irq_lock, flags);
	irq_allocations[data->irq - FIRST_IRQ].mask = *dest;
	spin_unlock_irqrestore(&irq_lock, flags);
	return 0;
}

static struct irq_chip crisv32_irq_type = {
	.name			= "CRISv32",
	.irq_shutdown		= disable_crisv32_irq,
	.irq_enable		= enable_crisv32_irq,
	.irq_disable		= disable_crisv32_irq,
	.irq_set_affinity	= set_affinity_crisv32_irq,
};

void
set_exception_vector(int n, irqvectptr addr)
{
	etrax_irv->v[n] = (irqvectptr) addr;
}

extern void do_IRQ(int irq, struct pt_regs * regs);

void
crisv32_do_IRQ(int irq, int block, struct pt_regs* regs)
{
	/* Interrupts that may not be moved to another CPU and
         * are IRQF_DISABLED may skip blocking. This is currently
         * only valid for the timer IRQ and the IPI and is used
         * for the timer interrupt to avoid watchdog starvation.
         */
	if (!block) {
		do_IRQ(irq, regs);
		return;
	}

	block_irq(irq, smp_processor_id());
	do_IRQ(irq, regs);

	unblock_irq(irq, irq_cpu(irq));
}

/* If multiple interrupts occur simultaneously we get a multiple
 * interrupt from the CPU and software has to sort out which
 * interrupts that happened. There are two special cases here:
 *
 * 1. Timer interrupts may never be blocked because of the
 *    watchdog (refer to comment in include/asr/arch/irq.h)
 * 2. GDB serial port IRQs are unhandled here and will be handled
 *    as a single IRQ when it strikes again because the GDB
 *    stubb wants to save the registers in its own fashion.
 */
void
crisv32_do_multiple(struct pt_regs* regs)
{
	int cpu;
	int mask;
	int masked[NBR_REGS];
	int bit;
	int i;

	cpu = smp_processor_id();

	/* An extra irq_enter here to prevent softIRQs to run after
         * each do_IRQ. This will decrease the interrupt latency.
	 */
	irq_enter();

	for (i = 0; i < NBR_REGS; i++) {
		/* Get which IRQs that happened. */
		masked[i] = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
			r_masked_vect, i);

		/* Calculate new IRQ mask with these IRQs disabled. */
		mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i);
		mask &= ~masked[i];

	/* Timer IRQ is never masked */
#ifdef TIMER_VECT1
		if ((i == 1) && (masked[0] & TIMER_MASK))
			mask |= TIMER_MASK;
#else
		if ((i == 0) && (masked[0] & TIMER_MASK))
			mask |= TIMER_MASK;
#endif
		/* Block all the IRQs */
		REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i, mask);

	/* Check for timer IRQ and handle it special. */
#ifdef TIMER_VECT1
		if ((i == 1) && (masked[i] & TIMER_MASK)) {
			masked[i] &= ~TIMER_MASK;
			do_IRQ(TIMER0_INTR_VECT, regs);
		}
#else
		if ((i == 0) && (masked[i] & TIMER_MASK)) {
			 masked[i] &= ~TIMER_MASK;
			 do_IRQ(TIMER0_INTR_VECT, regs);
		}
#endif
	}

#ifdef IGNORE_MASK
	/* Remove IRQs that can't be handled as multiple. */
	masked[0] &= ~IGNORE_MASK;
#endif

	/* Handle the rest of the IRQs. */
	for (i = 0; i < NBR_REGS; i++) {
		for (bit = 0; bit < 32; bit++) {
			if (masked[i] & (1 << bit))
				do_IRQ(bit + FIRST_IRQ + i*32, regs);
		}
	}

	/* Unblock all the IRQs. */
	for (i = 0; i < NBR_REGS; i++) {
		mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i);
		mask |= masked[i];
		REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i, mask);
	}

	/* This irq_exit() will trigger the soft IRQs. */
	irq_exit();
}

/*
 * This is called by start_kernel. It fixes the IRQ masks and setup the
 * interrupt vector table to point to bad_interrupt pointers.
 */
void __init
init_IRQ(void)
{
	int i;
	int j;
	reg_intr_vect_rw_mask vect_mask = {0};

	/* Clear all interrupts masks. */
	for (i = 0; i < NBR_REGS; i++)
		REG_WR_VECT(intr_vect, regi_irq, rw_mask, i, vect_mask);

	for (i = 0; i < 256; i++)
		etrax_irv->v[i] = weird_irq;

	/* Point all IRQ's to bad handlers. */
	for (i = FIRST_IRQ, j = 0; j < NR_IRQS; i++, j++) {
		irq_set_chip_and_handler(j, &crisv32_irq_type,
					 handle_simple_irq);
		set_exception_vector(i, interrupt[j]);
	}

	/* Mark Timer and IPI IRQs as CPU local */
	irq_allocations[TIMER0_INTR_VECT - FIRST_IRQ].cpu = CPU_FIXED;
	irq_set_status_flags(TIMER0_INTR_VECT, IRQ_PER_CPU);
	irq_allocations[IPI_INTR_VECT - FIRST_IRQ].cpu = CPU_FIXED;
	irq_set_status_flags(IPI_INTR_VECT, IRQ_PER_CPU);

	set_exception_vector(0x00, nmi_interrupt);
	set_exception_vector(0x30, multiple_interrupt);

	/* Set up handler for various MMU bus faults. */
	set_exception_vector(0x04, i_mmu_refill);
	set_exception_vector(0x05, i_mmu_invalid);
	set_exception_vector(0x06, i_mmu_access);
	set_exception_vector(0x07, i_mmu_execute);
	set_exception_vector(0x08, d_mmu_refill);
	set_exception_vector(0x09, d_mmu_invalid);
	set_exception_vector(0x0a, d_mmu_access);
	set_exception_vector(0x0b, d_mmu_write);

#ifdef CONFIG_BUG
	/* Break 14 handler, used to implement cheap BUG().  */
	set_exception_vector(0x1e, breakh_BUG);
#endif

	/* The system-call trap is reached by "break 13". */
	set_exception_vector(0x1d, system_call);

	/* Exception handlers for debugging, both user-mode and kernel-mode. */

	/* Break 8. */
	set_exception_vector(0x18, gdb_handle_exception);
	/* Hardware single step. */
	set_exception_vector(0x3, gdb_handle_exception);
	/* Hardware breakpoint. */
	set_exception_vector(0xc, gdb_handle_exception);

#ifdef CONFIG_ETRAX_KGDB
	kgdb_init();
	/* Everything is set up; now trap the kernel. */
	breakpoint();
#endif
}


text:
<?php

/**
 * @file
 * Definition of Drupal\Core\Annotation\Translation.
 */

namespace Drupal\Core\Annotation;

use Drupal\Component\Annotation\AnnotationBase;
use Drupal\Core\StringTranslation\TranslationWrapper;

/**
 * @defgroup plugin_translatable Annotation for translatable text
 * @{
 * Describes how to put translatable UI text into annotations.
 *
 * When providing plugin annotation, properties whose values are displayed in
 * the user interface should be made translatable. Much the same as how user
 * interface text elsewhere is wrapped in t() to make it translatable, in plugin
 * annotation, wrap translatable strings in the @ Translation() annotation.
 * For example:
 * @code
 *   title = @ Translation("Title of the plugin"),
 * @endcode
 * Remove spaces after @ in your actual plugin - these are put into this sample
 * code so that it is not recognized as annotation.
 *
 * To provide replacement values for placeholders, use the "arguments" array:
 * @code
 *   title = @ Translation("Bundle !title", arguments = {"!title" = "Foo"}),
 * @endcode
 *
 * It is also possible to provide a context with the text, similar to t():
 * @code
 *   title = @ Translation("Bundle", context = "Validation"),
 * @endcode
 * Other t() arguments like language code are not valid to pass in. Only
 * context is supported.
 *
 * @see i18n
 * @see annotation
 * @}
 */

/**
 * Defines a translatable annotation object.
 *
 * Some metadata within an annotation needs to be translatable. This class
 * supports that need by allowing both the translatable string and, if
 * specified, a context for that string. The string (with optional context)
 * is passed into t().
 *
 * @ingroup plugin_translatable
 *
 * @Annotation
 */
class Translation extends AnnotationBase {

  /**
   * The string translation object.
   *
   * @var \Drupal\Core\StringTranslation\TranslationWrapper
   */
  protected $translation;

  /**
   * Constructs a new class instance.
   *
   * Parses values passed into this class through the t() function in Drupal and
   * handles an optional context for the string.
   *
   * @param array $values
   *   Possible array keys:
   *   - value (required): the string that is to be translated.
   *   - arguments (optional): an array with placeholder replacements, keyed by
   *     placeholder.
   *   - context (optional): a string that describes the context of "value";
   */
  public function __construct(array $values) {
    $string = $values['value'];
    $arguments = isset($values['arguments']) ? $values['arguments'] : array();
    $options = array();
    if (!empty($values['context'])) {
      $options = array(
        'context' => $values['context'],
      );
    }
    $this->translation = new TranslationWrapper($string, $arguments, $options);
  }

  /**
   * {@inheritdoc}
   */
  public function get() {
    return $this->translation;
  }

}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class ViewUsersHelperTest < ActionView::TestCase
end


text:
package org.decimal4j.op.arith;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.decimal4j.api.Decimal;
import org.decimal4j.api.DecimalArithmetic;
import org.decimal4j.op.AbstractDecimalDecimalToDecimalTest;
import org.decimal4j.scale.ScaleMetrics;
import org.decimal4j.test.TestSettings;
import org.decimal4j.truncate.CheckedRounding;
import org.decimal4j.truncate.OverflowMode;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Unit test for {@link Decimal#add(Decimal)} and {@link Decimal#add(Decimal, OverflowMode)}.
 */
@RunWith(Parameterized.class)
public class AddTest extends AbstractDecimalDecimalToDecimalTest {

	public AddTest(ScaleMetrics scaleMetrics, OverflowMode overflowMode, DecimalArithmetic arithmetic) {
		super(arithmetic);
	}

	@Parameters(name = "{index}: {0}, {1}")
	public static Iterable<Object[]> data() {
		final List<Object[]> data = new ArrayList<Object[]>();
		for (final ScaleMetrics s : TestSettings.SCALES) {
			data.add(new Object[] {s, OverflowMode.UNCHECKED, s.getRoundingDownArithmetic()});
			data.add(new Object[] {s, OverflowMode.CHECKED, s.getArithmetic(CheckedRounding.DOWN)});
		}
		return data;
	}

	@Override
	protected String operation() {
		return "+";
	}

	@Override
	protected BigDecimal expectedResult(BigDecimal a, BigDecimal b) {
		return a.add(b);
	}

	@Override
	protected <S extends ScaleMetrics> Decimal<S> actualResult(Decimal<S> a, Decimal<S> b) {
		if (isUnchecked() && RND.nextBoolean()) {
			return a.add(b);
		}
		return a.add(b, getOverflowMode());
	}
}


text:
///
/// @file t_IncrementalItemCF.cpp
/// @brief test IncrementalItemCF in Incremental Collaborative Filtering operations
/// @author Jun Jiang
/// @date Created 2011-04-29
///

#include "ItemCFTest.h"
#include <idmlib/resys/incremcf/IncrementalItemCF.h>

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/random.hpp>

#include <util/ClockTimer.h>
#include <boost/timer.hpp>

#include <list>
#include <string>

#include <cmath>

using namespace std;
using namespace boost;
using namespace idmlib::recommender;

using namespace izenelib::util;

namespace bfs = boost::filesystem;

namespace
{
const char* TEST_DIR_STR = "cf";
}

struct RandomGenerators
{
    boost::mt19937 engine ;
    boost::uniform_int<> itemDistribution ;
    boost::variate_generator<boost::mt19937, boost::uniform_int<> > itemRandom;
    boost::uniform_int<> newVisitDistribution;
    boost::variate_generator<boost::mt19937, boost::uniform_int<> > newVisitRandom;

    RandomGenerators(int ITEMLIMIT, int NEWVISITLIMIT)
        :itemDistribution(1, ITEMLIMIT)
        ,itemRandom (engine, itemDistribution)
        ,newVisitDistribution(1, NEWVISITLIMIT)
        ,newVisitRandom (engine, newVisitDistribution)
    {
    }

    /**
     * to avoid assert fail in IncrementalItemCF::calcSimValue_(),
     * it only generates new items. */
    void genItems(std::list<uint32_t>& newItems)
    {
        int N = newVisitRandom();
        for(int i = 0; i < N; ++i)
        {
            newItems.push_back(itemRandom());
        }
    }

};

BOOST_AUTO_TEST_SUITE(IncrementalItemCFTest)

BOOST_AUTO_TEST_CASE(smokeTest)
{
    bfs::path cfPath(TEST_DIR_STR);
    boost::filesystem::remove_all(cfPath);
    bfs::create_directories(cfPath);

    ItemCFParam itemCFParam(cfPath.string());
    ItemCFTest itemCFTest;

    {
        IncrementalItemCF cfManager(itemCFParam);
        itemCFTest.setCFManager(&cfManager);

        uint32_t user1 = 1;
        itemCFTest.checkPurchase(user1, "", "1 2 3");

        uint32_t user2 = 2;
        itemCFTest.checkPurchase(user2, "", "3 4 5", true);

        itemCFTest.checkRecommend("1");
        itemCFTest.checkRecommend("2");
        itemCFTest.checkRecommend("3");
        itemCFTest.checkRecommend("4");
        itemCFTest.checkRecommend("1 2");
        itemCFTest.checkRecommend("1 2 3");
        itemCFTest.checkRecommend("1 2 3 4");

        itemCFTest.checkWeightRecommend("2 1.5 4 -1.0");
        itemCFTest.checkWeightRecommend("5 1.0 1 0.5");
        itemCFTest.checkWeightRecommend("1 1.5 3 0.5 4 1.0");
        itemCFTest.checkWeightRecommend("1 1.5 3 0.5 4 -1.0");
    }

    {
        IncrementalItemCF cfManager(itemCFParam);
        itemCFTest.setCFManager(&cfManager);

        itemCFTest.checkVisitMatrix();
        itemCFTest.checkSimMatrix();

        uint32_t user1 = 1;
        itemCFTest.checkPurchase(user1, "1 2 3", "4 6 8", true);

        uint32_t user2 = 2;
        itemCFTest.checkPurchase(user2, "3 4 5", "6 7 9");

        uint32_t user3 = 3;
        itemCFTest.checkPurchase(user3, "", "1 3 5");
        itemCFTest.checkPurchase(user3, "1 3 5", "2 8 4");

        uint32_t user4 = 4;
        itemCFTest.checkPurchase(user4, "", "4 2 9");
        itemCFTest.checkPurchase(user4, "4 2 9", "7 6 5", true);

        uint32_t user5 = 5;
        itemCFTest.checkPurchase(user5, "", "1");

        itemCFTest.checkRecommend("1");
        itemCFTest.checkRecommend("2");
        itemCFTest.checkRecommend("3");
        itemCFTest.checkRecommend("4");
        itemCFTest.checkRecommend("1 2");
        itemCFTest.checkRecommend("1 2 3");
        itemCFTest.checkRecommend("1 2 3 4");
        itemCFTest.checkRecommend("1 3 5 7 9");

        itemCFTest.checkWeightRecommend("3 1.0 6 -1.0");
        itemCFTest.checkWeightRecommend("9 1.5 2 0.5 5 -1.5");
    }
}

BOOST_AUTO_TEST_CASE(largeTest)
{
    bfs::path cfPath(TEST_DIR_STR);
    boost::filesystem::remove_all(cfPath);
    bfs::create_directories(cfPath);

    ItemCFParam itemCFParam(cfPath.string());
    IncrementalItemCF cfManager(itemCFParam);

    int MaxITEM = 100000;
    int MaxNewVisit = 10;
    RandomGenerators generators(MaxITEM, MaxNewVisit);

    ClockTimer t;

    int ORDERS = 20000;
    for(int i = 0; i < ORDERS; ++i)
    {
        if(i%500 == 0)
        {
            std::cout << "orders: " << i
                      << ", elapsed time: " << t.elapsed() << ", "
                      << cfManager << std::endl;
        }
        std::list<uint32_t> oldItems;
        std::list<uint32_t> newItems;
        generators.genItems(newItems);

        cfManager.updateMatrix(oldItems, newItems);

        // get recommend items
        std::vector<uint32_t> totalItems(oldItems.begin(), oldItems.end());
        totalItems.insert(totalItems.end(), newItems.begin(), newItems.end());
        RecommendItemVec recItems;
        cfManager.recommend(20, totalItems, recItems);
    }

}

BOOST_AUTO_TEST_SUITE_END()


text:
<?php

namespace MatthC\Privileges\Models;

/**
 * Class Permission
 * @package MatthC\Privileges\Models
 *
 * @author Matthieu Calie <matthieu.calie@gmail.com>
 */
class Permission extends PrivilegesModel
{
    /**
     * @var array
     */
    protected $fillable = ['name', 'description'];

    /**
     * Get linked Roles
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}


text:
<?php
require_once("solr.class.inc.php");

require('Solarium/library/Solarium/Autoloader.php');
Solarium_Autoloader::register();

/*----------------------------------------------------------------
 *
* Solr class with API Solarium
*
*----------------------------------------------------------------*/
class Solr extends Solr_Abstract {

	private $_client = null;

	public function Solr_Solarium () {
	}

	public function connect($solr_host, $solr_port, $solr_baseurl, $solr_corename) {
		$config = array(
			    'adapteroptions' => array(
			        'host' => $solr_host,
			        'port' => $solr_port,
			        'path' => $solr_baseurl . '/' . $solr_corename,
		)
		);
		$this->_client = new Solarium_Client($config);
		return $this->ping();
	}

	public function ping() {
		if ($this->_client==null)
		return false;
		// create a ping query
		$ping = $this->_client->createPing();
		// execute the ping query
		try{
			$this->_client->ping($ping);
			return true;
		}catch(Solarium_Exception $e){
			return false;
		}
	}
	public function system() {
		return null;
	}

	public function getFiedValues($field) {

		if ($this->_client==null)
		return "";

		// get a select query instance
		$query = $this->_client->createSelect();

		// get the facetset component
		$facetSet = $query->getFacetSet();

		// create a facet field instance and set options
		$facet = $facetSet->createFacetField();
		$facet->setKey($field);
		$facet->setField($field);

		// add the facet instance to the facetset
		$facetSet->addFacet($facet);

		// this executes the query and returns the result
		$resultset = $this->_client->select($query);

		// display the total number of documents found by solr
		//echo 'NumFound: '.$resultset->getNumFound();

		// display facet counts
		//echo '
Facet counts for field "inStock":
';
		$facet = $resultset->getFacetSet()->getFacet($field);
		foreach($facet as $value => $count) {
			if ($value!="") {
				if ($ret!="") $ret .= "|";
				$ret .= $value . ":" . $count;
			}
		}

		return $ret;
	}

	function query(
	$qry,
	$query_lang,
	$sort,
	$groupsize,
	$offset,
	$count,
	$fq,
	$word_variations,
	$filter_lang,
	$filter_country,
	$filter_mimetype,
	$filter_source,
	$filter_collection,
	$filter_tag,
	$filter_location_lat,
	$filter_location_lng,
	$filter_location_radius,
	$mode,
	$rss,
	$debug=false) {

		global $facetcollections, $facettags, $facetcountry, $facetlanguage, $facetcontenttype, $facetsourcename;

		$query = $this->_client->createSelect();

		if ($word_variations && $querylang!="") {
			$queryField = "content_mls";
		}
		else {
			$queryField = "content_ml";
		}

		if ($query_lang=="")
		$query_lang = "en";

		// Facets
		if (!$rss) {
// 			$aFacet = Array();
// 			if ($facetcollections) array_push($aFacet, "collection");
// 			if ($facettags) array_push($aFacet, "tag");
// 			if ($facetsourcename) array_push($aFacet, "source_str");
// 			if ($facetcountry) array_push($aFacet, "country");
// 			if ($facetlanguage) array_push($aFacet, "language");
// 			if ($facetcontenttype) array_push($aFacet, "contenttyperoot");

// 			$params['facet'] = 'true';
// 			$params['facet.field'] = $aFacet;
// 			$params['facet.mincount'] = '1';
// 			$params['facet.limit'] = '10';

			// get the facetset component
			$facetSet = $query->getFacetSet();

			if ($facetcollections) {
				$facet = $facetSet->createFacetField();
				$facet->setKey('collection');
				$facet->setField('collection');
				$facetSet->addFacet($facet);
			}

			if ($facetcountry) {
				$facet = $facetSet->createFacetField();
				$facet->setKey('country');
				$facet->setField('country');
				$facetSet->addFacet($facet);
			}

		}

		$qry = trim($this->escapeQuery($qry));
		$finalqry = '\[' . $query_lang . '\]' . $qry;

		$query->setQuery($queryField . ':' . $finalqry);

		// this executes the query and returns the result
		$resultset = $this->_client->select($query);

		$sorl_response = new Solr_Response($resultset->getResponse()->getBody(), $resultset->getResponse()->getStatusCode());
		return $sorl_response;
	}

}

?>


text:
"""This module is the url dispatcher for strain related views.

It takes the root */strain...* and generates strain-list, strain-new, strain-edit, strain-delete, strain-detail and views from animal.views."""

from django.conf.urls import url

from mousedb.animal import views
from mousedb.data.views import StrainData, StrainDataCSV

urlpatterns = [
    url(r'^$', views.StrainList.as_view(), name="strain-list"),
	url(r'^new/?$', views.StrainCreate.as_view(), name="strain-new"),
	url(r'^(?P<slug>[-\w]+)/edit/?$', views.StrainUpdate.as_view(), name="strain-edit"),
	url(r'^(?P<slug>[-\w]+)/update/?$', views.StrainUpdate.as_view(), name="strain-edit"),
	url(r'^(?P<slug>[-\w]+)/delete/?$',
	    views.StrainDelete.as_view(),
	    name="strain-delete"),
    url(r'^(?P<slug>[-\w]+)/all/?$', views.StrainDetailAll.as_view(), name="strain-all"),
    url(r'^(?P<strain_slug>[-\w]+)/data/?$', StrainData.as_view(), name="strain-data"),
    url(r'^(?P<strain_slug>[-\w]+)/data.csv$',
        StrainDataCSV.as_view(),
        name="strain-data-csv"),
    url(r'^(?P<strain_slug>[-\w]+)/(?P<breeding_type>[\w-]+)/?$',
        views.CrossTypeAnimalList.as_view(),
        name="strain-crosstype"),
    url(r'^(?P<slug>[-\w]+)/?$', views.StrainDetail.as_view(), name="strain-detail"),

]


text:
import sys
import os
import os.path as osp
import glob
from collections import OrderedDict

from bv_build.workers import BuildWorker
from bv_build.project_info import read_project_info
from bv_build.subprocess_utils import verbose_check_call

def create_site_customize(build_directory):
    # Create a sitecustomize Python package that imports all modules it
    # contains during Python startup. This is mainly used to modify sys.path
    # to include pure Python components source (see module
    # brainvisa.maker.build_models.pure_python). This package is used only
    # in build directory, it is not installed in packages (to date there is
    # one exception to this in axon component, see Axon's CMakeLists.txt).
    sitecustomize_content = '''\
import os

for i in os.listdir(os.path.dirname(__file__)):
    if i.endswith('.py') and i != '__init__.py':
        module = i[:-3]
        __import__('sitecustomize.%s' % module)
'''
    sitecustomize_dir = osp.join(build_directory, 'python', 'sitecustomize')
    if not osp.exists(sitecustomize_dir):
        os.makedirs(sitecustomize_dir)
    open(osp.join(sitecustomize_dir,'__init__.py'), 'w').write(
        sitecustomize_content)

def cmake_path(path):
    '''
    Convert a system path to a CMakeLists.txt compatible path.
    '''
    if sys.platform == 'win32':
        return path.replace( '\\', '/' )
    else :
        return path

def cmake_command():
    if sys.platform == 'win32':
        return ['cmake', '-G', 'MSYS Makefiles']
    else:
        return ['cmake']

class BrainVISACMakeWorker(BuildWorker):
    @staticmethod
    def get_model(model_name):
        m = __import__('bv_build.workers.brainvisa_cmake_models.%s' % model_name, fromlist=[''], level=0)
        # Return one of the classes defined in module. There should be
        # exaclty one class.
        return (i for i in m.__dict__.itervalues() if isinstance(i,type) and
            i.__module__ == m.__name__).next()

    @classmethod
    def start_configure(cls, dir_manager, verbose, release, debug):
        create_site_customize(dir_manager.directory)

        dir_manager.cache.setdefault('workers',{}).setdefault('brainvisa-cmake',{})['components'] = OrderedDict()

        # Save CMake build type in cache
        if release:
            build_type = ('RelWithDebInfo' if debug else 'Release')
        else:
            build_type = ('Debug' if debug else 'None')
        dir_manager.cache['workers']['brainvisa-cmake']['cmake_build_type'] = build_type

    @classmethod
    def configure_module(cls, dir_manager, verbose, module, model='genuine'):
        model = cls.get_model(model)
        model.configure_module(dir_manager, verbose, module)

    @classmethod
    def terminate_configure(cls, dir_manager, verbose):
        # Create bv_maker.cmake file
        sorted_components = dir_manager.cache['workers']['brainvisa-cmake']['components']
        cmakeFile = osp.join(dir_manager.directory, 'bv_maker.cmake')
        out = open( cmakeFile, 'w' )
        print >> out, 'set( BRAINVISA_PROJECTS build CACHE STRING "BrainVISA Projects list" FORCE )'
        print >> out, 'set( _BRAINVISA_PROJECTS build CACHE STRING "BrainVISA Projects list" FORCE )'
        print >> out, 'set( BRAINVISA_COMPONENTS', ' '.join(sorted_components),'CACHE STRING "BrainVISA components list" FORCE )'
        print >> out, 'set( _BRAINVISA_COMPONENTS', ' '.join(sorted_components),'CACHE STRING "BrainVISA components list" FORCE )'
        print >> out
        for component, component_cache in sorted_components.iteritems():
            print >> out, 'set( BRAINVISA_SOURCES_' + component + ' "' + cmake_path(component_cache['source_directory']) + '" CACHE STRING "Sources directory for component ' + component + '" FORCE )'
            print >> out, 'set( ' + component + '_DIR "' + cmake_path(component_cache['cmake_directory']) + '" CACHE STRING "Directory used for find_package( ' + component + ' )" FORCE )'
            print >> out, 'set( ' + component + '_VERSION "' + component_cache['version'] + '" )'
        out.close()

        cmakeLists = osp.join( dir_manager.directory, 'CMakeLists.txt' )
        out = open( cmakeLists, 'w' )
        print >> out, '''
cmake_minimum_required( VERSION 2.6 )
set( CMAKE_PREFIX_PATH "${CMAKE_BINARY_DIR}" ${CMAKE_PREFIX_PATH} )
find_package( brainvisa-cmake NO_POLICY_SCOPE )
include( "${brainvisa-cmake_DIR}/brainvisa-compilation.cmake" )
'''
        out.close()

        command = cmake_command()

        build_type = dir_manager.cache['workers']['brainvisa-cmake']['cmake_build_type']
        command += ['-DCMAKE_BUILD_TYPE:STRING=' + build_type, cmake_path(dir_manager.directory)]

        # set bv_maker path, so that cmake finds its modules
        os.environ['PATH'] = osp.join(dir_manager.directory, 'bin') + osp.sep \
            + os.getenv('PATH')
        verbose_check_call(command, cwd=dir_manager.directory, verbose=verbose)

    @classmethod
    def start_build(cls, dir_manager, verbose):
        pass

    @classmethod
    def build_module(cls, dir_manager, verbose, module, model='genuine'):
        model = cls.get_model(model)
        model.build_module(dir_manager, verbose, module)

    @classmethod
    def terminate_build(cls, dir_manager, verbose):
        # TODO manage make options
        command = ['make']
        verbose_check_call(command, cwd=dir_manager.directory, verbose=verbose)

  #def doc( self ):
    #self._process_configuration_lines()
    #system( cwd=self.directory, *( ['make'] + self.make_options.split() + ['-j1', 'doc'] ) )

  #def test( self ):
    #self._process_configuration_lines()


text:
layout: minimal
title: Tetris
tags: [tetris,mithril.js,]
date: 2018-01-31
comments: false
---

{% include tetris.html %}


text:
module ApplicationHelper
  # Always use the Twitter Bootstrap pagination renderer
  # def will_paginate(collection_or_options = nil, options = {})
  #   if collection_or_options.is_a? Hash
  #     options, collection_or_options = collection_or_options, nil
  #   end
  #   unless options[:renderer]
  #     options = options.merge :renderer => BootstrapPagination::Rails
  #   end
  #   super *[collection_or_options, options].compact
  # end
end


text:
<?php

namespace ErenMustafaOzdal\LaravelProductModule\Http\Requests\ProductShowcase;

use App\Http\Requests\Request;
use Sentinel;

class StoreRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return hasPermission('admin.product_showcase.store');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'              => 'required|max:255',
        ];
    }
}


text:
namespace descriptions
{
Serializer::Serializer(DescriptionsCollection && descriptions)
  : m_descriptions(std::move(descriptions))
{
  CHECK(!m_descriptions.empty(), ());

  std::sort(m_descriptions.begin(), m_descriptions.end(), base::LessBy(&FeatureDescription::m_featureIndex));

  m_langMetaCollection.reserve(m_descriptions.size());

  size_t stringsCount = 0;

  for (size_t i = 0; i < m_descriptions.size(); ++i)
  {
    auto & index = m_descriptions[i];
    CHECK(!index.m_description.IsEmpty(), ());

    LangMeta langMeta;
    index.m_description.ForEach([this, &stringsCount, &langMeta, i](LangCode lang, std::string const & str)
                                {
                                  CHECK_GREATER_OR_EQUAL(lang, 0, ());
                                  CHECK(lang < StringUtf8Multilang::kMaxSupportedLanguages, ());
                                  CHECK(!str.empty(), ());
                                  ++stringsCount;
                                  auto & group = m_groupedByLang[lang];
                                  langMeta.insert(std::make_pair(lang, static_cast<StringIndex>(group.size())));
                                  group.push_back(i);
                                });
    m_langMetaCollection.push_back(langMeta);
  }

  std::map<LangCode, uint32_t> indicesOffsets;
  uint32_t currentOffset = 0;
  for (auto & langIndices : m_groupedByLang)
  {
    indicesOffsets.insert(std::make_pair(langIndices.first, currentOffset));
    currentOffset += langIndices.second.size();
  }

  for (auto & langMeta : m_langMetaCollection)
  {
    for (auto & translation : langMeta)
      translation.second += indicesOffsets[translation.first];
  }
}
}  // namespace descriptions


text:
<?php

/**
 * Permission store for table: permission
 */

namespace Octo\System\Store;

use b8\Database;
use Octo;
use Octo\System\Model\User;

/**
 * Permission Store
 * @uses Octo\System\Store\Base\PermissionStoreBase
 */
class PermissionStore extends Base\PermissionStoreBase
{
	public function updatePermissions($userId, $perms)
    {
        $pdo = Database::getConnection('write');

        $pdo->beginTransaction();

        try {
            $stmt = $pdo->prepare('DELETE FROM permission WHERE user_id = :userId');
            $stmt->bindValue(':userId', $userId);
            $stmt->execute();

            $pdo = Database::getConnection('write');
            $stmt = $pdo->prepare('INSERT INTO permission (user_id, uri, can_access) VALUES (:userId, :uri, :can)');

            foreach ($perms as $uri => $can) {
                $stmt->bindValue(':userId', $userId);
                $stmt->bindValue(':uri', $uri);
                $stmt->bindValue(':can', $can);
                $stmt->execute();
            }

            $pdo->commit();
        } catch (\Exception $ex) {
            $pdo->rollBack();
        }
    }

    public function getPermissionsArray(User $user)
    {
        $pdo = Database::getConnection('read');
        $stmt = $pdo->prepare('SELECT uri, can_access FROM permission WHERE user_id = :userId');
        $stmt->bindValue(':userId', $user->getId());

        if ($stmt->execute()) {
            $perms = $stmt->fetchAll(Database::FETCH_ASSOC);
            $rtn = [];

            foreach ($perms as $perm) {
                $rtn[$perm['uri']] = (bool)$perm['can_access'];
            }

            return $rtn;
        }

        return [];
    }
}


text:
import AbstractService from './AbstractService';
import SearchParameters from '../domain/SearchParameters';

/**
 * Websocket logs
 *
 * @author Radek Tomiška
 * @deprecated @since 9.2.0 websocket notification will be removed
 */
export default class WebsocketService extends AbstractService {

  getApiPath() {
    return '/notification-websockets';
  }

  getNiceLabel(entity) {
    if (!entity) {
      return '';
    }
    return entity.message.subject;
  }

  /**
   * Returns default searchParameters for current entity type
   *
   * @return {object} searchParameters
   */
  getDefaultSearchParameters() {
    return super.getDefaultSearchParameters().setName(SearchParameters.NAME_QUICK).clearSort().setSort('created', 'desc');
  }
}


text:
class AutoFilterFunctionalTest:
  public testing::Test
{
public:
  AutoFilterFunctionalTest(void) {
    AutoCurrentContext()->Initiate();
  }
};

void FilterFunction(const Decoration<0>& typeIn, auto_out<Decoration<1>> typeOut) {
  *typeOut = Decoration<1>(1 + 1 + typeIn.i);
}

TEST_F(AutoFilterFunctionalTest, FunctionDecorationTest) {
  // AddRecipient that is an instance of std::function f : a -> b
  // This must be satisfied by decoration of type a,
  // independent of the order of decoration.

  AutoRequired<AutoPacketFactory> factory;

  //Decoration with data first
  {
    auto packet = factory->NewPacket();
    packet->Decorate(Decoration<0>());
    ASSERT_EQ(1, packet->GetDecorationTypeCount()) << "Unexpected number of decorations";
    packet->AddRecipient(AutoFilterDescriptor(&FilterFunction));
    const Decoration<1>* getdec;
    ASSERT_TRUE(packet->Get(getdec)) << "Decoration function was not called";
    ASSERT_EQ(2, packet->GetDecorationTypeCount()) << "Unexpected number of decorations";
  }

  //Decoration with function first
  //NOTE: This test also catches failures to flush temporary subscriber information
  {
    auto packet = factory->NewPacket();
    packet->AddRecipient(AutoFilterDescriptor(&FilterFunction));
    packet->Decorate(Decoration<0>());
    const Decoration<1>* getdec;
    ASSERT_TRUE(packet->Get(getdec)) << "Decoration function was not called";
    ASSERT_EQ(2, packet->GetDecorationTypeCount()) << "Unexpected number of decorations";
  }
}

TEST_F(AutoFilterFunctionalTest, FunctionDecorationLambdaTest) {
  AutoRequired<AutoPacketFactory> factory;

  //Decoration with function first
  {
    auto packet = factory->NewPacket();
    int addType = 1;
    auto sentry = std::make_shared<bool>(true);
    *packet +=
      [addType, sentry](const Decoration<0>& typeIn, auto_out<Decoration<1>> typeOut) {
        *typeOut = Decoration<1>(1 + 1 + typeIn.i);
      };

    // Sentry's use count should be precisely two at this point
    ASSERT_EQ(2UL, sentry.use_count()) << "Appended recipient lambda was destroyed unexpectedly when it should have been pended";

    packet->Decorate(Decoration<0>());
    const Decoration<1>* getdec;
    ASSERT_TRUE(packet->Get(getdec)) << "Decoration function was not called";
    ASSERT_EQ(1 + addType, getdec->i) << "Increment was not applied";
  }
}

TEST_F(AutoFilterFunctionalTest, FunctionInjectorTest) {
  AutoRequired<AutoPacketFactory> factory;

  auto packet = factory->NewPacket();
  int addType = 1;
  packet->AddRecipient([addType](auto_out<Decoration<0>> typeOut) {
    *typeOut = Decoration<0>(addType);
  });
  const Decoration<0>* getdec;
  ASSERT_TRUE(packet->Get(getdec)) << "Decoration function was not called";
  ASSERT_EQ(0 + addType, getdec->i) << "Increment was not applied";
}

TEST_F(AutoFilterFunctionalTest, FunctionExtractorTest) {
  AutoRequired<AutoPacketFactory> factory;

  auto packet = factory->NewPacket();
  int extType = -1;
  packet->AddRecipient([&extType](const Decoration<1>& typeIn) {
    extType = typeIn.i;
  });
  packet->Decorate(Decoration<1>());
  ASSERT_EQ(1, extType) << "Decoration type was not extracted";
}

TEST_F(AutoFilterFunctionalTest, RecipientRemovalTest) {
  auto called = std::make_shared<bool>(false);
  AutoRequired<AutoPacketFactory> factory;

  // Add a recipient and then remove it, verify it doesn't get called
  auto packet = factory->NewPacket();
  const auto recipient =
    (
      *packet += [called] (const Decoration<0>&) {
        *called = true;
      }
    );
  packet->RemoveRecipient(*recipient);
  packet->Decorate(Decoration<0>());

  ASSERT_FALSE(*called) << "A recipient that should have been removed was called";
}

TEST_F(AutoFilterFunctionalTest, ObservingFunctionTest) {
  AutoRequired<AutoPacketFactory> factory;

  auto packet = factory->NewPacket();

  // Attach a lambda to a const version of this packet:
  auto called = std::make_shared<bool>(false);
  static_cast<const AutoPacket&>(*packet) += [called](const Decoration<0>& dec, Decoration<1> dec1) {
    *called = true;
  };

  // Verify that a call was made as expected once we decorate:
  packet->Decorate(Decoration<0>());
  packet->Decorate(Decoration<1>());
  ASSERT_TRUE(*called) << "Receive-only filter attached to a const packet image was not correctly called";
}

TEST_F(AutoFilterFunctionalTest, TripleFunctionTest) {
  AutoRequired<AutoPacketFactory> factory;

  auto packet = factory->NewPacket();

  // Attach two lambdas, verify they each get called when we expect;
  auto called1 = std::make_shared<bool>(false);
  auto called2 = std::make_shared<bool>(false);
  auto called3 = std::make_shared<bool>(false);
  *packet += [called1](const Decoration<0>&) { *called1 = true; };
  *packet += [called2](const Decoration<0>&, const Decoration<1>&) { *called2 = true; };
  *packet += [called3](const Decoration<1>&) { *called3 = true; };

  // Only the third method should be called
  packet->Decorate(Decoration<1>());

  ASSERT_FALSE(*called1) << "Incorrect filter method called in response to Decorate";
  ASSERT_FALSE(*called2) << "Incorrect filter method called in response to Decorate";
  ASSERT_TRUE(*called3) << "Filter method called when a decoration was absent";

  // Now the other two should be called:
  packet->Decorate(Decoration<0>());
  ASSERT_TRUE(*called1) << "Final observer method was not invoked as expected";
  ASSERT_TRUE(*called2) << "Two-argument observer method not invoked as expected";
}

TEST_F(AutoFilterFunctionalTest, MultiPostHocIntroductionTest) {
  AutoCurrentContext()->Initiate();
  AutoRequired<AutoPacketFactory> factory;

  int called = 0;

  *factory += [&called](int& out) { out = called++; };
  *factory += [&called](int& out) { out = called++; };

  // Add a gather step on the packet:
  auto packet = factory->NewPacket();
  *packet += [&called](const int* vals []){
    ASSERT_NE(nullptr, vals);
    called++;
  };

  ASSERT_EQ(3, called) << "Not all lambda functions were called as expected";
}


text:
package org.apache.metron.rest.model;

import java.util.List;

public class AlertsUIUserSettings {

  private String user;

  private List<String> tableColumns;

  private List<SavedSearch> savedSearches;

  private List<String> facetFields;

  public String getUser() {
    return user;
  }

  public void setUser(String user) {
    this.user = user;
  }

  public List<String> getTableColumns() {
    return tableColumns;
  }

  public void setTableColumns(List<String> tableColumns) {
    this.tableColumns = tableColumns;
  }

  public List<SavedSearch> getSavedSearches() {
    return savedSearches;
  }

  public void setSavedSearches(List<SavedSearch> savedSearches) {
    this.savedSearches = savedSearches;
  }

  public List<String> getFacetFields() {
    return facetFields;
  }

  public void setFacetFields(List<String> facetFields) {
    this.facetFields = facetFields;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    AlertsUIUserSettings that = (AlertsUIUserSettings) o;

    return (user != null ? user.equals(that.user) : that.user == null) &&
        (tableColumns != null ? tableColumns.equals(that.tableColumns) : that.tableColumns == null) &&
        (savedSearches != null ? savedSearches.equals(that.savedSearches) : that.savedSearches == null) &&
        (facetFields != null ? facetFields.equals(that.facetFields) : that.facetFields == null);
  }

  @Override
  public int hashCode() {
    int result = user != null ? user.hashCode() : 0;
    result = 31 * result + (tableColumns != null ? tableColumns.hashCode() : 0);
    result = 31 * result + (savedSearches != null ? savedSearches.hashCode() : 0);
    result = 31 * result + (facetFields != null ? facetFields.hashCode() : 0);
    return result;
  }
}


text:
./start-jobserver.sh
./start-master.sh && ./start-worker.sh


text:
Scrapy-Heroku
=============

A package to assist with running scrapy on heroku. This is accomplished by providing
a custom application configuration at ``scrapy_heroku.app.application`` that launches
the scrapyd web service using the PORT environment variable and a multi-process work
queue implemented on a Postgres database specified by the DATABASE_URL environment
variable.

Configuration
-------------

Create a git repo that has a scrapy project at the root (scrapy.cfg should be at the
top level). Edit your scrapy.cfg to include the following::

```python
[scrapyd]
application = scrapy_heroku.app.application

[deploy]
url = http://<YOUR_HEROKU_APP_NAME>.herokuapp.com:80/
project = <YOUR_PROJECT_NAME>
username = <A_USER_NAME>
password = <A_PASSWORD>
```

Add a requirements.txt file that includes ``scrapy``, ``scrapy-heroku``, and ``scrapyd``.
It is strongly recommended that you version pin scrapy-heroku as well as the version of scrapy that
your project is developed against (pip freeze > requirements.txt).

For Example:
```python
# requirements.txt
Scrapy==0.24.4
scrapyd==1.0.1
scrapy-heroku==0.7.1
```

Finally create a Procfile that consists of::

```
web: scrapyd
```

Make sure you have a postgres database with the DATABASE_URL env parameter set.

* Project page: <http://github.com/dmclain/scrapy-heroku>


text:
package com.rajat.e_subzi;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.rajat.e_subzi.Objects.ProductObject;
import com.rajat.e_subzi.Volley.CallVolley;

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

/**
 * Created by Rishab on 02-03-2016.
 */
public class DiscountListAdapter extends BaseAdapter {

    ArrayList<ProductObject> discounts=new ArrayList<ProductObject>();
    ArrayList<String>photoUrls=new ArrayList<String>();
    ArrayList<Boolean> delivery =new ArrayList<Boolean>();
    Context context;
    public DiscountListAdapter(ArrayList<ProductObject> discounts,ArrayList<String> photoUrls,ArrayList<Boolean> delivery,Context context){
        super();
        this.photoUrls=photoUrls;
        this.discounts=discounts;
        this.delivery=delivery;
        this.context=context;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return discounts.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.discount_list_view, null, true);
        final ImageView iv = (ImageView) row.findViewById(R.id.disc_image);
        CallVolley.getBitmapFromUrlBack(photoUrls.get(position), context, iv);
        TextView data = (TextView) row.findViewById(R.id.commodity);
        data.setText(discounts.get(position).getDescription());
        final String commodity =data.getText().toString();
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadPhoto(iv,commodity,400,400);
            }
        });
        data=(TextView)row.findViewById(R.id.price);
        data.setText("Price : "+Integer.toString(discounts.get(position).getPrice()));
        data=(TextView)row.findViewById(R.id.discount);
        data.setText("Discount : " + Integer.toString(discounts.get(position).getDiscount()));
        String format ="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
        String format2="yyyy-MM-dd HH:mm";
        SimpleDateFormat sdf2 = new SimpleDateFormat(format2, Locale.getDefault());
        Date date = null;
        String datetime="";
        try {
            String myDate= discounts.get(position).getCreated_at();
            //date = new Date(myDate);
            date = sdf.parse(myDate);

            Calendar cal = Calendar.getInstance(); // creates calendar
            cal.setTime(date); // sets calendar time/date=====> you can set your own date here
            cal.add(Calendar.HOUR_OF_DAY, 5); // adds one hour
            cal.add(Calendar.MINUTE, 30); // adds one Minute
            date=cal.getTime();
            datetime = sdf2.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            date = new Date();
        }
        data=(TextView)row.findViewById(R.id.created_at);
        data.setText("Created at: "+datetime);
        data=(TextView)row.findViewById(R.id.deliveryAvail);
        if(delivery.get(position)){
            data.setText("Delivery Available");
            data.setTextColor(Color.parseColor("#46b419"));
        }else{
            data.setText("Delivery Not Available");
            data.setTextColor(Color.RED);
        }

        return row;
    }
    private void loadPhoto(ImageView iv,String name, int width, int height) {

        AlertDialog.Builder imageDialog = new AlertDialog.Builder(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);

        View layout = inflater.inflate(R.layout.custom_fullimage_dialog,
                (ViewGroup) Discounts.lay);
        ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
        TextView text = (TextView)layout.findViewById(R.id.custom_fullimage_placename);
        text.setText(name);
        image.setImageDrawable(iv.getBackground());
        imageDialog.setView(layout);

        imageDialog.create();
        imageDialog.show();
    }
}


text:
Installation

<mat-sidenav-container>

  <mat-sidenav #sidenav mode="over" position="end">
    <app-config-tutorial></app-config-tutorial>
  </mat-sidenav>

  <mat-horizontal-stepper linear="true" #stepper>

    <mat-step label="Activate" [stepControl]="enableSyncFormControl">
      <mat-card>
        <app-enable-sync (syncStatus)="onSyncStatusChange($event)"></app-enable-sync>
      </mat-card>
    </mat-step>

    <mat-step label="Configure" [stepControl]="configSyncFormControl">
      <mat-card>
        <app-config-sync (submit)="onConfigSubmit()" (cancel)="onConfigCancel()"></app-config-sync>
      </mat-card>
    </mat-step>

    <mat-step label="Done">
      Synchronization configuration is finished. You are going to be redirected to the note app shortly ...
    </mat-step>

  </mat-horizontal-stepper>

</mat-sidenav-container>

<button
  id="open-help"
  type="button"
  mat-fab color="warn"
  (click)="sidenav.toggle()"
  title="Open sidebar help window describing how to get firebase settings"
  *ngIf="stepper.selectedIndex === 1">
  <mat-icon class="md-24" aria-label="Help icon">help</mat-icon>
</button>


text:
// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -std=c11

typedef struct S S; // expected-note 4 {{forward declaration of 'struct S'}}
extern _Atomic(S*) e;
void a(S* b, void* c) {
  void (*fp)(int) = 0;
  b++;       // expected-error {{arithmetic on a pointer to an incomplete type}}
  b += 1;    // expected-error {{arithmetic on a pointer to an incomplete type}}
  c++;       // expected-warning {{arithmetic on a pointer to void is a GNU extension}}
  c += 1;    // expected-warning {{arithmetic on a pointer to void is a GNU extension}}
  c--;       // expected-warning {{arithmetic on a pointer to void is a GNU extension}}
  c -= 1;    // expected-warning {{arithmetic on a pointer to void is a GNU extension}}
  (void) c[1]; // expected-warning {{subscript of a pointer to void is a GNU extension}}
  b = 1+b;   // expected-error {{arithmetic on a pointer to an incomplete type}}
  /* The next couple tests are only pedantic warnings in gcc */
  void (*d)(S*,void*) = a;
  d += 1;    // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' (aka 'void (struct S *, void *)') is a GNU extension}}
  d++;       // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' (aka 'void (struct S *, void *)') is a GNU extension}}
  d--;       // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' (aka 'void (struct S *, void *)') is a GNU extension}}
  d -= 1;    // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' (aka 'void (struct S *, void *)') is a GNU extension}}
  (void)(1 + d); // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' (aka 'void (struct S *, void *)') is a GNU extension}}
  e++;       // expected-error {{arithmetic on a pointer to an incomplete type}}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.WordLooper"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-sdk android:minSdkVersion="19"/>
    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>


text:
#include "proto/messages.h"

#include "config/heron-internals-config-vars.h"

namespace heron {
namespace config {

const sp_string HeronInternalsConfigVars::HERON_LOGGING_DIRECTORY = "heron.logging.directory";
const sp_string HeronInternalsConfigVars::HERON_LOGGING_MAXIMUM_SIZE_MB =
    "heron.logging.maximum.size.mb";
const sp_string HeronInternalsConfigVars::HERON_LOGGING_MAXIMUM_FILES =
    "heron.logging.maximum.files";
const sp_string HeronInternalsConfigVars::HERON_CHECK_TMANAGER_LOCATION_INTERVAL_SEC =
    "heron.check.tmanager.location.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_LOGGING_PRUNE_INTERVAL_SEC =
    "heron.logging.prune.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_LOGGING_FLUSH_INTERVAL_SEC =
    "heron.logging.flush.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_LOGGING_ERR_THRESHOLD =
    "heron.logging.err.threshold";

const sp_string HeronInternalsConfigVars::HERON_METRICS_EXPORT_INTERVAL_SEC =
    "heron.metrics.export.interval.sec";

// heron.metricsmgr.* configs are for the metrics manager
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_SCRIBE_HOST =
    "heron.metricsmgr.scribe.host";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_SCRIBE_PORT =
    "heron.metricsmgr.scribe.port";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_SCRIBE_CATEGORY =
    "heron.metricsmgr.scribe.category";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_SCRIBE_SERVICE_NAMESPACE =
    "heron.metricsmgr.scribe.service.namespace";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_SCRIBE_WRITE_RETRY_TIMES =
    "heron.metricsmgr.scribe.write.retry.times";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_SCRIBE_WRITE_TIMEOUT_SEC =
    "heron.metricsmgr.scribe.write.timeout.sec";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_SCRIBE_PERIODIC_FLUSH_INTERVAL_SEC =
    "heron.metricsmgr.scribe.periodic.flush.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_RECONNECT_TMANAGER_INTERVAL_SEC =
    "heron.metricsmgr.reconnect.tmanager.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_METRICSMGR_NETWORK_OPTIONS_MAXIMUM_PACKET_MB =
    "heron.metricsmgr.network.options.maximum.packet.mb";

// heron.tmanager.* configs are for the metrics manager
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_METRICS_COLLECTOR_MAXIMUM_INTERVAL_MIN =
    "heron.tmanager.metrics.collector.maximum.interval.min";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_ESTABLISH_RETRY_TIMES =
    "heron.tmanager.establish.retry.times";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_ESTABLISH_RETRY_INTERVAL_SEC =
    "heron.tmanager.establish.retry.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_NETWORK_SERVER_OPTIONS_MAXIMUM_PACKET_MB =
    "heron.tmanager.network.server.options.maximum.packet.mb";
const sp_string
    HeronInternalsConfigVars::HERON_TMANAGER_NETWORK_CONTROLLER_OPTIONS_MAXIMUM_PACKET_MB =
        "heron.tmanager.network.controller.options.maximum.packet.mb";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_NETWORK_STATS_OPTIONS_MAXIMUM_PACKET_MB =
    "heron.tmanager.network.stats.options.maximum.packet.mb";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_METRICS_COLLECTOR_PURGE_INTERVAL_SEC =
    "heron.tmanager.metrics.collector.purge.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_METRICS_COLLECTOR_MAXIMUM_EXCEPTION =
    "heron.tmanager.metrics.collector.maximum.exception";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_METRICS_NETWORK_BINDALLINTERFACES =
    "heron.tmanager.metrics.network.bindallinterfaces";
const sp_string HeronInternalsConfigVars::HERON_TMANAGER_STMGR_STATE_TIMEOUT_SEC =
    "heron.tmanager.stmgr.state.timeout.sec";

// heron.streammgr.* configs are for the stream manager
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_CACHE_DRAIN_FREQUENCY_MS =
    "heron.streammgr.cache.drain.frequency.ms";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_CACHE_DRAIN_SIZE_MB =
    "heron.streammgr.cache.drain.size.mb";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_MEMPOOL_MAX_MESSAGE_NUMBER =
    "heron.streammgr.mempool.max.message.number";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_XORMGR_ROTATINGMAP_NBUCKETS =
    "heron.streammgr.xormgr.rotatingmap.nbuckets";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_CLIENT_RECONNECT_INTERVAL_SEC =
    "heron.streammgr.client.reconnect.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_CLIENT_RECONNECT_TMANAGER_INTERVAL_SEC =
    "heron.streammgr.client.reconnect.tmanager.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_CLIENT_RECONNECT_TMANAGER_MAX_ATTEMPTS =
    "heron.streammgr.client.reconnect.tmanager.max.attempts";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_NETWORK_OPTIONS_MAXIMUM_PACKET_MB =
    "heron.streammgr.network.options.maximum.packet.mb";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_TMANAGER_HEARTBEAT_INTERVAL_SEC =
    "heron.streammgr.tmanager.heartbeat.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_CONNECTION_READ_BATCH_SIZE_MB =
    "heron.streammgr.connection.read.batch.size.mb";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_CONNECTION_WRITE_BATCH_SIZE_MB =
    "heron.streammgr.connection.write.batch.size.mb";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_NETWORK_BACKPRESSURE_THRESHOLD =
    "heron.streammgr.network.backpressure.threshold";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_NETWORK_BACKPRESSURE_HIGHWATERMARK_MB =
    "heron.streammgr.network.backpressure.highwatermark.mb";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_NETWORK_BACKPRESSURE_LOWWATERMARK_MB =
    "heron.streammgr.network.backpressure.lowwatermark.mb";
const sp_string HeronInternalsConfigVars::HERON_STREAMMGR_STATEFUL_BUFFER_SIZE_MB =
    "heron.streammgr.stateful.buffer.size.mb";

// heron.instance.* configs are for the instance
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_RECONNECT_STREAMMGR_INTERVAL_SEC =
    "heron.instance.reconnect.streammgr.interval.sec";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_RECONNECT_STREAMMGR_TIMES =
    "heron.instance.reconnect.streammgr.times";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_INTERNAL_BOLT_READ_QUEUE_CAPACITY =
    "heron.instance.internal.bolt.read.queue.capacity";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_INTERNAL_BOLT_WRITE_QUEUE_CAPACITY =
    "heron.instance.internal.bolt.write.queue.capacity";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_INTERNAL_SPOUT_READ_QUEUE_CAPACITY =
    "heron.instance.internal.spout.read.queue.capacity";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_INTERNAL_SPOUT_WRITE_QUEUE_CAPACITY =
    "heron.instance.internal.spout.write.queue.capacity";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_EMIT_BATCH_TIME_MS =
    "heron.instance.emit.batch.time.ms";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_EMIT_BATCH_SIZE =
    "heron.instance.emit.batch.size.bytes";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_SET_DATA_TUPLE_CAPACITY =
    "heron.instance.set.data.tuple.capacity";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_SET_DATA_TUPLE_SIZE_BYTES =
    "heron.instance.set.data.tuple.size.bytes";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_SET_CONTROL_TUPLE_CAPACITY =
    "heron.instance.set.control.tuple.capacity";
const sp_string HeronInternalsConfigVars::HERON_INSTANCE_ACKNOWLEDGEMENT_NBUCKETS =
    "heron.instance.acknowledgement.nbuckets";
}  // namespace config
}  // namespace heron


text:
package bftsmart.demo.counter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import java.io.InputStreamReader;

import bftsmart.tom.ServiceProxy;
import bftsmart.tom.server.BatchExecutable;
import bftsmart.tom.server.Recoverable;
import bftsmart.tom.util.Logger;

import hermes.HermesConfig;
import hermes.orchestration.notification.StatNotification;
import hermes.runtime.HermesRuntime;
import hermes.runtime.bft.BFTNode;
import hermes.stats.StatToken;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import hermes.stats.Stats;

/**
 * Example client that updates a BFT replicated service (a counter).
 *
 */
public final class CounterClient extends Object {

    static protected void hermesCodeInjection(String[] args) {
        String id = args[0];

        //HermesRuntime m_runtime = new HermesRuntime();
        HermesRuntime.getInstance().setID(id);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
        Date date = new Date();
        dateFormat.format(date);
        String prefix = "replica";
        if (id.compareTo("1001") == 0) {
            System.out.println("\nCLIENT\n");
            prefix = "client";
        } else {
            System.out.println("\nREPLICA\n");
        }
        String logName = HermesConfig.getWorkingDir() + "/node_" + prefix + "_"
                + HermesRuntime.getInstance().getRuntimeID() + "_" + dateFormat.format(date) + ".log";
        HermesConfig.addLoggerFile(logName);
        try {
            HermesRuntime.getInstance().open();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public CounterClient() {
    }

    //@SuppressWarnings("static-access")
    public static void main(String[] args) {// throws IOException {

        if (args.length < 2) {
            System.out.println("Usage: java ...CounterClient <process id> <increment> [<number of operations>]");
            System.out.println("       if <increment> equals 0 the request will be read-only");
            System.out.println("       default <number of operations> equals 1000");
            System.exit(-1);
        }
        hermesCodeInjection(args);
        ServiceProxy counterProxy = new ServiceProxy(Integer.parseInt(args[0]));

        //counterProxy.setInvokeTimeout(1);
        //Stats stats = new Stats();
        long start, end;
        int result = 0;

        try {

            int inc = Integer.parseInt(args[1]);
            int numberOfOps = (args.length > 2) ? Integer.parseInt(args[2]) : 1000;

            boolean wait = false;

            if ((args.length > 2 && args[2].equals("wait"))
                    || (args.length > 3 && args[3].equals("wait"))) {
                wait = true;
            }

            Logger.debug = false;
            BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));

            for (int i = 0; i < numberOfOps; i++) {

                if (wait) {
                    System.out.println("Iteration " + i);
                    System.out.println("Press Enter for next iteration, type 'exit' to exit or type 'go' to run all remaining iterations");

                    String lido = inReader.readLine();

                    if (lido.equals("exit")) {
                        break;
                    } else if (lido.equals("go")) {
                        wait = false;
                    }
                }

                ByteArrayOutputStream out = new ByteArrayOutputStream(4);
                new DataOutputStream(out).writeInt(inc);

                System.out.println("Counter sending: " + i);
                start = System.nanoTime();
                byte[] reply;
                if (inc == 0) {
                    reply = counterProxy.invokeUnordered(out.toByteArray());
                } else {
                    reply = counterProxy.invokeOrdered(out.toByteArray());
                }

                end = System.nanoTime();
                //stats.collect(i, end-start);
                HermesRuntime.getInstance().notification(
                        new StatNotification(HermesRuntime.getInstance().getRuntimeID(),
                        new StatToken(i, end - start)), 10000);

                //System.out.println("delta: " + ((float) end - (float) start) / (float) 1000000);
                if (reply != null) {
                    int newValue = new DataInputStream(new ByteArrayInputStream(reply)).readInt();
                    System.out.println("Counter value: " + newValue);
                    result = 0;
                } else {
                    result = 1;
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            result = 1;
        } finally {
            counterProxy.close();
            System.exit(result);
        }
    }
}


text:
#define DEBUG_FBUPDATE 0
#include <gralloc_priv.h>
#include <overlay.h>
#include "hwc_fbupdate.h"
#include "mdp_version.h"

using namespace qdutils;
using namespace overlay;

namespace qhwc {

namespace ovutils = overlay::utils;

IFBUpdate* IFBUpdate::getObject(const int& width, const int& rightSplit,
        const int& dpy) {
    if(width > MAX_DISPLAY_DIM || rightSplit) {
        return new FBUpdateHighRes(dpy);
    }
    return new FBUpdateLowRes(dpy);
}

inline void IFBUpdate::reset() {
    mModeOn = false;
}

//================= Low res====================================
FBUpdateLowRes::FBUpdateLowRes(const int& dpy): IFBUpdate(dpy) {}

inline void FBUpdateLowRes::reset() {
    IFBUpdate::reset();
    mDest = ovutils::OV_INVALID;
}

bool FBUpdateLowRes::prepare(hwc_context_t *ctx, hwc_display_contents_1 *list,
                             int fbZorder) {
    if(!ctx->mMDP.hasOverlay) {
        ALOGD_IF(DEBUG_FBUPDATE, "%s, this hw doesnt support overlays",
                 __FUNCTION__);
        return false;
    }
    mModeOn = configure(ctx, list, fbZorder);
    return mModeOn;
}

// Configure
bool FBUpdateLowRes::configure(hwc_context_t *ctx, hwc_display_contents_1 *list,
                               int fbZorder) {
    bool ret = false;
    hwc_layer_1_t *layer = &list->hwLayers[list->numHwLayers - 1];
    if (LIKELY(ctx->mOverlay)) {
        overlay::Overlay& ov = *(ctx->mOverlay);
        private_handle_t *hnd = (private_handle_t *)layer->handle;
        ovutils::Whf info(getWidth(hnd), getHeight(hnd),
                          ovutils::getMdpFormat(hnd->format), hnd->size);

        //Request a pipe
        ovutils::eMdpPipeType type = ovutils::OV_MDP_PIPE_ANY;
        if(qdutils::MDPVersion::getInstance().is8x26() && mDpy) {
            //For 8x26 external always use DMA pipe
            type = ovutils::OV_MDP_PIPE_DMA;
        }
        ovutils::eDest dest = ov.nextPipe(type, mDpy, Overlay::MIXER_DEFAULT);
        if(dest == ovutils::OV_INVALID) { //None available
            ALOGE("%s: No pipes available to configure framebuffer",
                __FUNCTION__);
            return false;
        }

        mDest = dest;

        ovutils::eMdpFlags mdpFlags = ovutils::OV_MDP_BLEND_FG_PREMULT;

        ovutils::eZorder zOrder = static_cast<ovutils::eZorder>(fbZorder);

        //XXX: FB layer plane alpha is currently sent as zero from
        //surfaceflinger
        ovutils::PipeArgs parg(mdpFlags,
                info,
                zOrder,
                ovutils::IS_FG_OFF,
                ovutils::ROT_FLAGS_NONE,
                ovutils::DEFAULT_PLANE_ALPHA,
                (ovutils::eBlending) getBlending(layer->blending));
        ov.setSource(parg, dest);

        hwc_rect_t sourceCrop;
        getNonWormholeRegion(list, sourceCrop);
        // x,y,w,h
        ovutils::Dim dcrop(sourceCrop.left, sourceCrop.top,
                           sourceCrop.right - sourceCrop.left,
                           sourceCrop.bottom - sourceCrop.top);
        ov.setCrop(dcrop, dest);

        int transform = layer->transform;
        ovutils::eTransform orient =
            static_cast<ovutils::eTransform>(transform);
        ov.setTransform(orient, dest);

        if(!qdutils::MDPVersion::getInstance().is8x26()) {
            getNonWormholeRegion(list, sourceCrop);
        }

        hwc_rect_t displayFrame = sourceCrop;
        ovutils::Dim dpos(displayFrame.left,
                          displayFrame.top,
                          displayFrame.right - displayFrame.left,
                          displayFrame.bottom - displayFrame.top);

        if(mDpy && !qdutils::MDPVersion::getInstance().is8x26())
            // Calculate the actionsafe dimensions for External(dpy = 1 or 2)
            getActionSafePosition(ctx, mDpy, dpos.x, dpos.y, dpos.w, dpos.h);
        ov.setPosition(dpos, dest);

        ret = true;
        if (!ov.commit(dest)) {
            ALOGE("%s: commit fails", __FUNCTION__);
            ret = false;
        }
    }
    return ret;
}

bool FBUpdateLowRes::draw(hwc_context_t *ctx, private_handle_t *hnd)
{
    if(!mModeOn) {
        return true;
    }
    bool ret = true;
    overlay::Overlay& ov = *(ctx->mOverlay);
    ovutils::eDest dest = mDest;
    if (!ov.queueBuffer(hnd->fd, hnd->offset, dest)) {
        ALOGE("%s: queueBuffer failed for FBUpdate", __FUNCTION__);
        ret = false;
    }
    return ret;
}

//================= High res====================================
FBUpdateHighRes::FBUpdateHighRes(const int& dpy): IFBUpdate(dpy) {}

inline void FBUpdateHighRes::reset() {
    IFBUpdate::reset();
    mDestLeft = ovutils::OV_INVALID;
    mDestRight = ovutils::OV_INVALID;
}

bool FBUpdateHighRes::prepare(hwc_context_t *ctx, hwc_display_contents_1 *list,
                              int fbZorder) {
    if(!ctx->mMDP.hasOverlay) {
        ALOGD_IF(DEBUG_FBUPDATE, "%s, this hw doesnt support overlays",
                 __FUNCTION__);
        return false;
    }
    ALOGD_IF(DEBUG_FBUPDATE, "%s, mModeOn = %d", __FUNCTION__, mModeOn);
    mModeOn = configure(ctx, list, fbZorder);
    return mModeOn;
}

// Configure
bool FBUpdateHighRes::configure(hwc_context_t *ctx,
        hwc_display_contents_1 *list, int fbZorder) {
    bool ret = false;
    hwc_layer_1_t *layer = &list->hwLayers[list->numHwLayers - 1];
    if (LIKELY(ctx->mOverlay)) {
        overlay::Overlay& ov = *(ctx->mOverlay);
        private_handle_t *hnd = (private_handle_t *)layer->handle;
        ovutils::Whf info(getWidth(hnd), getHeight(hnd),
                          ovutils::getMdpFormat(hnd->format), hnd->size);

        //Request left pipe
        ovutils::eDest destL = ov.nextPipe(ovutils::OV_MDP_PIPE_ANY, mDpy,
                Overlay::MIXER_LEFT);
        if(destL == ovutils::OV_INVALID) { //None available
            ALOGE("%s: No pipes available to configure framebuffer",
                __FUNCTION__);
            return false;
        }
        //Request right pipe
        ovutils::eDest destR = ov.nextPipe(ovutils::OV_MDP_PIPE_ANY, mDpy,
                Overlay::MIXER_RIGHT);
        if(destR == ovutils::OV_INVALID) { //None available
            ALOGE("%s: No pipes available to configure framebuffer",
                __FUNCTION__);
            return false;
        }

        mDestLeft = destL;
        mDestRight = destR;

        ovutils::eMdpFlags mdpFlagsL = ovutils::OV_MDP_BLEND_FG_PREMULT;

        ovutils::eZorder zOrder = static_cast<ovutils::eZorder>(fbZorder);

        //XXX: FB layer plane alpha is currently sent as zero from
        //surfaceflinger
        ovutils::PipeArgs pargL(mdpFlagsL,
                info,
                zOrder,
                ovutils::IS_FG_OFF,
                ovutils::ROT_FLAGS_NONE,
                ovutils::DEFAULT_PLANE_ALPHA,
                (ovutils::eBlending) getBlending(layer->blending));
        ov.setSource(pargL, destL);

        ovutils::eMdpFlags mdpFlagsR = mdpFlagsL;
        ovutils::setMdpFlags(mdpFlagsR, ovutils::OV_MDSS_MDP_RIGHT_MIXER);
        ovutils::PipeArgs pargR(mdpFlagsR,
                info,
                zOrder,
                ovutils::IS_FG_OFF,
                ovutils::ROT_FLAGS_NONE,
                ovutils::DEFAULT_PLANE_ALPHA,
                (ovutils::eBlending) getBlending(layer->blending));
        ov.setSource(pargR, destR);

        hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
        hwc_rect_t displayFrame = layer->displayFrame;

        const float xres = ctx->dpyAttr[mDpy].xres;
        const int lSplit = getLeftSplit(ctx, mDpy);
        const float lSplitRatio = lSplit / xres;
        const float lCropWidth =
                (sourceCrop.right - sourceCrop.left) * lSplitRatio;

        ovutils::Dim dcropL(
                sourceCrop.left,
                sourceCrop.top,
                lCropWidth,
                sourceCrop.bottom - sourceCrop.top);

        ovutils::Dim dcropR(
                sourceCrop.left + lCropWidth,
                sourceCrop.top,
                (sourceCrop.right - sourceCrop.left) - lCropWidth,
                sourceCrop.bottom - sourceCrop.top);

        ov.setCrop(dcropL, destL);
        ov.setCrop(dcropR, destR);

        int transform = layer->transform;
        ovutils::eTransform orient =
            static_cast<ovutils::eTransform>(transform);
        ov.setTransform(orient, destL);
        ov.setTransform(orient, destR);

        const int lWidth = (lSplit - displayFrame.left);
        const int rWidth = (displayFrame.right - lSplit);
        const int height = displayFrame.bottom - displayFrame.top;

        ovutils::Dim dposL(displayFrame.left,
                           displayFrame.top,
                           lWidth,
                           height);
        ov.setPosition(dposL, destL);

        ovutils::Dim dposR(0,
                           displayFrame.top,
                           rWidth,
                           height);
        ov.setPosition(dposR, destR);

        ret = true;
        if (!ov.commit(destL)) {
            ALOGE("%s: commit fails for left", __FUNCTION__);
            ret = false;
        }
        if (!ov.commit(destR)) {
            ALOGE("%s: commit fails for right", __FUNCTION__);
            ret = false;
        }
    }
    return ret;
}

bool FBUpdateHighRes::draw(hwc_context_t *ctx, private_handle_t *hnd)
{
    if(!mModeOn) {
        return true;
    }
    bool ret = true;
    overlay::Overlay& ov = *(ctx->mOverlay);
    ovutils::eDest destL = mDestLeft;
    ovutils::eDest destR = mDestRight;
    if (!ov.queueBuffer(hnd->fd, hnd->offset, destL)) {
        ALOGE("%s: queue failed for left of dpy = %d",
              __FUNCTION__, mDpy);
        ret = false;
    }
    if (!ov.queueBuffer(hnd->fd, hnd->offset, destR)) {
        ALOGE("%s: queue failed for right of dpy = %d",
              __FUNCTION__, mDpy);
        ret = false;
    }
    return ret;
}

//---------------------------------------------------------------------
}; //namespace qhwc


text:
from django.core.management.base import (BaseCommand, CommandError)
from myadmin.backenddb import (insert_custom_areas, insert_default_categories)

class Command(BaseCommand):
    help = 'Closes the specified poll for voting'

    def add_arguments(self, parser):
        pass
        # parser.add_argument('poll_id', nargs='+', type=int)

    def handle(self, *args, **options):
        # load default areas
        insert_custom_areas('Bangalore', 'Karnataka', 'India')
        # load default categories
        insert_default_categories()


text:
package spool

import (
	"fmt"
	"os"

	"github.com/vektra/cypress"
	"github.com/vektra/cypress/cli/commands"
)

type Send struct {
	Dir string `short:"d" description:"where to write the messages to"`
}

func (s *Send) Execute(args []string) error {
	if s.Dir == "" {
		return fmt.Errorf("no target specified")
	}

	if _, err := os.Stat(s.Dir); err != nil {
		os.MkdirAll(s.Dir, 0755)
	}

	spool, err := NewSpool(s.Dir)
	if err != nil {
		return err
	}

	dec, err := cypress.NewStreamDecoder(os.Stdin)
	if err != nil {
		return err
	}

	return cypress.Glue(dec, spool)
}

type Recv struct {
	Dir string `short:"d" description:"where to write the messages to"`
}

func (r *Recv) Execute(args []string) error {
	if r.Dir == "" {
		return fmt.Errorf("no target specified")
	}

	if _, err := os.Stat(r.Dir); err != nil {
		return err
	}

	spool, err := NewSpool(r.Dir)
	if err != nil {
		return err
	}

	enc := cypress.NewStreamEncoder(os.Stdout)

	gen, err := spool.Generator()
	if err != nil {
		return err
	}

	return cypress.Glue(gen, enc)
}

func init() {
	commands.Add("spool:send", "write messages to a spool", "", &Send{})
	commands.Add("spool:recv", "read messages from a spool", "", &Recv{})
}


text:
package au.gov.ga.geodesy.sitelog.domain.model;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;

/**
 * http://sopac.ucsd.edu/ns/geodesy/doc/igsSiteLog/monumentInfo/2004/siteIdentification.xsd:siteIdentificationType
 */
public class SiteIdentification {

   @Size(max = 200)
   protected String siteName;

   @NotNull
   @Size(min = 4, max = 4)
   protected String fourCharacterId;

   @Size(max = 200)
   protected String monumentInscription;

   @Size(max = 200)
   protected String iersDOMESNumber;

   @Size(max = 200)
   protected String cdpNumber;

   @Size(max = 200)
   protected String monumentDescription;

   @Size(max = 200)
   protected String heightOfMonument;

   @Size(max = 200)
   protected String monumentFoundation;

   @Size(max = 200)
   protected String foundationDepth;

   @Size(max = 200)
   protected String markerDescription;

   @Past
   protected Date dateInstalled;

   @Size(max = 200)
   protected String geologicCharacteristic;

   @Size(max = 200)
   protected String bedrockType;

   @Size(max = 200)
   protected String bedrockCondition;

   @Size(max = 200)
   protected String fractureSpacing;

   @Size(max = 200)
   protected String faultZonesNearby;

   @Size(max = 200)
   protected String distanceActivity;

   @Size(max = 4000)
   protected String notes;

   /**
    * Return site name.
    */
   public String getSiteName() {
      return siteName;
   }

   /**
    * Set site name.
    */
   public void setSiteName(String value) {
      this.siteName = value;
   }

   /**
    * Return four character id.
    */
   public String getFourCharacterId() {
      return fourCharacterId;
   }

   /**
    * Set four character id. Four character IDs are converted and stored in upper case.
    */
   public void setFourCharacterId(String value) {
      this.fourCharacterId = value != null ? value.toUpperCase() : null;
   }

   /**
    * Return monument inscription.
    */
   public String getMonumentInscription() {
      return monumentInscription;
   }

   /**
    * Set monument inscription.
    */
   public void setMonumentInscription(String value) {
      this.monumentInscription = value;
   }

   /**
    * Return IERS DOMES number.
    */
   public String getIersDOMESNumber() {
      return iersDOMESNumber;
   }

   /**
    * Set IERS DOMES number.
    */
   public void setIersDOMESNumber(String value) {
      this.iersDOMESNumber = value;
   }

   /**
    * Return CDP number.
    */
   public String getCdpNumber() {
      return cdpNumber;
   }

   /**
    * Set CDP number.
    */
   public void setCdpNumber(String value) {
      this.cdpNumber = value;
   }

   /**
    * Return monument description type.
    */
   public String getMonumentDescription() {
      return monumentDescription;
   }

   /**
    * Set monumnent description type.
    */
   public void setMonumentDescription(String value) {
      this.monumentDescription = value;
   }

   /**
    * Return height of monument.
    */
   public String getHeightOfMonument() {
      return heightOfMonument;
   }

   /**
    * Set height of monument.
    */
   public void setHeightOfMonument(String value) {
      this.heightOfMonument = value;
   }

   /**
    * Return monument foundation.
    */
   public String getMonumentFoundation() {
      return monumentFoundation;
   }

   /**
    * Set monument foundation.
    */
   public void setMonumentFoundation(String value) {
      this.monumentFoundation = value;
   }

   /**
    * Return foundation depth.
    */
   public String getFoundationDepth() {
      return foundationDepth;
   }

   /**
    * Set foundation depth.
    */
   public void setFoundationDepth(String value) {
      this.foundationDepth = value;
   }

   /**
    * Return marker description.
    */
   public String getMarkerDescription() {
      return markerDescription;
   }

   /**
    * Set marker description.
    */
   public void setMarkerDescription(String value) {
      this.markerDescription = value;
   }

   /**
    * Return date installed.
    */
   public Date getDateInstalled() {
      return dateInstalled;
   }

   /**
    * Set date installed.
    */
   public void setDateInstalled(Date value) {
      this.dateInstalled = value;
   }

   /**
    * Return geologic characteristic.
    */
   public String getGeologicCharacteristic() {
      return geologicCharacteristic;
   }

   /**
    * Set geologic characteristic.
    */
   public void setGeologicCharacteristic(String value) {
      this.geologicCharacteristic = value;
   }

   /**
    * Return bedrock type.
    */
   public String getBedrockType() {
      return bedrockType;
   }

   /**
    * Set bedrock type.
    */
   public void setBedrockType(String value) {
      this.bedrockType = value;
   }

   /**
    * Return bedrock condition.
    */
   public String getBedrockCondition() {
      return bedrockCondition;
   }

   /**
    * Set bedrock condition.
    */
   public void setBedrockCondition(String value) {
      this.bedrockCondition = value;
   }

   /**
    * Return fracture spacing.
    */
   public String getFractureSpacing() {
      return fractureSpacing;
   }

   /**
    * Set fracture spacing.
    */
   public void setFractureSpacing(String value) {
      this.fractureSpacing = value;
   }

   /**
    * Return nearby fault zones.
    */
   public String getFaultZonesNearby() {
      return faultZonesNearby;
   }

   /**
    * Set nearby fault zones.
    */
   public void setFaultZonesNearby(String value) {
      this.faultZonesNearby = value;
   }

   /**
    * Return distance activity.
    */
   public String getDistanceActivity() {
      return distanceActivity;
   }

   /**
    * Set distance activity.
    */
   public void setDistanceActivity(String value) {
      this.distanceActivity = value;
   }

   /**
    * Return notes.
    */
   public String getNotes() {
      return notes;
   }

   /**
    * Set notes.
    */
   public void setNotes(String value) {
      this.notes = value;
   }
}


text:
<?php
#
# rt-theme
# loop item for portfolio custom posts
# image post format
#

$testimonial = get_post_meta( $post->ID, RT_COMMON_THEMESLUG.'_testimonial', true);
$name = get_post_meta( $post->ID, RT_COMMON_THEMESLUG.'_name', true);
$title = get_post_meta( $post->ID, RT_COMMON_THEMESLUG.'_title', true);
$link = get_post_meta( $post->ID, RT_COMMON_THEMESLUG.'_link', true);
$link_text = get_post_meta( $post->ID, RT_COMMON_THEMESLUG.'_link_text', true);
$add_class = has_post_thumbnail() ? "with_image" : "";
?>

<?php if ( has_post_thumbnail() && ! post_password_required() ) : ?>

	<?php
	// Create thumbnail image
	$thumbnail_image_output = get_resized_image_output( array( "image_url" => "", "image_id" => get_post_thumbnail_id(), "w" => 400, "h" => 400, "crop" => true ) );
	echo $thumbnail_image_output;
	?>

<?php endif;?>

<div class="text <?php echo $add_class;?>">

			<?php echo $testimonial; ?>

		<?php echo $name; ?>
		<?php echo ! empty( $title ) ? '- '. $title. '' : "" ; ?>

		<?php echo ! empty( $link ) && ! empty( $link_text ) ? ''. str_replace( "http://","",$link_text ). '' : "" ; ?>
		<?php echo ! empty( $link ) && empty( $link_text ) ? ''. str_replace( "http://","",$link ). '' : "" ; ?>


text:
using namespace std;

class TCounter {
public:
    TCounter(const char* str, size_t subStringLen=2)
        : String {str}
        , Length {subStringLen}
    {
        Init();
    }
    TCounter(const string& str, size_t subStringLen=2)
        : String {str}
        , Length {subStringLen}
    {
        Init();
    }
    string Str() const {
        return String;
    }
    size_t SubStrLength() const {
        return Length;
    }
    bool Has(const string& substr) const {
        return SubStrings.count(substr);
    }
    size_t operator[](const string& substr) const {
        return SubStrings.at(substr);
    }
private:
    void Init() {
        if (String.size() >= Length) {
            for(size_t pos {0}, end {String.size() - Length + 1}; pos < end; ++pos) {
                ++SubStrings[String.substr(pos, Length)];
            }
        }
    }
private:
    string String;
    size_t Length;
    map<string, size_t> SubStrings;
};

class TSubStrings {
public:
    class TIterator {
    public:
        TIterator()
            : SubStr {}
        {}
        TIterator(size_t len, char ch)
            : SubStr (len, ch)
        {}
        string& operator*() {
            return SubStr;
        }
        TIterator& operator++() {
            if (not SubStr.empty()) {
                for(size_t pos {SubStr.size()}; pos--; ) {
                    if (SubStr[pos] == 'z') {
                        SubStr[pos] = 'a';
                    } else {
                        ++SubStr[pos];
                        return *this;
                    }
                }
                SubStr.clear();
            }
            return *this;
        }
        bool operator!=(const TIterator& that) {
            return SubStr != that.SubStr;
        }
    private:
        string SubStr;
    };
public:
    TSubStrings(const size_t& len)
        : Length {len}
    {}
    TIterator begin() {
        return TIterator {Length, 'a'};
    }
    TIterator end() {
        return TIterator {};
    }
private:
    size_t Length;
};

void CountAllCombinations(const TCounter& counter) {
    cout << "str: " << counter.Str() << endl;
    cout << "len: " << counter.Str().size() << endl;
    cout << "sub str len: " << counter.SubStrLength() << endl;
    if (counter.SubStrLength() <= counter.Str().size()) {
        for(const string& subStr : TSubStrings {counter.SubStrLength()}) {
            if (counter.Has(subStr)) {
                cout << ' ' << subStr << ": " << counter[subStr] << endl;
            }
        }
    }
}

int main(int, char* []) {
    CountAllCombinations(TCounter {"xabaacbaxabb"});
    cout << "---" << endl;
    CountAllCombinations(TCounter {string {"xabaacbaxabb"}, 3});
    cout << "---" << endl;
    CountAllCombinations(TCounter {string {"xabaacbaxabb"}, 4});
    cout << "---" << endl;
    CountAllCombinations(TCounter {"xabaacbaxabb", 1});
    return 0;
}


text:
module WhereIn6 where

--A definition can be demoted to the local 'where' binding of a friend declaration,
--if it is only used by this friend declaration.

--Demoting a definition narrows down the scope of the definition.
--In this example, demote the top level 'addthree' to 'fun'
--This example also aims to test the removing of parameters and parentheses.

fun x y z =inc (addthree x y z)
       where inc a =a +1

addthree a b c=a+b+c