text:
/* $Date: 2005/10/22 00:42:59 $ $RCSfile: mac.c,v $ $Revision: 1.32 $ */
#include "gmac.h"
#include "regs.h"
#include "fpga_defs.h"

#define MAC_CSR_INTERFACE_GMII      0x0
#define MAC_CSR_INTERFACE_TBI       0x1
#define MAC_CSR_INTERFACE_MII       0x2
#define MAC_CSR_INTERFACE_RMII      0x3

/* Chelsio's MAC statistics. */
struct mac_statistics {

	/* Transmit */
	u32 TxFramesTransmittedOK;
	u32 TxReserved1;
	u32 TxReserved2;
	u32 TxOctetsTransmittedOK;
	u32 TxFramesWithDeferredXmissions;
	u32 TxLateCollisions;
	u32 TxFramesAbortedDueToXSCollisions;
	u32 TxFramesLostDueToIntMACXmitError;
	u32 TxReserved3;
	u32 TxMulticastFrameXmittedOK;
	u32 TxBroadcastFramesXmittedOK;
	u32 TxFramesWithExcessiveDeferral;
	u32 TxPAUSEMACCtrlFramesTransmitted;

	/* Receive */
	u32 RxFramesReceivedOK;
	u32 RxFrameCheckSequenceErrors;
	u32 RxAlignmentErrors;
	u32 RxOctetsReceivedOK;
	u32 RxFramesLostDueToIntMACRcvError;
	u32 RxMulticastFramesReceivedOK;
	u32 RxBroadcastFramesReceivedOK;
	u32 RxInRangeLengthErrors;
	u32 RxTxOutOfRangeLengthField;
	u32 RxFrameTooLongErrors;
	u32 RxPAUSEMACCtrlFramesReceived;
};

static int static_aPorts[] = {
	FPGA_GMAC_INTERRUPT_PORT0,
	FPGA_GMAC_INTERRUPT_PORT1,
	FPGA_GMAC_INTERRUPT_PORT2,
	FPGA_GMAC_INTERRUPT_PORT3
};

struct _cmac_instance {
	u32 index;
};

static int mac_intr_enable(struct cmac *mac)
{
	u32 mac_intr;

	if (t1_is_asic(mac->adapter)) {
		/* ASIC */

		/* We don't use the on chip MAC for ASIC products. */
	} else {
		/* FPGA */

		/* Set parent gmac interrupt. */
		mac_intr = readl(mac->adapter->regs + A_PL_ENABLE);
		mac_intr |= FPGA_PCIX_INTERRUPT_GMAC;
		writel(mac_intr, mac->adapter->regs + A_PL_ENABLE);

		mac_intr = readl(mac->adapter->regs + FPGA_GMAC_ADDR_INTERRUPT_ENABLE);
		mac_intr |= static_aPorts[mac->instance->index];
		writel(mac_intr,
		       mac->adapter->regs + FPGA_GMAC_ADDR_INTERRUPT_ENABLE);
	}

	return 0;
}

static int mac_intr_disable(struct cmac *mac)
{
	u32 mac_intr;

	if (t1_is_asic(mac->adapter)) {
		/* ASIC */

		/* We don't use the on chip MAC for ASIC products. */
	} else {
		/* FPGA */

		/* Set parent gmac interrupt. */
		mac_intr = readl(mac->adapter->regs + A_PL_ENABLE);
		mac_intr &= ~FPGA_PCIX_INTERRUPT_GMAC;
		writel(mac_intr, mac->adapter->regs + A_PL_ENABLE);

		mac_intr = readl(mac->adapter->regs + FPGA_GMAC_ADDR_INTERRUPT_ENABLE);
		mac_intr &= ~(static_aPorts[mac->instance->index]);
		writel(mac_intr,
		       mac->adapter->regs + FPGA_GMAC_ADDR_INTERRUPT_ENABLE);
	}

	return 0;
}

static int mac_intr_clear(struct cmac *mac)
{
	u32 mac_intr;

	if (t1_is_asic(mac->adapter)) {
		/* ASIC */

		/* We don't use the on chip MAC for ASIC products. */
	} else {
		/* FPGA */

		/* Set parent gmac interrupt. */
		writel(FPGA_PCIX_INTERRUPT_GMAC,
		       mac->adapter->regs +  A_PL_CAUSE);
		mac_intr = readl(mac->adapter->regs + FPGA_GMAC_ADDR_INTERRUPT_CAUSE);
		mac_intr |= (static_aPorts[mac->instance->index]);
		writel(mac_intr,
		       mac->adapter->regs + FPGA_GMAC_ADDR_INTERRUPT_CAUSE);
	}

	return 0;
}

static int mac_get_address(struct cmac *mac, u8 addr[6])
{
	u32 data32_lo, data32_hi;

	data32_lo = readl(mac->adapter->regs
			  + MAC_REG_IDLO(mac->instance->index));
	data32_hi = readl(mac->adapter->regs
			  + MAC_REG_IDHI(mac->instance->index));

	addr[0] = (u8) ((data32_hi >> 8) & 0xFF);
	addr[1] = (u8) ((data32_hi) & 0xFF);
	addr[2] = (u8) ((data32_lo >> 24) & 0xFF);
	addr[3] = (u8) ((data32_lo >> 16) & 0xFF);
	addr[4] = (u8) ((data32_lo >> 8) & 0xFF);
	addr[5] = (u8) ((data32_lo) & 0xFF);
	return 0;
}

static int mac_reset(struct cmac *mac)
{
	u32 data32;
	int mac_in_reset, time_out = 100;
	int idx = mac->instance->index;

	data32 = readl(mac->adapter->regs + MAC_REG_CSR(idx));
	writel(data32 | F_MAC_RESET,
	       mac->adapter->regs + MAC_REG_CSR(idx));

	do {
		data32 = readl(mac->adapter->regs + MAC_REG_CSR(idx));

		mac_in_reset = data32 & F_MAC_RESET;
		if (mac_in_reset)
			udelay(1);
	} while (mac_in_reset && --time_out);

	if (mac_in_reset) {
		CH_ERR("%s: MAC %d reset timed out\n",
		       mac->adapter->name, idx);
		return 2;
	}

	return 0;
}

static int mac_set_rx_mode(struct cmac *mac, struct t1_rx_mode *rm)
{
	u32 val;

	val = readl(mac->adapter->regs
			    + MAC_REG_CSR(mac->instance->index));
	val &= ~(F_MAC_PROMISC | F_MAC_MC_ENABLE);
	val |= V_MAC_PROMISC(t1_rx_mode_promisc(rm) != 0);
	val |= V_MAC_MC_ENABLE(t1_rx_mode_allmulti(rm) != 0);
	writel(val,
	       mac->adapter->regs + MAC_REG_CSR(mac->instance->index));

	return 0;
}

static int mac_set_speed_duplex_fc(struct cmac *mac, int speed, int duplex,
				   int fc)
{
	u32 data32;

	data32 = readl(mac->adapter->regs
			       + MAC_REG_CSR(mac->instance->index));
	data32 &= ~(F_MAC_HALF_DUPLEX | V_MAC_SPEED(M_MAC_SPEED) |
		V_INTERFACE(M_INTERFACE) | F_MAC_TX_PAUSE_ENABLE |
		F_MAC_RX_PAUSE_ENABLE);

	switch (speed) {
	case SPEED_10:
	case SPEED_100:
		data32 |= V_INTERFACE(MAC_CSR_INTERFACE_MII);
		data32 |= V_MAC_SPEED(speed == SPEED_10 ? 0 : 1);
		break;
	case SPEED_1000:
		data32 |= V_INTERFACE(MAC_CSR_INTERFACE_GMII);
		data32 |= V_MAC_SPEED(2);
		break;
	}

	if (duplex >= 0)
		data32 |= V_MAC_HALF_DUPLEX(duplex == DUPLEX_HALF);

	if (fc >= 0) {
		data32 |= V_MAC_RX_PAUSE_ENABLE((fc & PAUSE_RX) != 0);
		data32 |= V_MAC_TX_PAUSE_ENABLE((fc & PAUSE_TX) != 0);
	}

	writel(data32,
	       mac->adapter->regs + MAC_REG_CSR(mac->instance->index));
	return 0;
}

static int mac_enable(struct cmac *mac, int which)
{
	u32 val;

	val = readl(mac->adapter->regs
			    + MAC_REG_CSR(mac->instance->index));
	if (which & MAC_DIRECTION_RX)
		val |= F_MAC_RX_ENABLE;
	if (which & MAC_DIRECTION_TX)
		val |= F_MAC_TX_ENABLE;
	writel(val,
	       mac->adapter->regs + MAC_REG_CSR(mac->instance->index));
	return 0;
}

static int mac_disable(struct cmac *mac, int which)
{
	u32 val;

	val = readl(mac->adapter->regs
			    + MAC_REG_CSR(mac->instance->index));
	if (which & MAC_DIRECTION_RX)
		val &= ~F_MAC_RX_ENABLE;
	if (which & MAC_DIRECTION_TX)
		val &= ~F_MAC_TX_ENABLE;
	writel(val,
	       mac->adapter->regs + MAC_REG_CSR(mac->instance->index));
	return 0;
}

#if 0
static int mac_set_ifs(struct cmac *mac, u32 mode)
{
	t1_write_reg_4(mac->adapter,
		       MAC_REG_IFS(mac->instance->index),
		       mode);
	return 0;
}

static int mac_enable_isl(struct cmac *mac)
{
	u32 data32 = readl(mac->adapter->regs
				   + MAC_REG_CSR(mac->instance->index));
	data32 |= F_MAC_RX_ENABLE | F_MAC_TX_ENABLE;
	t1_write_reg_4(mac->adapter,
		       MAC_REG_CSR(mac->instance->index),
		       data32);
	return 0;
}
#endif

static int mac_set_mtu(struct cmac *mac, int mtu)
{
	if (mtu > 9600)
		return -EINVAL;
	writel(mtu + ETH_HLEN + VLAN_HLEN,
	       mac->adapter->regs + MAC_REG_LARGEFRAMELENGTH(mac->instance->index));

	return 0;
}

static const struct cmac_statistics *mac_update_statistics(struct cmac *mac,
							   int flag)
{
	struct mac_statistics st;
	u32 *p = (u32 *) & st, i;

	writel(0,
	       mac->adapter->regs + MAC_REG_RMCNT(mac->instance->index));

	for (i = 0; i < sizeof(st) / sizeof(u32); i++)
		*p++ = readl(mac->adapter->regs
			     + MAC_REG_RMDATA(mac->instance->index));

	/* XXX convert stats */
	return &mac->stats;
}

static void mac_destroy(struct cmac *mac)
{
	kfree(mac);
}

static struct cmac_ops chelsio_mac_ops = {
	.destroy                 = mac_destroy,
	.reset                   = mac_reset,
	.interrupt_enable        = mac_intr_enable,
	.interrupt_disable       = mac_intr_disable,
	.interrupt_clear         = mac_intr_clear,
	.enable                  = mac_enable,
	.disable                 = mac_disable,
	.set_mtu                 = mac_set_mtu,
	.set_rx_mode             = mac_set_rx_mode,
	.set_speed_duplex_fc     = mac_set_speed_duplex_fc,
	.macaddress_get          = mac_get_address,
	.statistics_update       = mac_update_statistics,
};

static struct cmac *mac_create(adapter_t *adapter, int index)
{
	struct cmac *mac;
	u32 data32;

	if (index >= 4)
		return NULL;

	mac = kzalloc(sizeof(*mac) + sizeof(cmac_instance), GFP_KERNEL);
	if (!mac)
		return NULL;

	mac->ops = &chelsio_mac_ops;
	mac->instance = (cmac_instance *) (mac + 1);

	mac->instance->index = index;
	mac->adapter = adapter;

	data32 = readl(adapter->regs + MAC_REG_CSR(mac->instance->index));
	data32 &= ~(F_MAC_RESET | F_MAC_PROMISC | F_MAC_PROMISC |
		    F_MAC_LB_ENABLE | F_MAC_RX_ENABLE | F_MAC_TX_ENABLE);
	data32 |= F_MAC_JUMBO_ENABLE;
	writel(data32, adapter->regs + MAC_REG_CSR(mac->instance->index));

	/* Initialize the random backoff seed. */
	data32 = 0x55aa + (3 * index);
	writel(data32,
	       adapter->regs + MAC_REG_GMRANDBACKOFFSEED(mac->instance->index));

	/* Check to see if the mac address needs to be set manually. */
	data32 = readl(adapter->regs + MAC_REG_IDLO(mac->instance->index));
	if (data32 == 0 || data32 == 0xffffffff) {
		/*
		 * Add a default MAC address if we can't read one.
		 */
		writel(0x43FFFFFF - index,
		       adapter->regs + MAC_REG_IDLO(mac->instance->index));
		writel(0x0007,
		       adapter->regs + MAC_REG_IDHI(mac->instance->index));
	}

	(void) mac_set_mtu(mac, 1500);
	return mac;
}

struct gmac t1_chelsio_mac_ops = {
	.create = mac_create
};


text:
EXPMatcherImplementationBegin(_containAll, (id expected)) {
  BOOL actualIsCompatible = [actual isKindOfClass:[NSString class]] || [actual conformsToProtocol:@protocol(NSFastEnumeration)];
  BOOL expectedIsCompatible = [expected isKindOfClass:[NSString class]] || [expected conformsToProtocol:@protocol(NSFastEnumeration)];
  BOOL expectedIsNil = (expected == nil);

  prerequisite(^BOOL{
    return actualIsCompatible && expectedIsCompatible && !expectedIsNil;
  });

  match(^BOOL{
    if(actualIsCompatible && expectedIsCompatible) {
      if([actual isKindOfClass:[NSString class]]) {
        return [(NSString *)actual rangeOfString:[expected description]].location != NSNotFound;
      } else {
          for (id object in expected) {
              if (![actual containsObject:object]) return NO;
          }
          return YES;
      }
    }
    return NO;
  });

  failureMessageForTo(^NSString *{
    if(!actualIsCompatible) return [NSString stringWithFormat:@"%@ is not an instance of NSString or NSFastEnumeration", EXPDescribeObject(actual)];
    if(!expectedIsCompatible) return [NSString stringWithFormat:@"%@ is not an instance of NSString or NSFastEnumeration", EXPDescribeObject(expected)];
    if(expectedIsNil) return @"the expected value is nil/null";
    return [NSString stringWithFormat:@"expected %@ to contain %@", EXPDescribeObject(actual), EXPDescribeObject(expected)];
  });

  failureMessageForNotTo(^NSString *{
    if(!actualIsCompatible) return [NSString stringWithFormat:@"%@ is not an instance of NSString or NSFastEnumeration", EXPDescribeObject(actual)];
    if(!expectedIsCompatible) return [NSString stringWithFormat:@"%@ is not an instance of NSString or NSFastEnumeration", EXPDescribeObject(expected)];
    if(expectedIsNil) return @"the expected value is nil/null";
    return [NSString stringWithFormat:@"expected %@ not to contain %@", EXPDescribeObject(actual), EXPDescribeObject(expected)];
  });
}
EXPMatcherImplementationEnd

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<config>
	<processInMemory>true</processInMemory>
	<defaultTermLangCode>es</defaultTermLangCode>
	<defaultTermDescriptionType>900000000000003001</defaultTermDescriptionType>
	<defaultTermLanguageRefset>5641000179103</defaultTermLanguageRefset>
	<normalizeTextIndex>true</normalizeTextIndex>
	<createCompleteConceptsFile>false</createCompleteConceptsFile>
	<editionName>UY edition</editionName>
	<databaseName>uy-edition</databaseName>
	<effectiveTime>20171215</effectiveTime>
    <expirationTime>20191002</expirationTime>
    <outputFolder>uy-edition</outputFolder>
    <foldersBaselineLoad>
		<folder><PATH_TO_UNZIPPED_EDITION_RELEASE_FILES>/Snapshot</folder>
	</foldersBaselineLoad>
	<modulesToIgnoreBaselineLoad></modulesToIgnoreBaselineLoad>
	<foldersExtensionLoad></foldersExtensionLoad>
	<modulesToIgnoreExtensionLoad></modulesToIgnoreExtensionLoad>
</config>


text:
use x86_64::VirtAddr;

use super::prelude::*;

mod allocator;

/// Allocate a contiguous virtual address block
pub fn allocate(size_pages: usize) -> Allocation {
    let start = allocator::allocate(size_pages as u64);
    Allocation {
        start,
        end: start + size_pages * (PAGE_SIZE_BYTES as usize),
    }
}

/// An owned virtual address space allocation, freed on drop
#[derive(Debug, PartialEq, Eq)]
pub struct Allocation {
    pub start: VirtAddr,
    pub end: VirtAddr,
}

impl Drop for Allocation {
    fn drop(&mut self) {
        allocator::free(self.start, self.size_pages())
    }
}

impl Allocation {
    #[inline]
    pub fn size_bytes(&self) -> u64 {
        self.end.as_u64() - self.start.as_u64()
    }

    #[inline]
    pub fn size_pages(&self) -> u64 {
        self.size_bytes() / PAGE_SIZE_BYTES
    }

    #[inline]
    pub fn page_starts(&self) -> impl Iterator<Item = VirtAddr> {
        (self.start.as_u64()..self.end.as_u64())
            .step_by(PAGE_SIZE_BYTES as usize)
            .map(VirtAddr::new)
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

using Nap.Configuration;
using Nap.Configuration.Sections;
using Nap.Exceptions;
using Nap.Html;
using Xunit;

namespace Nap.Configuration.Tests
{
#if IMMUTABLE
    [Trait("Library", "Nap.Immutable")]
#else
    [Trait("Library", "Nap")]
#endif
    [Trait("Type", "Configuration")]
    public class NapConfigurationTests
    {
        private readonly NapSetup _setup;
        // Tests to ensure that *.config files get parsed correctly.

        public NapConfigurationTests()
        {
            _setup = new NapSetup();
            _setup.InstallPlugin<NapConfigurationPlugin>();
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_DoesNotThrowException()
        {
            var config = new NapClient(_setup);
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_BaseUrl_Matches()
        {
            var nap = new NapClient(_setup);
            Assert.Equal("http://example.com", nap.Config.BaseUrl);
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_Headers_Match()
        {
            var nap = new NapClient(_setup);
            var headers = nap.Config.Headers.AsDictionary();

            // Assert
            Assert.NotNull(headers);
            Assert.Equal(1, headers.Count);
            Assert.Equal("testHeader", headers.First().Key);
            Assert.Equal("testHeaderValue", headers.First().Value);
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_QueryParameters_Match()
        {
            var nap = new NapClient(_setup);
            var queryParameters = nap.Config.QueryParameters.AsDictionary();

            // Assert
            Assert.NotNull(queryParameters);
            Assert.Equal(1, queryParameters.Count);
            Assert.Equal("testQueryParameter", queryParameters.First().Key);
            Assert.Equal("testQueryParameterValue", queryParameters.First().Value);
        }

        [Fact]
        public void AddInvalidHeader_ThrowsConfigurationException()
        {
            Assert.Throws<NapConfigurationException>(() =>
            {
                var nap = new NapClient(_setup);
                var config = nap.Config;
                ((Headers)config.Headers).Add(new EmptyHeader());
            });
        }

        [Fact]
        public void AddInvalidQueryParameter_ThrowsConfigurationException()
        {
            Assert.Throws<NapConfigurationException>(() =>
            {
                var nap = new NapClient(_setup);
                var config = nap.Config;
                ((QueryParameters)config.QueryParameters).Add(new EmptyQueryParameter());
            });
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_Serializers_Match()
        {
            var nap = new NapClient(_setup);
            var serializers = nap.Config.Serializers.AsDictionary();

            // Assert
            Assert.NotNull(serializers);
            Assert.Equal(4, serializers.Count);
            Assert.Equal("text/html", serializers.Last().Key);
            Assert.IsType<NapHtmlSerializer>(serializers.Last().Value);
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_Profile_HasProfile()
        {
            var nap = new NapClient(_setup);
            var config = (NapConfig)nap.Config;

            // Assert
            Assert.True(config.Profiles.Any(), "App.config should have at least one profile");
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_Profile_IsForFoobar()
        {
            var nap = new NapClient(_setup);
            var config = (NapConfig)nap.Config;

            // Assert
            Assert.True(config.Profiles.AsDictionary().ContainsKey("foobar"), "App.config should have a profile for foobar.com");
        }

        [Fact]
        public void GetConfiguration_FromConfigFile_Profile_Foobar_HasValidValues()
        {
            var nap = new NapClient(_setup);
            var config = (NapConfig)nap.Config;
            var profile = config.Profiles.AsDictionary()["foobar"];

            // Assert
            Assert.Equal("http://www.foobar.com", profile.BaseUrl);
            Assert.False(profile.FillMetadata, "Foobar profile should have fillMetadata=false");
            Assert.Equal("Json", profile.Serialization);
            Assert.True(profile.Headers.Any(), "Foobar profile should have at least one header");
            Assert.True(profile.Headers.Any(h => h.Key == "TOKEN"), "Foobar profile should have at least one header with key 'TOKEN'");
            Assert.Equal("LONG_GUID", profile.Headers.First(h => h.Key == "TOKEN").Value);
        }
    }
}


text:
Compute the total invoice amount charged (in the reference currency) per day per currency.

The snapshot view is: `v_report_invoices_daily`

## Timeline configuration

```
curl -v \
     -X POST \
     -u admin:password \
     -H "X-Killbill-ApiKey:bob" \
     -H "X-Killbill-ApiSecret:lazar" \
     -H 'Content-Type: application/json' \
     -d '{"reportName": "report_invoices_daily",
          "reportType": "TIMELINE",
          "reportPrettyName": "Daily invoices value",
          "sourceTableName": "report_invoices_daily",
          "refreshProcedureName": "refresh_report_invoices_daily",
          "refreshFrequency": "DAILY"}' \
     "http://127.0.0.1:8080/plugins/killbill-analytics/reports"
```


text:
<?php

namespace Emizentech\ShopByBrand\Block\Adminhtml\Items;

class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

    /**
     * Initialize form
     * Add standard buttons
     * Add "Save and Continue" button
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_objectId = 'id';
        $this->_controller = 'adminhtml_items';
        $this->_blockGroup = 'Emizentech_ShopByBrand';

        parent::_construct();

        $this->buttonList->add(
            'save_and_continue_edit',
            [
                'class' => 'save',
                'label' => __('Save and Continue Edit'),
                'data_attribute' => [
                    'mage-init' => ['button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form']],
                ]
            ],
            10
        );
    }

    /**
     * Getter for form header text
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
        $item = $this->_coreRegistry->registry('current_emizentech_shopbybrand_items');
        if ($item->getId()) {
            return __("Edit Brand '%1'", $this->escapeHtml($item->getName()));
        } else {
            return __('New Brand');
        }
    }
}


text:
export GITZ_DIR=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

# enable debug mode
if [ "$DEBUG" = "ture" ]; then
	set -x
fi

usage() {
	echo "usage: gitz  <subcommand>"
	echo
	echo "Available subcommands are:"
	echo "   sub      switch/create sub personal branch base on the given branch, base on current branch if no params."
	echo "   super   switch to personal's super branch of current branch"
	echo "   pull   pull from the given branch, from current branch if no params."
	echo "   push   push to current remote branch. It will pull from super branch before push action"
	echo "   request   create a pull request base on current personal's branch."
	echo "   remove   remove both of the local and remote branch of given name."
	echo
	echo "Try 'gitz help <subcommand> help' for details."
}

main() {
	if [ $# -lt 0 ]; then
		usage
		exit 1
	fi

	export POSIXLY_CORRECT=1

	# sanity checks
	SUBCOMMAND="$1"; shift

	if [ ! -e "$GITZ_DIR/gitz-$SUBCOMMAND.sh" ]; then
		usage
		exit 1
	fi

	# run command
	sh "$GITZ_DIR/gitz-$SUBCOMMAND.sh" $*
	FLAGS_PARENT="gitz $SUBCOMMAND"
}

main "$@"


text:
layout: tag
title: 'Tags: Restating the obvious'
tag: obvious
permalink: tags/obvious/
---


text:
package org.motechproject.nms.testing.it.region;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.motechproject.nms.region.domain.District;
import org.motechproject.nms.region.domain.HealthBlock;
import org.motechproject.nms.region.domain.HealthFacility;
import org.motechproject.nms.region.domain.HealthFacilityType;
import org.motechproject.nms.region.domain.HealthSubFacility;
import org.motechproject.nms.region.domain.State;
import org.motechproject.nms.region.domain.Taluka;
import org.motechproject.nms.region.domain.Village;
import org.motechproject.nms.region.repository.DistrictDataService;
import org.motechproject.nms.region.repository.HealthBlockDataService;
import org.motechproject.nms.region.repository.HealthFacilityDataService;
import org.motechproject.nms.region.repository.HealthFacilityTypeDataService;
import org.motechproject.nms.region.repository.HealthSubFacilityDataService;
import org.motechproject.nms.region.repository.StateDataService;
import org.motechproject.nms.region.repository.TalukaDataService;
import org.motechproject.nms.region.repository.VillageDataService;
import org.motechproject.nms.region.service.HealthBlockService;
import org.motechproject.nms.testing.service.TestingService;
import org.motechproject.testing.osgi.BasePaxIT;
import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory;
import org.ops4j.pax.exam.ExamFactory;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerSuite;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.inject.Inject;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
@ExamFactory(MotechNativeTestContainerFactory.class)
public class LocationServiceBundleIT extends BasePaxIT {
    @Inject
    StateDataService stateDataService;

    @Inject
    DistrictDataService districtDataService;

    @Inject
    TalukaDataService talukaDataService;

    @Inject
    VillageDataService villageDataService;

    @Inject
    HealthBlockDataService healthBlockDataService;

    @Inject
    HealthBlockService healthBlockService;

    @Inject
    HealthFacilityTypeDataService healthFacilityTypeDataService;

    @Inject
    HealthFacilityDataService healthFacilityDataService;

    @Inject
    HealthSubFacilityDataService healthSubFacilityDataService;

    @Inject
    TestingService testingService;

    @Inject
    PlatformTransactionManager transactionManager;

    State state;
    District district;
    Taluka taluka;
    Village village;
    HealthBlock healthBlock;
    HealthFacilityType healthFacilityType;
    HealthFacility healthFacility;
    HealthSubFacility healthSubFacility;

    @Before
    public void doTheNeedful() {
        testingService.clearDatabase();

        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());

        healthSubFacility = new HealthSubFacility();
        healthSubFacility.setName("Health Sub Facility 1");
        healthSubFacility.setRegionalName("Health Sub Facility 1");
        healthSubFacility.setCode(1L);

        healthFacilityType = new HealthFacilityType();
        healthFacilityType.setName("Health Facility Type 1");
        healthFacilityType.setCode(1L);

        healthFacility = new HealthFacility();
        healthFacility.setName("Health Facility 1");
        healthFacility.setRegionalName("Health Facility 1");
        healthFacility.setCode(1L);
        healthFacility.setHealthFacilityType(healthFacilityType);
        healthFacility.getHealthSubFacilities().add(healthSubFacility);

        healthBlock = new HealthBlock();
        healthBlock.setName("Health Block 1");
        healthBlock.setRegionalName("Health Block 1");
        healthBlock.setHq("Health Block 1 HQ");
        healthBlock.setCode(1L);
        healthBlock.getHealthFacilities().add(healthFacility);

        village = new Village();
        village.setName("Village 1");
        village.setRegionalName("Village 1");
        village.setVcode(1L);

        taluka = new Taluka();
        taluka.setName("Taluka 1");
        taluka.setRegionalName("Taluka 1");
        taluka.setIdentity(1);
        taluka.setCode("0004");
        taluka.getVillages().add(village);

        //TODO HARITHA commented 2 lines m-n taluka hb
//        taluka.addHealthBlock(healthBlock);
//
//
//        healthBlock.addTaluka(taluka);

        district = new District();
        district.setName("District 1");
        district.setRegionalName("District 1");
        district.setCode(1L);
        district.getTalukas().add(taluka);

        state = new State();
        state.setName("State 1");
        state.setCode(1L);
        state.getDistricts().add(district);
        transactionManager.commit(status);
    }

    @Test(expected = ConstraintViolationException.class)
    public void testCreateStateNoName() throws Exception {
        state.setName(null);

        stateDataService.create(state);
    }

    @Test(expected = ConstraintViolationException.class)
    public void testCreateDistrictNoName() throws Exception {
        district.setName(null);

        districtDataService.create(district);
    }

    @Test(expected = ConstraintViolationException.class)
    public void testCreateTalukaNoName() throws Exception {
        taluka.setName(null);

        talukaDataService.create(taluka);
    }

    @Test(expected = ConstraintViolationException.class)
    public void testCreateVillageNoName() throws Exception {
        village.setName(null);

        // Village is the leaf, I have to create something connected to the object graph so I save the
        // taluka (it's parent) instead
        talukaDataService.create(taluka);
    }

    @Test (expected = ConstraintViolationException.class)
    @Ignore // Remove once https://applab.atlassian.net/browse/MOTECH-1691 is resolved
    public void testCreateVillageNoCode() throws Exception {
        village.setVcode(0);
        village.setSvid(0);

        // Village is the leaf, I have to create something connected to the object graph so I save the
        // taluka (it's parent) instead
        stateDataService.create(state);
    }

    @Test(expected = ConstraintViolationException.class)
    public void testCreateHealthBlockNoName() throws Exception {
        healthBlock.setName(null);

        healthBlockDataService.create(healthBlock);
    }

    @Test(expected = ConstraintViolationException.class)
    public void testCreateHealthFacilityNoName() throws Exception {
        healthFacility.setName(null);

        healthFacilityDataService.create(healthFacility);
    }

    @Test(expected = ConstraintViolationException.class)
    public void testCreateHealthSubFacilityNoName() throws Exception {
        healthSubFacility.setName(null);

        healthSubFacilityDataService.create(healthSubFacility);
    }

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void testDistrictsWithSameCodeDifferentStates() throws Exception {
        stateDataService.create(state);
        districtDataService.create(district);

        State otherState = new State();
        otherState.setName("State 2");
        otherState.setCode(2L);
        stateDataService.create(otherState);

        District otherDistrict = new District();
        otherDistrict.setName("District 2");
        otherDistrict.setRegionalName("District 2");
        otherDistrict.setCode(1L);
        otherDistrict.setState(otherState);
        districtDataService.create(otherDistrict);
    }

    @Test
    public void testDistrictsWithSameCodeSameStates() throws Exception {
        stateDataService.create(state);
        districtDataService.create(district);

        District otherDistrict = new District();
        otherDistrict.setName("District 2");
        otherDistrict.setRegionalName("District 2");
        otherDistrict.setCode(1L);
        otherDistrict.setState(state);

        exception.expect(javax.jdo.JDODataStoreException.class);
        districtDataService.create(otherDistrict);
    }

    @Test
    public void testVillagesWithSameCodeDifferentTalukas() throws Exception {
        stateDataService.create(state);
        districtDataService.create(district);
        talukaDataService.create(taluka);
        villageDataService.create(village);

        Taluka otherTaluka = new Taluka();
        otherTaluka.setName("Taluka 2");
        otherTaluka.setRegionalName("Taluka 2");
        otherTaluka.setDistrict(district);
        otherTaluka.setIdentity(2);
        otherTaluka.setCode("0005");
        talukaDataService.create(otherTaluka);

        Village otherVillage = new Village();
        otherVillage.setName("Village 2");
        otherVillage.setRegionalName("Village 2");
        otherVillage.setVcode(1L);
        otherVillage.setTaluka(otherTaluka);
        villageDataService.create(otherVillage);
    }

    @Test
    public void testVillagesWithSameCodeSameTalukas() throws Exception {
        stateDataService.create(state);
        districtDataService.create(district);
        talukaDataService.create(taluka);
        villageDataService.create(village);

        Village otherVillage = new Village();
        otherVillage.setName("Village 2");
        otherVillage.setRegionalName("Village 2");
        otherVillage.setVcode(1L);
        otherVillage.setTaluka(taluka);
        exception.expect(javax.jdo.JDODataStoreException.class);
        villageDataService.create(otherVillage);
    }

    // Single Taluka Single HB, should find it
    // State -> District -> Taluka -> HealthBlock(1)
    @Ignore //Iest is ignored since there is no direct mapping between Taluka and Health block.
    @Test
    public void testFindHealthBlockByTalukaAndCode1() {
        stateDataService.create(state);
        districtDataService.create(district);
        Taluka t = talukaDataService.create(taluka);
        healthBlockDataService.create(healthBlock);

        HealthBlock hb = healthBlockService.findByTalukaAndCode(t, 1L);
        assertNotNull(hb);
        assertEquals(hb.getCode(), healthBlock.getCode());
    }

    // Multiple, lookup by t(1) and HB(2), should find it
    // State -> District -> Taluka(1) -> HealthBlock(1)
    //                   -> Taluka(2) -> HealthBlock(2)
    @Ignore  //Iest is ignored since there is no direct mapping between Taluka and Health block.
    @Test
    public void testFindHealthBlockByTalukaAndCode2() {
        stateDataService.create(state);
        district = districtDataService.create(district);
        Taluka t = talukaDataService.create(taluka);
        healthBlockDataService.create(healthBlock);

        HealthBlock healthBlock2 = new HealthBlock();
        healthBlock2.setName("Health Block 2");
        healthBlock2.setRegionalName("Health Block 2");
        healthBlock2.setHq("Health Block 2 HQ");
        healthBlock2.setCode(2L);

        Taluka taluka2 = new Taluka();
        taluka2.setName("Taluka 2");
        taluka2.setRegionalName("Taluka 2");
        taluka2.setIdentity(2);
        taluka2.setCode("0005");
        taluka2.setDistrict(district);
        //TODO HARITHA commented 2 lines m-n taluka hb
        //taluka2.addHealthBlock(healthBlock2);

        taluka2 = talukaDataService.create(taluka2);
        healthBlockDataService.create(healthBlock2);

        HealthBlock hb = healthBlockService.findByTalukaAndCode(t, 2L);
        assertNotNull(hb);
        assertEquals(hb.getCode(), healthBlock2.getCode());

        hb = healthBlockService.findByTalukaAndCode(t, 1L);
        assertNotNull(hb);
        assertEquals(hb.getCode(), healthBlock.getCode());

        hb = healthBlockService.findByTalukaAndCode(taluka2, 1L);
        assertNotNull(hb);
        assertEquals(hb.getCode(), healthBlock.getCode());

        hb = healthBlockService.findByTalukaAndCode(taluka2, 2L);
        assertNotNull(hb);
        assertEquals(hb.getCode(), healthBlock2.getCode());
    }

    // Two HB in Single Taluka, lookup by t(1) hb(1), should find it
    // State -> District -> Taluka -> HealthBlock(1)
    //                             -> HealthBlock(2)
    @Ignore  //Iest is ignored since there is no direct mapping between Taluka and Health block.
    @Test
    public void testFindHealthBlockByTalukaAndCode3() {
        stateDataService.create(state);
        districtDataService.create(district);
        Taluka t = talukaDataService.create(taluka);
        healthBlockDataService.create(healthBlock);

        HealthBlock healthBlock2 = new HealthBlock();
        healthBlock2.setName("Health Block 2");
        healthBlock2.setRegionalName("Health Block 2");
        healthBlock2.setHq("Health Block 2 HQ");
        healthBlock2.setCode(2L);
        //TODO HARITHA commented 2 lines m-n taluka hb
        //healthBlock2.addTaluka(t);

        healthBlockDataService.create(healthBlock2);

        HealthBlock hb = healthBlockService.findByTalukaAndCode(t, 1L);
        assertNotNull(hb);
        assertEquals(hb.getCode(), healthBlock.getCode());

        hb = healthBlockService.findByTalukaAndCode(t, 2L);
        assertNotNull(hb);
        assertEquals(hb.getCode(), healthBlock2.getCode());
    }
    // Multiple, lookup by t(1), hb(2) should not find it
    // State(1) -> District -> Taluka(1) -> HealthBlock(1)
    // State(2) -> District -> Taluka(2) -> HealthBlock(2)
    @Ignore  //Iest is ignored since there is no direct mapping between Taluka and Health block.
    @Test
    public void testFindHealthBlockByTalukaAndCode4() {
        stateDataService.create(state);
        districtDataService.create(district);
        Taluka t = talukaDataService.create(taluka);
        healthBlockDataService.create(healthBlock);

        HealthBlock healthBlock2 = new HealthBlock();
        healthBlock2.setName("Health Block 2");
        healthBlock2.setRegionalName("Health Block 2");
        healthBlock2.setHq("Health Block 2 HQ");
        healthBlock2.setCode(2L);

        Taluka taluka2 = new Taluka();
        taluka2.setName("Taluka 2");
        taluka2.setRegionalName("Taluka 2");
        taluka2.setIdentity(2);
        taluka2.setCode("0005");
        //TODO HARITHA commented 2 lines m-n taluka hb
        //taluka2.addHealthBlock(healthBlock2);

        District district2 = new District();
        district2.setName("District 2");
        district2.setRegionalName("District 2");
        district2.setCode(2L);
        district2.getTalukas().add(taluka2);

        State state2 = new State();
        state2.setName("State 2");
        state2.setCode(2L);
        state2.getDistricts().add(district2);

        stateDataService.create(state2);
        districtDataService.create(district2);
        Taluka t2 = talukaDataService.create(taluka2);
        healthBlockDataService.create(healthBlock2);

        HealthBlock hb = healthBlockService.findByTalukaAndCode(t, 2L);
        assertNull(hb);

        hb = healthBlockService.findByTalukaAndCode(t2, 1L);
        assertNull(hb);
    }

    @Test
    @Ignore // TODO: Remove once https://applab.atlassian.net/browse/MOTECH-1678 is resolved
    public void testValidCreate() throws Exception {
        stateDataService.create(state);

        State newState = stateDataService.findByCode(1L);
        assertNotNull(newState);
        Assert.assertEquals(state, newState);

        Set<District> districtList = newState.getDistricts();
        assertEquals(1, districtList.size());
        assertTrue(districtList.contains(district));

        List<Taluka> talukaList = districtList.iterator().next().getTalukas();
        assertEquals(1, talukaList.size());
        assertTrue(talukaList.contains(taluka));

        List<Village> villageList = talukaList.get(0).getVillages();
        assertEquals(1, villageList.size());
        assertTrue(villageList.contains(village));

        //TODO HARITHA commented 2 lines m-n taluka hb
        //Set<HealthBlock> healthBlockList = talukaList.get(0).getHealthBlocks();
//        assertEquals(1, healthBlockList.size());
//        assertTrue(healthBlockList.contains(healthBlock));

//        List<HealthFacility> healthFacilityList = healthBlockList.iterator().next().getHealthFacilities();
//        assertEquals(1, healthFacilityList.size());
//        Assert.assertEquals(healthFacilityType, healthFacilityList.get(0).getHealthFacilityType());
//        assertTrue(healthFacilityList.contains(healthFacility));

//        List<HealthSubFacility> healthSubFacilityList = healthFacilityList.get(0).getHealthSubFacilities();
//        assertEquals(1, healthSubFacilityList.size());
//        assertTrue(healthSubFacilityList.contains(healthSubFacility));
    }
}


text:
<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\App;
use Pingpong\Admin\Controllers\BaseController;

class WidgetMenusController extends BaseController {

    public function __construct() {
        $this->repository = $this->getRepository();
    }

    /**
     * Get repository instance.
     *
     * @return mixed
     */
    public function getRepository() {
        $repository = 'Modules\Admin\Repositories\WidgetMenu\WidgetMenuRepository';
        return app($repository);
    }

    /**
     * Remove the specified Tag from storage.
     *
     * @param int $id
     *
     * @return Response
     */
    public function destroy($id) {
        try {
            $this->repository->delete($id);
            return true;
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        }
    }

    /**
     * Add the specified menu in storage.

     * @param string $menu
     *
     * @return Response
     */
    public function linkMenuWithWidget($widgetID, $menuID) {
        try {
            return $this->repository->linkMenuWithWidget($widgetID, $menuID);
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        }
    }

    /**
     * Get all the menus for the specified widget from storage.
     *
     * @param int $widgetID
     *
     * @return Response
     */
    public function getAllMenus($widgetID) {
        try {

            $menus = $this->repository->getAllMenus($widgetID);
            return $menus;
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        }
    }

    /**
     * Remove all the menus of a partcular widget.
     *
     * @param int $widgetID
     *
     * @param string $menu
     *
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function removeAllMenus($widgetID) {
        try {
            $this->repository->removeAllMenus($widgetID);
            return true;
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        }
    }

}


text:
{
    matrix_id: '632',
    name: 'lp_grow15',
    group: 'LPnetlib',
    description: 'Netlib LP problem grow15: minimize c\'*x, where Ax=b, lo<=x<=hi',
    author: 'R. Fourer',
    editor: 'R. Fourer',
    date: '1983',
    kind: 'linear programming problem',
    problem_2D_or_3D: '0',
    num_rows: '300',
    num_cols: '645',
    nonzeros: '5620',
    num_explicit_zeros: '0',
    num_strongly_connected_components: '1',
    num_dmperm_blocks: '1',
    structural_full_rank: 'true',
    structural_rank: '300',
    pattern_symmetry: '0.000',
    numeric_symmetry: '0.000',
    rb_type: 'real',
    structure: 'rectangular',
    cholesky_candidate: 'no',
    positive_definite: 'no',
    notes: 'A Netlib LP problem, in lp/data.  For more information
send email to netlib@ornl.gov with the message:

	 send index from lp
	 send readme from lp/data

The following are relevant excerpts from lp/data/readme (by David M. Gay):

The column and nonzero counts in the PROBLEM SUMMARY TABLE below exclude
slack and surplus columns and the right-hand side vector, but include
the cost row.  We have omitted other free rows and all but the first
right-hand side vector, as noted below.  The byte count is for the
MPS compressed file; it includes a newline character at the end of each
line.  These files start with a blank initial line intended to prevent
mail programs from discarding any of the data.  The BR column indicates
whether a problem has bounds or ranges:  B stands for "has bounds", R
for "has ranges".  The BOUND-TYPE TABLE below shows the bound types
present in those problems that have bounds.

The optimal value is from MINOS version 5.3 (of Sept. 1988)
running on a VAX with default options.

                       PROBLEM SUMMARY TABLE

Name       Rows   Cols   Nonzeros    Bytes  BR      Optimal Value
GROW15      301    645     5665      35041  B    -1.0687094129E+08

        BOUND-TYPE TABLE
GROW15     UP

Supplied by Bob Fourer.
When included in Netlib: Extra bound sets omitted; explicit zeros
omitted; Cost coefficients negated.

Source:   GROW15, GROW22, GROW7: R. Fourer, "Solving Staircase Linear
Programs by the Simplex Method, 2: Pricing", Math. Prog. 25 (1983),
pp. 251-292.

',
    b_field: 'full 300-by-1
',
    aux_fields: 'c: full 645-by-1
lo: full 645-by-1
hi: full 645-by-1
z0: full 1-by-1
',    norm: '2.509998e+00',
    min_singular_value: '4.435223e-01',
    condition_number: '5.659238e+00',
    svd_rank: '300',
    sprank_minus_rank: '0',
    null_space_dimension: '0',
    full_numerical_rank: 'yes',
    image_files: 'lp_grow15.png,lp_grow15_svd.png,lp_grow15_graph.gif,',
}


text:
(function () {
  'use strict';

  angular
    .module('crowdsource.project.controllers')
    .controller('ViewTemplateCtrl', ViewTemplateCtrl);

  ViewTemplateCtrl.$inject = ['$scope', 'FormService', '$routeParams'];

  /**
  * @namespace ViewTemplateCtrl
  */
  function ViewTemplateCtrl ($scope, FormService, $routeParams) {
      $scope.form = {};
    // read form with given id
    FormService.form($routeParams.id).then(function(form) {
      $scope.form = form;
    });
  }

})();


text:
var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy
    , constants = require('../lib/constants.js');

exports.getLogin = function (req, res) {
    res.render('login', { user: req.user});
};

exports.getLogout = function (req, res) {
    req.logout();
    res.redirect('/');
};

/*
 POST of /login
 Use passport.authenticate() as route middleware to authenticate the
 request. If authentication fails, the user will be redirected back to the
 login page. Othewise, the primary route function will be called.
 In this example, it will redirect the user to the home page.
 */

// THIS MAY NOT WORK AT ALL, BECAUSE WE MIGHT BE CONFUSING PASSPORT WITH A REQUIRE IN HERE TOO

exports.postLogin = function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        console.log('app.post.login.passport.authenticate : Enter');
        // General error?
        if (err) {
            console.log('Passport authenticate : General error.');
            return next(err);
        }

        // User not found? Flash the message and return to /login
        if (!user) {
            console.log('Passport authenticate : User not found.');
            return res.redirect(constants.LOGINROUTE);
        }

        // No errors detected, so perform the login
        req.logIn(user, function (err) {
            console.log('Passport authenticate : Performing login.');
            if (err) {
                console.log('Passport authenticate : Error detected.');
                return next(err);
            }
            // Redirect to the welcome page, with the authentication information intact
            console.log('Passport authenticate : It worked. Redirecting to /');
            return res.redirect('/');
        });
    })(req, res, next);
};


text:
using System.Collections.Generic;

namespace CountWordsInLargeText.Trie
{
    internal class TrieNode
    {
        internal TrieNode(char character, IDictionary<char, TrieNode> children, int wordCount, TrieNode parent)
        {
            this.Character = character;
            this.Children = children;
            this.WordCount = wordCount;
            this.Parent = parent;
        }

        internal char Character { get; private set; }

        internal IDictionary<char, TrieNode> Children { get; set; }

        internal bool IsWord
        {
            get { return this.WordCount > 0; }
        }

        internal int WordCount { get; set; }

        internal TrieNode Parent { get; private set; }

        public override string ToString()
        {
            return this.Character.ToString();
        }

        public override bool Equals(object obj)
        {
            TrieNode that;
            return
                obj != null
                && (that = obj as TrieNode) != null
                && that.Character == this.Character;
        }

        public override int GetHashCode()
        {
            return this.Character.GetHashCode();
        }

        internal IEnumerable<TrieNode> GetChildren()
        {
            return this.Children.Values;
        }

        internal TrieNode GetChild(char character)
        {
            TrieNode trieNode;
            this.Children.TryGetValue(character, out trieNode);
            return trieNode;
        }

        internal void SetChild(TrieNode child)
        {
            this.Children[child.Character] = child;
        }

        internal void RemoveNode(TrieNode rootTrieNode)
        {
            // set this node's word count to 0
            this.WordCount = 0;
            this.RemoveNode_Recursive(rootTrieNode);
        }

        internal void Clear()
        {
            this.WordCount = 0;
            this.Children.Clear();
        }

        private void RemoveChild(char character)
        {
            this.Children.Remove(character);
        }

        private void RemoveNode_Recursive(TrieNode rootTrieNode)
        {
            if (this.Children.Count == 0 && !this.IsWord && this != rootTrieNode)
            {
                var parent = this.Parent;
                this.Parent.RemoveChild(this.Character);
                this.Parent = null;
                parent.RemoveNode_Recursive(rootTrieNode);
            }
        }
    }
}


text:
import newspaper
import datetime

URL = 'http://www.reuters.com/news/archive/worldNews?date='

def getPaper(date):
    URL = 'http://www.reuters.com/news/archive/worldNews?date='
    URL = URL + str(date)
    print(URL)
    paper = newspaper.build(URL)
    print(paper)
    articles_ = paper.articles
    print(articles_)
    i=0
    acticles_[i].download()
    articles_[i].parse()
    articles_   [i].nlp()
    print(articles[i].keywords)


text:
package de.kisi.android;

import android.app.Application;
import android.content.pm.PackageManager.NameNotFoundException;
import de.kisi.android.api.QuickBloxApi;
import de.kisi.android.vicinity.manager.GeofenceManager;

public class KisiApplication extends Application {

	private static KisiApplication instance;
	/**
	 * Retuns a valid Context object
	 */
	public static KisiApplication getInstance() {
		return instance;
	}

	/**
	 * @return Returns the version name specified in the manifest file
	 */
	public String getVersion() throws NameNotFoundException {
		String versionName = (this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
		return versionName;
	}

	/**
	 * @return Returns the version code specified in the manifest file
	 */
	public int getVersionCode() {
		try {
			return getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			return 0;
		}
	}

	/**
	 * This is the first method called by Android.
	 * Here we use all the initialization of the different
	 * Manager that have to start right before everything else.
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		// This have to be the first call.
		// Every Manager who needs a Context object uses the method
		// getApplicationInstance()
		instance = this;
		// Start GeofenceManager for registering all Geofences
		GeofenceManager.getInstance();
		// Bluetooth gets triggered by Geofences
		// So far the BLE Framework requires a lot of Power
		// Only run BLE when it is realy required
		//BluetoothLEManager.getInstance().startService(false);

		// Initiate the Quickblox API.
		QuickBloxApi.getInstance();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		de.kisi.android.db.DataManager.getInstance().close();
	}
}


text:
package org.apache.camel.component.hbase;

import org.apache.camel.spring.SpringCamelContext;
import org.apache.hadoop.hbase.TableExistsException;
import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HBaseSpringConsumerTest extends HBaseConsumerTest {

    private AbstractApplicationContext applicationContext;

    @Override
    @Before
    public void setUp() throws Exception {
        if (systemReady) {
            try {
                hbaseUtil.createTable(HBaseHelper.getHBaseFieldAsBytes(PERSON_TABLE), families);
            } catch (TableExistsException ex) {
                //Ignore if table exists
            }
            applicationContext = createApplicationContext();
            context = SpringCamelContext.springCamelContext(applicationContext);
        }
    }

    @Override
    @After
    public void tearDown() throws Exception {
        if (systemReady) {
            super.tearDown();
            if (applicationContext != null) {
                applicationContext.destroy();
            }
        }
    }

    public AbstractApplicationContext createApplicationContext() throws Exception {
        return new ClassPathXmlApplicationContext("/consumer.xml");
    }

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }
}


text:
using System;

namespace TestNS
{
	public class TestCase
	{
		public static int Compare<T> (T[] array1, T[] array2)
		{
			return 0;
		}

		public static void DoSomething<T> (Func<T, T, int> fn)
		{
			Console.WriteLine (fn (default (T), default (T)));
		}

		public static int Main ()
		{
			DoSomething<byte[]> (TestCase.Compare);
			return 0;
		}
	}
}


text:
package org.spincast.tests.websocket;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.junit.Test;
import org.spincast.core.exchange.DefaultRequestContext;
import org.spincast.core.server.Server;
import org.spincast.core.websocket.DefaultWebsocketContext;
import org.spincast.core.websocket.WebsocketConnectionConfig;
import org.spincast.core.websocket.WebsocketEndpointManager;
import org.spincast.plugins.httpclient.websocket.WebsocketClientWriter;
import org.spincast.shaded.org.apache.commons.lang3.RandomUtils;
import org.spincast.testing.defaults.NoAppWebsocketTestingBase;
import org.spincast.testing.junitrunner.RepeatUntilSuccess;
import org.spincast.tests.varia.DefaultWebsocketControllerTest;
import org.spincast.tests.varia.WebsocketClientTest;

import com.google.common.collect.Sets;

public class LoadTest extends NoAppWebsocketTestingBase {

    protected final int nbrWebsocketControllers = 3;
    protected final int nbrEndpointByController = 3;
    protected final int nbrPeerByEndpoint = 15; // at least 4 for some tests

    protected final Map<String, Controller> controllers = new HashMap<String, Controller>();
    protected final Map<String, Controller> controllersByEndpointId = new HashMap<String, Controller>();

    protected final Map<String, Peer> peers = new HashMap<String, Peer>();
    protected final Map<String, Set<Peer>> peersByEndpointId = new HashMap<String, Set<Peer>>();

    protected int getNbrWebsocketControllers() {
        return this.nbrWebsocketControllers;
    }

    protected int getNbrEndpointByController() {
        return this.nbrEndpointByController;
    }

    protected int getNbrPeerByEndpoint() {
        return this.nbrPeerByEndpoint;
    }

    protected Map<String, Controller> getControllers() {
        return this.controllers;
    }

    protected Controller getController(String controllerId) {
        return getControllers().get(controllerId);
    }

    protected Map<String, Controller> getControllersByEndpointId() {
        return this.controllersByEndpointId;
    }

    protected Controller getControllerByEndpointId(String endpointId) {
        return getControllersByEndpointId().get(endpointId);
    }

    protected Map<String, Set<Peer>> getPeersByEndpointId() {
        return this.peersByEndpointId;
    }

    protected Set<Peer> getPeersByEndpointId(String endpointId) {

        Set<Peer> peers = getPeersByEndpointId().get(endpointId);
        if (peers == null) {
            peers = new HashSet<LoadTest.Peer>();
            getPeersByEndpointId().put(endpointId, peers);
        }
        return peers;
    }

    protected Map<String, Peer> getPeers() {
        return this.peers;
    }

    protected Peer getPeer(String peerId) {
        return getPeers().get(peerId);
    }

    protected class Controller extends DefaultWebsocketControllerTest {

        public Controller(Server server) {
            super(server);
        }

        @Override
        public void onPeerMessage(DefaultWebsocketContext context, String message) {

            //==========================================
            // Validates that this message has not already been received.
            //==========================================
            assertFalse(hasReceivedStringMessage(message));

            super.onPeerMessage(context, message);
        }
    }

    protected class Peer extends WebsocketClientTest {

        private final String controllerId;
        private final String endpointId;
        private WebsocketClientWriter writer;
        private final String peerId;

        public Peer(String controllerId, String endpointId, String peerId) {
            this.controllerId = controllerId;
            this.endpointId = endpointId;
            this.peerId = peerId;
        }

        public String getControllerId() {
            return this.controllerId;
        }

        public String getEndpointId() {
            return this.endpointId;
        }

        public String getPeerId() {
            return this.peerId;
        }

        public WebsocketClientWriter getWriter() {
            return this.writer;
        }

        public void setWriter(WebsocketClientWriter writer) {
            this.writer = writer;
        }

        @Override
        public void onEndpointMessage(String message) {

            //==========================================
            // Validates that this message has not already been received.
            //==========================================
            assertFalse(hasReceivedStringMessage(message));

            super.onEndpointMessage(message);
        }
    }

    protected String createControllerId(int controllerPos) {
        return "controller_" + controllerPos;
    }

    protected String createEndpointId(int controllerPos, int endpointPos) {
        return "endpoint_" + controllerPos + "_" + endpointPos;
    }

    protected String createPeerId(int controllerPos, int endpointPos, int peerPos) {
        return "peer_" + controllerPos + "_" + endpointPos + "_" + peerPos;
    }

    protected void createControllers() {

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

            final int controllerPos = i + 1;
            Controller controller = new Controller(getServer()) {

                @Override
                public WebsocketConnectionConfig onPeerPreConnect(DefaultRequestContext context) {

                    //==========================================
                    // We specify the endpointId and peerId to use by coookie,
                    // so the calling code can control them.
                    //==========================================
                    final String endpointIdCookie = context.request().getCookieValue("endpointId");
                    assertNotNull(endpointIdCookie);

                    final String peerIdCookie = context.request().getCookieValue("peerId");
                    assertNotNull(peerIdCookie);

                    return new WebsocketConnectionConfig() {

                        @Override
                        public String getEndpointId() {
                            return endpointIdCookie;
                        }

                        @Override
                        public String getPeerId() {
                            return peerIdCookie;
                        }
                    };
                }

                @Override
                public void onPeerMessage(DefaultWebsocketContext context, String message) {
                    super.onPeerMessage(context, message);

                    if (message.startsWith("echoall_")) {
                        getEndpointManager(context.getEndpointId()).sendMessage("echo all " + message);
                    } else if (message.startsWith("echo_")) {
                        context.sendMessageToCurrentPeer("echo " + message);
                    } else if (message.startsWith("echoexcept_")) {
                        getEndpointManager(context.getEndpointId()).sendMessageExcept(context.getPeerId(),
                                                                                "echo except " + message);
                    }
                }

            };
            getControllers().put(createControllerId(controllerPos), controller);
            getRouter().websocket("/ws" + controllerPos).handle(controller);
        }
    }

    protected void connectPeers() {

        //==========================================
        // For each controller
        //==========================================
        for (int controllerPos = 1; controllerPos <= getNbrWebsocketControllers(); controllerPos++) {

            String controllerId = createControllerId(controllerPos);
            Controller controller = getController(controllerId);
            assertNotNull(controller);

            //==========================================
            // The endpoints to create by controller
            //==========================================
            for (int endpointPos = 1; endpointPos <= getNbrEndpointByController(); endpointPos++) {

                String endpointId = createEndpointId(controllerPos, endpointPos);

                //==========================================
                // The peers to create for each endpoint
                //==========================================
                for (int peerPos = 1; peerPos <= getNbrPeerByEndpoint(); peerPos++) {

                    String peerId = createPeerId(controllerPos, endpointPos, peerPos);

                    Peer peer = new Peer(controllerId, endpointId, peerId);
                    WebsocketClientWriter writer =
                            websocket("/ws" + controllerPos).disableSslCertificateErrors()
                                                            .setCookie("endpointId", endpointId)
                                                            .setCookie("peerId", peerId)
                                                            .connect(peer);
                    assertNotNull(writer);
                    peer.setWriter(writer);

                    getPeers().put(peerId, peer);
                    getPeersByEndpointId(endpointId).add(peer);
                }

                getControllersByEndpointId().put(endpointId, controller);
            }
        }
    }

    protected Peer getRandomPeer() {
        int controllerPos = RandomUtils.nextInt(1, getNbrWebsocketControllers() + 1);
        int endpointPos = RandomUtils.nextInt(1, getNbrEndpointByController() + 1);
        int peerPos = RandomUtils.nextInt(1, getNbrPeerByEndpoint() + 1);

        String peerId = createPeerId(controllerPos, endpointPos, peerPos);

        return getPeer(peerId);
    }

    protected String getRandomEndpointId() {
        int controllerPos = RandomUtils.nextInt(1, getNbrWebsocketControllers() + 1);
        int endpointPos = RandomUtils.nextInt(1, getNbrEndpointByController() + 1);

        String endpointId = createEndpointId(controllerPos, endpointPos);

        return endpointId;
    }

    protected void validateMessageNotReceivedByEndpointsAndPeersExcept(String endpointIdExcept, HashSet<String> messages) {

        Map<String, Controller> controllers = getControllersByEndpointId();
        for (Entry<String, Controller> entry : controllers.entrySet()) {

            String endpointId = entry.getKey();
            if (endpointIdExcept.equals(endpointId)) {
                continue;
            }

            Controller controller = entry.getValue();
            assertTrue(Collections.disjoint(messages, controller.getStringMessageReceived(endpointId)));

            Set<Peer> peers = getPeersByEndpointId(endpointId);
            for (Peer peer : peers) {
                assertTrue(Collections.disjoint(messages, peer.getStringMessageReceived()));
            }
        }
    }

    @Test
    @RepeatUntilSuccess(value = 5, sleep = 1000)
    public void loadTest() throws Exception {

        //==========================================
        // Creates Websocket routes
        //==========================================
        createControllers();

        //==========================================
        // Connect peers
        //==========================================
        connectPeers();

        //==========================================
        // Validate all peers are connected
        //==========================================
        for (int controllerPos = 1; controllerPos <= getNbrWebsocketControllers(); controllerPos++) {
            Controller controller = getController(createControllerId(controllerPos));
            for (int endpointPos = 1; endpointPos <= getNbrEndpointByController(); endpointPos++) {
                assertTrue(controller.getEndpointManager(createEndpointId(controllerPos, endpointPos)).getPeersIds().size() +
                           " / " + getNbrPeerByEndpoint(),
                           controller.waitNrbPeerConnected(createEndpointId(controllerPos, endpointPos),
                                                           getNbrPeerByEndpoint(),
                                                           20000));
            }
        }

        //==========================================
        // Controller sends messages
        //==========================================
        for (int i = 0; i < 5; i++) {

            String endpointId = getRandomEndpointId();
            Controller controller = getControllerByEndpointId(endpointId);
            WebsocketEndpointManager endpointManager = controller.getEndpointManager(endpointId);
            List<Peer> peers = new ArrayList<>(getPeersByEndpointId(endpointId));

            //==========================================
            // Send message
            //==========================================
            String message = UUID.randomUUID().toString();
            endpointManager.sendMessage(message);

            for (Peer peer : peers) {
                assertTrue(peer.waitForStringMessageReceived(message));
            }

            Set<String> peerIdsTry = new HashSet<String>();
            int nbrPeersTry = RandomUtils.nextInt(1, peers.size() + 1);

            for (int j = 0; j < nbrPeersTry; j++) {
                peerIdsTry.add(peers.get(j).getPeerId());
            }

            //==========================================
            // Sends except
            //==========================================
            String message2 = UUID.randomUUID().toString();
            endpointManager.sendMessageExcept(peerIdsTry, message2);

            for (Peer peer : peers) {
                if (!peerIdsTry.contains(peer.getPeerId())) {
                    assertTrue(peer.waitForStringMessageReceived(message2));
                }
            }
            for (Peer peer : peers) {
                if (peerIdsTry.contains(peer.getPeerId())) {
                    assertFalse(peer.hasReceivedStringMessage(message2));
                }
            }

            //==========================================
            // Sends specific
            //==========================================
            String message3 = UUID.randomUUID().toString();
            endpointManager.sendMessage(peerIdsTry, message3);

            for (Peer peer : peers) {
                if (peerIdsTry.contains(peer.getPeerId())) {
                    assertTrue(peer.waitForStringMessageReceived(message3));
                }
            }
            for (Peer peer : peers) {
                if (!peerIdsTry.contains(peer.getPeerId())) {
                    assertFalse(peer.hasReceivedStringMessage(message3));
                }
            }

            validateMessageNotReceivedByEndpointsAndPeersExcept(endpointId, Sets.newHashSet(message, message2, message3));
        }

        //==========================================
        // Peers send messages
        //==========================================
        for (int i = 0; i < 5; i++) {

            Peer peer = getRandomPeer();

            //==========================================
            // Echo
            //==========================================
            String message = "echo_" + UUID.randomUUID().toString();
            peer.getWriter().sendMessage(message);

            Controller controller = getControllerByEndpointId(peer.getEndpointId());
            assertNotNull(controller);
            assertTrue(controller.waitForStringMessageReceived(peer.getEndpointId(), peer.getPeerId(), message));

            assertTrue(peer.waitForStringMessageReceived("echo " + message));

            //==========================================
            // Echo all
            //==========================================
            String message2 = "echoall_" + UUID.randomUUID().toString();
            peer.getWriter().sendMessage(message2);

            assertTrue(controller.waitForStringMessageReceived(peer.getEndpointId(), peer.getPeerId(), message2));

            Set<Peer> peers = getPeersByEndpointId(peer.getEndpointId());
            for (Peer peer2 : peers) {
                assertTrue(peer2.waitForStringMessageReceived("echo all " + message2));
            }

            //==========================================
            // Echo except
            //==========================================
            String message3 = "echoexcept_" + UUID.randomUUID().toString();
            peer.getWriter().sendMessage(message3);

            assertTrue(controller.waitForStringMessageReceived(peer.getEndpointId(), peer.getPeerId(), message3));

            peers = getPeersByEndpointId(peer.getEndpointId());

            for (Peer peer2 : peers) {
                if (!peer2.getPeerId().equals(peer.getPeerId())) {
                    assertTrue(peer2.waitForStringMessageReceived("echo except " + message3));
                }
            }

            for (Peer peer2 : peers) {
                if (peer2.getPeerId().equals(peer.getPeerId())) {
                    assertFalse(peer2.hasReceivedStringMessage("echo except " + message3));
                }
            }

            validateMessageNotReceivedByEndpointsAndPeersExcept(peer.getEndpointId(),
                                                                Sets.newHashSet(message, message2, message3));
        }

        //==========================================
        // Simultaneous messages sending
        //==========================================
        for (int i = 0; i < 5; i++) {

            String endpointId = getRandomEndpointId();
            Controller controller = getControllerByEndpointId(endpointId);
            final WebsocketEndpointManager endpointManager = controller.getEndpointManager(endpointId);
            List<Peer> peers = new ArrayList<>(getPeersByEndpointId(endpointId));

            final Peer peer1 = peers.get(0);
            final Peer peer2 = peers.get(1);
            final Peer peer3 = peers.get(2);
            final Peer peer4 = peers.get(3);

            final String message1 = UUID.randomUUID().toString();
            final String message2 = "echo_" + UUID.randomUUID().toString();
            final String message3 = "echoall_" + UUID.randomUUID().toString();
            final String message4 = "echoexcept_" + UUID.randomUUID().toString();
            final String message5 = UUID.randomUUID().toString();

            final String message2Echo = "echo " + message2;
            final String message3Echo = "echo all " + message3;
            final String message4Echo = "echo except " + message4;

            Thread t1 = new Thread(new Runnable() {

                @Override
                public void run() {
                    peer1.getWriter().sendMessage(message1);
                }
            });

            Thread t2 = new Thread(new Runnable() {

                @Override
                public void run() {
                    peer2.getWriter().sendMessage(message2);
                }
            });

            Thread t3 = new Thread(new Runnable() {

                @Override
                public void run() {
                    peer3.getWriter().sendMessage(message3);
                }
            });

            Thread t4 = new Thread(new Runnable() {

                @Override
                public void run() {
                    peer4.getWriter().sendMessage(message4);
                }
            });

            Thread t5 = new Thread(new Runnable() {

                @Override
                public void run() {
                    endpointManager.sendMessage(message5);
                }
            });

            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();

            //==========================================
            // Controller - received
            //==========================================
            assertTrue(controller.waitForStringMessageReceived(endpointId, peer1.getPeerId(), message1));
            assertTrue(controller.waitForStringMessageReceived(endpointId, peer2.getPeerId(), message2));
            assertTrue(controller.waitForStringMessageReceived(endpointId, peer3.getPeerId(), message3));
            assertTrue(controller.waitForStringMessageReceived(endpointId, peer4.getPeerId(), message4));

            //==========================================
            // Peer1 - received
            //==========================================
            assertTrue(peer1.waitForStringMessageReceived(message3Echo));
            assertTrue(peer1.waitForStringMessageReceived(message4Echo));
            assertTrue(peer1.waitForStringMessageReceived(message5));

            //==========================================
            // Peer2 - received
            //==========================================
            assertTrue(peer2.waitForStringMessageReceived(message2Echo));
            assertTrue(peer2.waitForStringMessageReceived(message3Echo));
            assertTrue(peer2.waitForStringMessageReceived(message4Echo));
            assertTrue(peer2.waitForStringMessageReceived(message5));

            //==========================================
            // Peer3 - received
            //==========================================
            assertTrue(peer3.waitForStringMessageReceived(message3Echo));
            assertTrue(peer3.waitForStringMessageReceived(message4Echo));
            assertTrue(peer3.waitForStringMessageReceived(message5));

            //==========================================
            // Peer4 - received
            //==========================================
            assertTrue(peer4.waitForStringMessageReceived(message3Echo));
            assertTrue(peer4.waitForStringMessageReceived(message5));

            //==========================================
            // All other endpoints' controllers and peers - not received
            //==========================================
            validateMessageNotReceivedByEndpointsAndPeersExcept(endpointId,
                                                                Sets.newHashSet(message1,
                                                                                message2Echo,
                                                                                message3Echo,
                                                                                message4Echo,
                                                                                message5));
            //==========================================
            // Controller - not received
            //==========================================
            assertFalse(controller.hasReceivedStringMessage(message5));

            //==========================================
            // Peer 1 - not received
            //==========================================
            assertFalse(peer1.hasReceivedStringMessage(message1));
            assertFalse(peer1.hasReceivedStringMessage(message2Echo));

            //==========================================
            // Peer 2 - not received
            //==========================================
            assertFalse(peer2.hasReceivedStringMessage(message1));

            //==========================================
            // Peer 3 - not received
            //==========================================
            assertFalse(peer3.hasReceivedStringMessage(message1));
            assertFalse(peer3.hasReceivedStringMessage(message2Echo));

            //==========================================
            // Peer 4 - not received
            //==========================================
            assertFalse(peer4.hasReceivedStringMessage(message1));
            assertFalse(peer4.hasReceivedStringMessage(message2Echo));
            assertFalse(peer4.hasReceivedStringMessage(message4Echo));
        }
    }
}


text:
import expect from 'expect'
import React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'

import match from '../match'
import { routerShape } from '../PropTypes'
import RouterContext from '../RouterContext'
import { createRouterObject } from '../RouterUtils'

describe('RouterContext', () => {
  let node, routes, context, history, transitionManager, router
  let listenBeforeLeavingRouteSentinel, isActiveSentinel, createHrefSentinel

  beforeEach(() => {
    listenBeforeLeavingRouteSentinel = {}
    isActiveSentinel = {}
    createHrefSentinel = {}

    node = document.createElement('div')

    history = {
      push: expect.createSpy(),
      replace: expect.createSpy(),
      createHref: expect.createSpy().andReturn(createHrefSentinel),
      go: expect.createSpy(),
      goBack: expect.createSpy(),
      goForward: expect.createSpy()
    }
    transitionManager = {
      listenBeforeLeavingRoute: expect.createSpy().andReturn(listenBeforeLeavingRouteSentinel),
      isActive: expect.createSpy().andReturn(isActiveSentinel)
    }

    router = createRouterObject(history, transitionManager)

    class Component extends React.Component {
      constructor(props, ctx) {
        super(props, ctx)
        context = ctx
      }
      render() { return null }
    }

    Component.contextTypes = {
      router: routerShape.isRequired
    }

    routes = { path: '/', component: Component }
  })

  afterEach(() => unmountComponentAtNode(node))

  function renderTest(done) {
    match({ location: '/', routes }, (err, redirect, renderProps) => {
      render(<RouterContext {...renderProps} history={history} router={router} />, node)
      done()
    })
  }

  describe('2.0', () => {
    it('exports only `router` to context')
  })

  it('exports a `router` object to routing context', (done) => {
    renderTest(() => {
      expect(context.router).toExist()
      done()
    })
  })

  describe('some weird tests that test implementation and should probably go away', () => {
    it('proxies calls to `push` to `props.history`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        context.router.push(...args)
        expect(history.push).toHaveBeenCalledWith(...args)
        done()
      })
    })

    it('proxies calls to `replace` to `props.history`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        context.router.replace(...args)
        expect(history.replace).toHaveBeenCalledWith(...args)
        done()
      })
    })

    it('proxies calls to `setRouteLeaveHook` to `props.transitionManager`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        const remove = context.router.setRouteLeaveHook(...args)
        expect(transitionManager.listenBeforeLeavingRoute).toHaveBeenCalledWith(...args)
        expect(remove).toBe(listenBeforeLeavingRouteSentinel)
        done()
      })
    })

    it('proxies calls to `isActive` to `props.transitionManager`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        const isActive = context.router.isActive(...args)
        expect(transitionManager.isActive).toHaveBeenCalledWith(...args)
        expect(isActive).toBe(isActiveSentinel)
        done()
      })
    })

    it('proxies calls to `createHref` to `props.history`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        const href = context.router.createHref(...args)
        expect(history.createHref).toHaveBeenCalledWith(...args)
        expect(href).toBe(createHrefSentinel)
        done()
      })
    })

    it('proxies calls to `go` to `props.history`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        context.router.go(...args)
        expect(history.go).toHaveBeenCalledWith(...args)
        done()
      })
    })

    it('proxies calls to `goBack` to `props.history`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        context.router.goBack(...args)
        expect(history.goBack).toHaveBeenCalledWith(...args)
        done()
      })
    })

    it('proxies calls to `goForward` to `props.history`', (done) => {
      const args = [ 1, 2, 3 ]
      renderTest(() => {
        context.router.goForward(...args)
        expect(history.goForward).toHaveBeenCalledWith(...args)
        done()
      })
    })
  })

})


text:
namespace new3DScene
{
	class new3DScene : public BF::Application::Scene
	{
		private:
			BF::Graphics::API::Shader P, PUV, PN, PUVN, PUVNTB;//, shader, lightShader;
			BF::Graphics::API::ConstantBuffer constantBuffer;
			BF::Graphics::API::ConstantBuffer materialConstantBuffer;
			//BF::Graphics::Model lightModel;
			//BF::Graphics::Model cubeModel;
			BF::Graphics::Model crateModel;
			//BF::Graphics::Model planeModel;
			BF::Graphics::FPSCamera fpsCamera;
			//BF::Graphics::Terrain terrain;

			bool directionalLight;
			float lightAngle;
			int lightIndex = 0;

			BF::Graphics::LightBuffer lights;
			//BF::Graphics::Material floorMaterial;
			BF::Graphics::Material crateMaterial;

			BF::Graphics::Skybox skybox;
			float angle = 0;

		public:
			new3DScene();
			~new3DScene();

		private:
			void Initialize() override;
			void Load() override;
			void Update() override;
			//void FixedUpdate() override;
			void Render() override;
			void RenderAllModels();
	};
}


text:
package com.gdn.venice.facade.callback;

/**
 * Session callback interface for implementing business logic pre/post events
 * 	- Classes that implement the SessionCallback interface must implement
 *    methods that perform validation or other business functions on the
 *    data. If an operation fails then the implementer MUST return
 *    Boolean.FALSE for the method that fails. This will create an EJBException
 *    and the whole container managed transaction will be rolled back.
 *
 *  - SessionCallback implementation classes must be registered in module-config.xml
 *    (see the example VenCountrySessionEJBCallback and the configuration file)
 *
 *

 * author: David Forden
 *

 * version: 1.0
 *

 * since: 2011
 */
public interface SessionCallback {

	/**
	 * Called by the framework prior to persisting the object
	 * @param businessObject is the specific business object that is being persisted
	 * @return true if the operation succeeds else false
	 */
	Boolean onPrePersist(Object businessObject);

	/**
	 * Called by the framework after persisting the object
	 *
	 * @param businessObjectbusinessObject is the specific business object that is being persisted
	 * @return true if the operation succeeds else false
	 */
	Boolean onPostPersist(Object businessObject);

	/**
	 * Called by the framework prior to merging the object
	 * @param businessObject is the specific business object that is being merged
	 * @return true if the operation succeeds else false
	 */
	Boolean onPreMerge(Object businessObject);

	/**
	 * Called by the framework after merging the object
	 *
	 * @param businessObjectbusinessObject is the specific business object that is being merged
	 * @return true if the operation succeeds else false
	 */
	Boolean onPostMerge(Object businessObject);

	/**
	 * Called by the framework prior to removing the object
	 * @param businessObject is the specific business object that is being removed
	 * @return true if the operation succeeds else false
	 */
	Boolean onPreRemove(Object businessObject);

	/**
	 * Called by the framework after removing the object
	 *
	 * @param businessObjectbusinessObject is the specific business object that is being removed
	 * @return true if the operation succeeds else false
	 */
	Boolean onPostRemove(Object businessObject);
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:layout_below="@id/textview_hello"
        android:id="@+id/button_select_db_file"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/button_select_db_file" />

    <Button
        android:layout_below="@id/button_select_db_file"
        android:id="@+id/button_restore"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:text="@string/button_restore" />

</RelativeLayout>


text:
"""
    tests.serving
    ~~~~~~~~~~~~~

    Added serving tests.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import os
import ssl
import subprocess
import textwrap

try:
    import OpenSSL
except ImportError:
    OpenSSL = None

try:
    import watchdog
except ImportError:
    watchdog = None

try:
    import httplib
except ImportError:
    from http import client as httplib

import requests
import requests.exceptions
import pytest

from werkzeug import __version__ as version, serving

def test_serving(dev_server):
    server = dev_server('from werkzeug.testapp import test_app as app')
    rv = requests.get('http://%s/?foo=bar&baz=blah' % server.addr).content
    assert b'WSGI Information' in rv
    assert b'foo=bar&baz=blah' in rv
    assert b'Werkzeug/' + version.encode('ascii') in rv

def test_absolute_requests(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        assert environ['HTTP_HOST'] == 'surelynotexisting.example.com:1337'
        assert environ['PATH_INFO'] == '/index.htm'
        addr = environ['HTTP_X_WERKZEUG_ADDR']
        assert environ['SERVER_PORT'] == addr.split(':')[1]
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'YES']
    ''')

    conn = httplib.HTTPConnection(server.addr)
    conn.request('GET', 'http://surelynotexisting.example.com:1337/index.htm#ignorethis',
                 headers={'X-Werkzeug-Addr': server.addr})
    res = conn.getresponse()
    assert res.read() == b'YES'

def test_double_slash_path(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        assert 'fail' not in environ['HTTP_HOST']
        start_response('200 OK', [('Content-Type', 'text/plain')])
        return [b'YES']
    ''')

    r = requests.get(server.url + '//fail')
    assert r.content == b'YES'

def test_broken_app(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        1 // 0
    ''')

    r = requests.get(server.url + '/?foo=bar&baz=blah')
    assert r.status_code == 500
    assert 'Internal Server Error' in r.text

@pytest.mark.skipif(not hasattr(ssl, 'SSLContext'),
                    reason='Missing PEP 466 (Python 2.7.9+) or Python 3.')
@pytest.mark.skipif(OpenSSL is None,
                    reason='OpenSSL is required for cert generation.')
def test_stdlib_ssl_contexts(dev_server, tmpdir):
    certificate, private_key = \
        serving.make_ssl_devcert(str(tmpdir.mkdir('certs')))

    server = dev_server('''
    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']

    import ssl
    ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    ctx.load_cert_chain("%s", "%s")
    kwargs['ssl_context'] = ctx
    ''' % (certificate, private_key))

    assert server.addr is not None
    r = requests.get(server.url, verify=False)
    assert r.content == b'hello'

@pytest.mark.skipif(OpenSSL is None, reason='OpenSSL is not installed.')
def test_ssl_context_adhoc(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']

    kwargs['ssl_context'] = 'adhoc'
    ''')
    r = requests.get(server.url, verify=False)
    assert r.content == b'hello'

@pytest.mark.skipif(OpenSSL is None, reason='OpenSSL is not installed.')
def test_make_ssl_devcert(tmpdir):
    certificate, private_key = \
        serving.make_ssl_devcert(str(tmpdir))
    assert os.path.isfile(certificate)
    assert os.path.isfile(private_key)

@pytest.mark.skipif(watchdog is None, reason='Watchdog not installed.')
def test_reloader_broken_imports(tmpdir, dev_server):
    # We explicitly assert that the server reloads on change, even though in
    # this case the import could've just been retried. This is to assert
    # correct behavior for apps that catch and cache import errors.
    #
    # Because this feature is achieved by recursively watching a large amount
    # of directories, this only works for the watchdog reloader. The stat
    # reloader is too inefficient to watch such a large amount of files.

    real_app = tmpdir.join('real_app.py')
    real_app.write("lol syntax error")

    server = dev_server('''
    trials = []
    def app(environ, start_response):
        assert not trials, 'should have reloaded'
        trials.append(1)
        import real_app
        return real_app.real_app(environ, start_response)

    kwargs['use_reloader'] = True
    kwargs['reloader_interval'] = 0.1
    kwargs['reloader_type'] = 'watchdog'
    ''')
    server.wait_for_reloader_loop()

    r = requests.get(server.url)
    assert r.status_code == 500

    real_app.write(textwrap.dedent('''
    def real_app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']
    '''))
    server.wait_for_reloader()

    r = requests.get(server.url)
    assert r.status_code == 200
    assert r.content == b'hello'

@pytest.mark.skipif(watchdog is None, reason='Watchdog not installed.')
def test_reloader_nested_broken_imports(tmpdir, dev_server):
    real_app = tmpdir.mkdir('real_app')
    real_app.join('__init__.py').write('from real_app.sub import real_app')
    sub = real_app.mkdir('sub').join('__init__.py')
    sub.write("lol syntax error")

    server = dev_server('''
    trials = []
    def app(environ, start_response):
        assert not trials, 'should have reloaded'
        trials.append(1)
        import real_app
        return real_app.real_app(environ, start_response)

    kwargs['use_reloader'] = True
    kwargs['reloader_interval'] = 0.1
    kwargs['reloader_type'] = 'watchdog'
    ''')
    server.wait_for_reloader_loop()

    r = requests.get(server.url)
    assert r.status_code == 500

    sub.write(textwrap.dedent('''
    def real_app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']
    '''))
    server.wait_for_reloader()

    r = requests.get(server.url)
    assert r.status_code == 200
    assert r.content == b'hello'

def test_monkeypached_sleep(tmpdir):
    # removing the staticmethod wrapper in the definition of
    # ReloaderLoop._sleep works most of the time, since `sleep` is a c
    # function, and unlike python functions which are descriptors, doesn't
    # become a method when attached to a class. however, if the user has called
    # `eventlet.monkey_patch` before importing `_reloader`, `time.sleep` is a
    # python function, and subsequently calling `ReloaderLoop._sleep` fails
    # with a TypeError. This test checks that _sleep is attached correctly.
    script = tmpdir.mkdir('app').join('test.py')
    script.write(textwrap.dedent('''
    import time

    def sleep(secs):
        pass

    # simulate eventlet.monkey_patch by replacing the builtin sleep
    # with a regular function before _reloader is imported
    time.sleep = sleep

    from werkzeug._reloader import ReloaderLoop
    ReloaderLoop()._sleep(0)
    '''))
    subprocess.check_call(['python', str(script)])

def test_wrong_protocol(dev_server):
    # Assert that sending HTTPS requests to a HTTP server doesn't show a
    # traceback
    # See https://github.com/mitsuhiko/werkzeug/pull/838

    server = dev_server('''
    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']
    ''')
    with pytest.raises(requests.exceptions.ConnectionError):
        requests.get('https://%s/' % server.addr)

    log = server.logfile.read()
    assert 'Traceback' not in log
    assert '\n127.0.0.1' in log


text:
var Cassandra = require('cassandra-driver') ;

var db = null;
var CassandraConnection = {
  Client: function(config, options) {
    var overriddenOptions = config;
    // The old driver used to specify hosts as the field, this is changed to contactPoints. Hosts is used as config param for backward compatibility
    overriddenOptions.contactPoints = config.hosts;
    if (config.keyspace) {
      overriddenOptions.keyspace = config.keyspace.toLowerCase();
    }
    db = new Cassandra.Client(overriddenOptions);
    return this;
  },
  execute: function(query, params, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options = {};
    }
    // This function also runs a prepared statement because that is required in the new versions of cassandra driver
    // As it gives an error whenever int is used to conform to the Number type. Cassandra assumed an int to be double
    // Recommended way of fixing this is preparing queries
    var overriddenOptions = Object.assign({}, options, {prepare: true});
    db.execute(query, params, overriddenOptions, callback);
  },
  stream: function(query, params, options, callback) {
    var overriddenOptions = Object.assign({}, options, {prepare: true});
    return db.stream(query, params, overriddenOptions, callback);
  },
  executePrepared: function(query, params, options, callback) {
    var overriddenOptions = Object.assign({}, options, {prepare: true});
    db.execute(query, params, overriddenOptions, callback);
  },
  executeBatch: function(queryArray, connection, options, callback) {
    var overriddenOptions = Object.assign({}, options, {prepare: true});
    if (!queryArray || queryArray.length == 0) {
      return callback();
    }
    db.batch(queryArray, overriddenOptions, callback);
  },
  shutdown: function(callback) {
    // The cassandra-driver does not have a close method for the db
    callback();
  }
};

module.exports = CassandraConnection;