text:
#include "LoadBalancing-cpp/inc/Client.h"
#include "LoadBalancing-cpp/inc/MutableRoom.h"
#include "LoadBalancing-cpp/inc/Internal/Utils.h"
#include "LoadBalancing-cpp/inc/Internal/Enums/Properties/Room.h"

/** @file inc/MutableRoom.h */

namespace ExitGames
{
	namespace LoadBalancing
	{
		using namespace Common;
		using namespace Common::MemoryManagement;
		using namespace Internal;

		MutableRoom::MutableRoom(const JString& name, const Hashtable& properties, Client* pClient, const JVector<JString>& propsListedInLobby, int playerTtl, int roomTtl)
			: super(name, properties)
			, mLoadBalancingClient(pClient)
			, mIsVisible(true)
			, mPlayers(JVector<Player*>())
			, mMasterClientID(0)
			, mPropsListedInLobby(propsListedInLobby)
			, mPlayerTtl(playerTtl)
			, mRoomTtl(roomTtl)
		{
			cacheProperties(properties);
		}

		MutableRoom::~MutableRoom(void)
		{
			destroyAllPlayers();
		}

		MutableRoom::MutableRoom(const MutableRoom& toCopy)
			: super(toCopy)
		{
			*this = toCopy;
		}

		MutableRoom& MutableRoom::operator=(const Room& toCopy)
		{
			return assign(toCopy);
		}

		bool MutableRoom::getIsMutable(void) const
		{
			return true;
		}

		MutableRoom& MutableRoom::assign(const Room& toCopy)
		{
			super::assign(toCopy);
			const MutableRoom& temp = static_cast<const MutableRoom&>(toCopy);
			if(!temp.getIsMutable())
				return *this;
			mLoadBalancingClient = temp.mLoadBalancingClient;
			mIsVisible = temp.mIsVisible;
			mPlayers = temp.mPlayers;
			mMasterClientID = temp.mMasterClientID;
			mPropsListedInLobby = temp.mPropsListedInLobby;
			mLoadBalancingClient = temp.mLoadBalancingClient;
			return *this;
		}

		void MutableRoom::mergeCustomProperties(const Hashtable& customProperties, bool webForward)
		{
			Hashtable stripDict = Utils::stripToCustomProperties(customProperties);
			if(!stripDict.getSize())
				return;
			Hashtable oldDict = mCustomProperties;
			mCustomProperties.put(stripDict);
			mCustomProperties = Utils::stripKeysWithNullValues(mCustomProperties);
			if(mCustomProperties != oldDict)
				mLoadBalancingClient->opSetPropertiesOfRoom(stripDict, webForward);
		}

		void MutableRoom::addCustomProperties(const Hashtable& customProperties, bool webForward)
		{
			mergeCustomProperties(Utils::stripKeysWithNullValues(customProperties), webForward);
		}

		void MutableRoom::cacheProperties(const Hashtable& properties)
		{
			if(properties.contains(static_cast<nByte>(Properties::Room::IS_VISIBLE)))
				mIsVisible = ValueObject<bool>(properties.getValue(static_cast<nByte>(Properties::Room::IS_VISIBLE))).getDataCopy();
			super::cacheProperties(properties);
		}

		JString MutableRoom::toString(bool withTypes, bool withCustomProperties, bool withPlayers) const
		{
			return mName + L"={" + payloadToString(withTypes, withCustomProperties, withPlayers) + L"}";
		}

		JString MutableRoom::payloadToString(bool withTypes, bool withCustomProperties, bool withPlayers) const
		{
			JString res = JString(L"masterClient: ") + mMasterClientID + L" " + super::payloadToString() + L" visible: " + mIsVisible;
			if(mPropsListedInLobby.getSize())
				res += L" propsListedInLobby: " + mPropsListedInLobby.toString(withTypes);
			if(withCustomProperties && mCustomProperties.getSize())
				res += L" props: " + mCustomProperties.toString(withTypes);
			if(withPlayers && mPlayers.getSize())
			{
				res += L" players: ";
				for(unsigned int i=0; i<mPlayers.getSize(); ++i)
					res += mPlayers[i]->toString(withTypes, withCustomProperties) + (i<mPlayers.getSize()-1?L", ":L"");
			}
			return res;
		}

		nByte MutableRoom::getPlayerCount(void) const
		{
			return mPlayers.getSize();
		}

		void MutableRoom::setMaxPlayers(nByte maxPlayers)
		{
			if(mMaxPlayers != maxPlayers)
				setRoomProperty(static_cast<nByte>(Properties::Room::MAX_PLAYERS), mMaxPlayers=maxPlayers);
		}

		void MutableRoom::setIsOpen(bool isOpen)
		{
			if(mIsOpen != isOpen)
				setRoomProperty(static_cast<nByte>(Properties::Room::IS_OPEN), mIsOpen=isOpen);
		}

		bool MutableRoom::getIsVisible(void) const
		{
			return mIsVisible;
		}

		void MutableRoom::setIsVisible(bool isVisible)
		{
			if(mIsVisible != isVisible)
				setRoomProperty(static_cast<nByte>(Properties::Room::IS_VISIBLE), mIsVisible=isVisible);
		}

		template<typename Etype> void MutableRoom::setRoomProperty(nByte key, Etype val)
		{
			Hashtable properties;
			properties.put(key, val);
			const bool webForward = false; // TODO: do we need to forward standard properties?
			mLoadBalancingClient->opSetPropertiesOfRoom(properties, webForward);
		}

		const JVector<Player*>& MutableRoom::getPlayers(void) const
		{
			return mPlayers;
		}

		const Player* MutableRoom::getPlayerForNumber(int playerNumber) const
		{
			for(unsigned i=0; i<mPlayers.getSize(); i++)
				if(mPlayers[i]->getNumber() == playerNumber)
					return mPlayers[i];
			return NULL;
		}

		int MutableRoom::getMasterClientID(void) const
		{
			return mMasterClientID;
		}

		const JVector<JString>& MutableRoom::getPropsListedInLobby(void) const
		{
			return mPropsListedInLobby;
		}

		void MutableRoom::setPropsListedInLobby(const JVector<JString>& propsListedInLobby, bool webForward)
		{
			if(mPropsListedInLobby != propsListedInLobby)
			{
				mPropsListedInLobby = propsListedInLobby;
				JString* propsListedInLobbyArr = allocateArray<JString>(propsListedInLobby.getSize());
				for(unsigned int i=0; i<propsListedInLobby.getSize(); ++i)
					propsListedInLobbyArr[i] = propsListedInLobby[i];
				Hashtable properties;
				properties.put(static_cast<nByte>(Properties::Room::PROPS_LISTED_IN_LOBBY), propsListedInLobbyArr, propsListedInLobby.getSize());
				deallocateArray(propsListedInLobbyArr);
				mLoadBalancingClient->opSetPropertiesOfRoom(properties, webForward);
			}
		}

		int MutableRoom::getPlayerTtl(void) const
		{
			return mPlayerTtl;
		}

		int MutableRoom::getRoomTtl(void) const
		{
			return mRoomTtl;
		}

		Player* MutableRoom::createPlayer(int number, const Hashtable& properties) const
		{
			return PlayerFactory::create(number, properties, this);
		}

		void MutableRoom::destroyPlayer(const Player* pPlayer) const
		{
			PlayerFactory::destroy(pPlayer);
		}

		void MutableRoom::setPlayers(const JVector<Player*>& players)
		{
			mPlayers = players;
		}

		void MutableRoom::removeAllPlayers(void)
		{
			destroyAllPlayers();
			mPlayers.removeAllElements();
		}

		void MutableRoom::destroyAllPlayers(void)
		{
			for(unsigned int i=0; i<mPlayers.getSize(); ++i)
				if(mPlayers[i]->getNumber() != mLocalPlayerNumber)
					destroyPlayer(mPlayers[i]);
		}

		void MutableRoom::addPlayer(Player& player)
		{
			mPlayers.addElement(&player);
			if(!mMasterClientID || player.getNumber() < mMasterClientID)
				mMasterClientID = player.getNumber();
		}

		void MutableRoom::addLocalPlayer(Player& player)
		{
			mLocalPlayerNumber = player.getNumber();
			addPlayer(player);
		}

		void MutableRoom::addPlayer(int number, const Common::Hashtable& properties)
		{
			addPlayer(*createPlayer(number, properties));
		}

		bool MutableRoom::removePlayer(int number)
		{
			bool retVal = false;
			for(unsigned int i=0; i<mPlayers.getSize(); ++i)
			{
				if(mPlayers[i]->getNumber() == number)
				{
					destroyPlayer(mPlayers[i]);
					mPlayers.removeElementAt(i);
					retVal = true;
				}
			}

			if(number == mMasterClientID)
			{
				mMasterClientID = mPlayers.getSize()?mPlayers[0]->getNumber():0;
				for(unsigned int i=1; i<mPlayers.getSize(); ++i)
					if(mPlayers[i]->getNumber() < mMasterClientID)
						mMasterClientID = mPlayers[i]->getNumber();
			}
			return retVal;
		}

		JVector<Player*>& MutableRoom::getNonConstPlayers(void)
		{
			return mPlayers;
		}
	}
}


text:
<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class PagoType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('pagado', CheckboxType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Pago'
        ));
    }

    public function getName()
    {
        return 'pago';
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Includeable, IncludeOptions } from 'sequelize'
import { SGModel, SGModelCtrl } from '../../index'

function restoreTimestamps(
  data: any,
  instance: SGModel,
  include?: Includeable | Includeable[]
) {
  const timestampFields = ['createdAt', 'updatedAt', 'deletedAt']

  for (const field of timestampFields) {
    const value = data[field]
    if (value) {
      instance.setDataValue(field, new Date(value))
    }
  }
  if (data['version'] != null) {
    instance.setDataValue('version', data['version'])
  }

  const restore = (includeItem: Includeable) => {
    if ((includeItem as IncludeOptions).as) {
      const item = includeItem as IncludeOptions
      const field = item.as as string
      if (data[field]) {
        if (Array.isArray(data[field])) {
          for (let index = 0; index < data[field].length; index++) {
            restoreTimestamps(
              data[field][index],
              instance[field][index],
              item.include
            )
          }
        } else {
          restoreTimestamps(data[field], instance[field], item.include)
        }
      }
    }
  }

  if (Array.isArray(include)) {
    include.forEach((i) => restore(i))
  } else if (include) {
    restore(include)
  }
}

export default function (
  data,
  model: SGModelCtrl,
  include?: Includeable | Includeable[]
) {
  if (!data) {
    return data
  }
  const instance = model.build(data, {
    isNewRecord: false,
    raw: false,
    include
  })
  if (Array.isArray(include)) {
    restoreTimestamps(data, instance, include)
  } else if (include != null) {
    restoreTimestamps(data, instance, [include])
  } else {
    restoreTimestamps(data, instance, [])
  }

  return instance
}


text:
namespace Lucene
{
    CachingTokenFilter::CachingTokenFilter(TokenStreamPtr input) : TokenFilter(input)
    {
    }

    CachingTokenFilter::~CachingTokenFilter()
    {
    }

    bool CachingTokenFilter::incrementToken()
    {
        if (!cache)
        {
            // fill cache lazily
            cache = Collection<AttributeSourceStatePtr>::newInstance();
            fillCache();
            iterator = cache.begin();
        }

        if (iterator == cache.end())
        {
            // the cache is exhausted, return false
            return false;
        }

        // Since the TokenFilter can be reset, the tokens need to be preserved as immutable.
        restoreState(*iterator++);
        return true;
    }

    void CachingTokenFilter::end()
    {
        if (finalState)
            restoreState(finalState);
    }

    void CachingTokenFilter::reset()
    {
        if (cache)
            iterator = cache.begin();
    }

    void CachingTokenFilter::fillCache()
    {
        while (input->incrementToken())
            cache.add(captureState());
        // capture final state
        input->end();
        finalState = captureState();
    }
}


text:
  - upgrade to Bitbucket Server 6.5.1

## 2.0.0

  - upgrade to Bitbucket Server 4.8.2
  - upgrade to Java 8

## 1.1.0

  - added option to specify version commit pattern

## 1.0.0

  - first release


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace BusinessModel.Core.Models.Mapping
{
    public class storeMap : EntityTypeConfiguration<store>
    {
        public storeMap()
        {
            // Primary Key
            this.HasKey(t => t.stor_id);

            // Properties
            this.Property(t => t.stor_id)
                .IsRequired()
                .IsFixedLength()
                .HasMaxLength(4);

            this.Property(t => t.stor_name)
                .HasMaxLength(40);

            this.Property(t => t.stor_address)
                .HasMaxLength(40);

            this.Property(t => t.city)
                .HasMaxLength(20);

            this.Property(t => t.state)
                .IsFixedLength()
                .HasMaxLength(2);

            this.Property(t => t.zip)
                .IsFixedLength()
                .HasMaxLength(5);

            // Table & Column Mappings
            this.ToTable("stores");
            this.Property(t => t.stor_id).HasColumnName("stor_id");
            this.Property(t => t.stor_name).HasColumnName("stor_name");
            this.Property(t => t.stor_address).HasColumnName("stor_address");
            this.Property(t => t.city).HasColumnName("city");
            this.Property(t => t.state).HasColumnName("state");
            this.Property(t => t.zip).HasColumnName("zip");
        }
    }
}


text:
//version 8:
class BuilderWithNonNullWithSetterPrefix {
	@lombok.NonNull
	private final String id;
	@java.lang.SuppressWarnings("all")
	BuilderWithNonNullWithSetterPrefix(@lombok.NonNull final String id) {
		if (id == null) {
			throw new java.lang.NullPointerException("id is marked non-null but is null");
		}
		this.id = id;
	}
	@java.lang.SuppressWarnings("all")
	public static class BuilderWithNonNullWithSetterPrefixBuilder {
		@java.lang.SuppressWarnings("all")
		private String id;
		@java.lang.SuppressWarnings("all")
		BuilderWithNonNullWithSetterPrefixBuilder() {
		}
		/**
		 * @return {@code this}.
		 */
		@java.lang.SuppressWarnings("all")
		public BuilderWithNonNullWithSetterPrefix.BuilderWithNonNullWithSetterPrefixBuilder withId(@lombok.NonNull final String id) {
			if (id == null) {
				throw new java.lang.NullPointerException("id is marked non-null but is null");
			}
			this.id = id;
			return this;
		}
		@java.lang.SuppressWarnings("all")
		public BuilderWithNonNullWithSetterPrefix build() {
			return new BuilderWithNonNullWithSetterPrefix(this.id);
		}
		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		public java.lang.String toString() {
			return "BuilderWithNonNullWithSetterPrefix.BuilderWithNonNullWithSetterPrefixBuilder(id=" + this.id + ")";
		}
	}
	@java.lang.SuppressWarnings("all")
	public static BuilderWithNonNullWithSetterPrefix.BuilderWithNonNullWithSetterPrefixBuilder builder() {
		return new BuilderWithNonNullWithSetterPrefix.BuilderWithNonNullWithSetterPrefixBuilder();
	}
}


text:
<ModuleSet>
	<Name>ModPolarizerClassI</Name>
	<Description>ModPolarizerClassIDesc</Description>
	<ModuleCategory>Defences</ModuleCategory>
	<Modules>
		<string>PolarizerClassI_4x4</string>
		<string>PolarizerClassI_3x3</string>
		<string>PolarizerClassI_2x2</string>
		<string>PolarizerClassI_1x1</string>
	</Modules>
</ModuleSet>


text:
/**
 * Client imports some but not all modules,
 * triggering/suppressing parse errors.
 * @flow
 */

// non-flow files should give parse errors if they're imported
var A = require("Foo");          // non-Flow file @providesModule Foo
var B = require("./NoProvides"); // non-Flow file


text:
using System;
using bstrkr.core.spatial;

namespace bstrkr.grabber
{
	public class WaypointDTO
	{
		public float Fraction { get; set; }

		public double Latitude { get; set; }

		public double Longitude { get; set; }

		public float Heading { get; set; }
	}
}


text:
from cassandra import InvalidRequest
from cassandra.cluster import Cluster
from cassandra.cluster import NoHostAvailable
from cassandra.cqlengine import columns, CQLEngineException
from cassandra.cqlengine import connection as conn
from cassandra.cqlengine.management import drop_keyspace, sync_table, drop_table, create_keyspace_simple
from cassandra.cqlengine.models import Model, QuerySetDescriptor
from cassandra.cqlengine.query import ContextQuery, BatchQuery, ModelQuerySet
from tests.integration.cqlengine import setup_connection, DEFAULT_KEYSPACE
from tests.integration.cqlengine.base import BaseCassEngTestCase
from tests.integration.cqlengine.query import test_queryset
from tests.integration import local, CASSANDRA_IP

class TestModel(Model):

    __keyspace__ = 'ks1'

    partition = columns.Integer(primary_key=True)
    cluster = columns.Integer(primary_key=True)
    count = columns.Integer()
    text = columns.Text()

class AnotherTestModel(Model):

    __keyspace__ = 'ks1'

    partition = columns.Integer(primary_key=True)
    cluster = columns.Integer(primary_key=True)
    count = columns.Integer()
    text = columns.Text()

class ContextQueryConnectionTests(BaseCassEngTestCase):

    @classmethod
    def setUpClass(cls):
        super(ContextQueryConnectionTests, cls).setUpClass()
        create_keyspace_simple('ks1', 1)

        conn.unregister_connection('default')
        conn.register_connection('fake_cluster', ['1.2.3.4'], lazy_connect=True, retry_connect=True, default=True)
        conn.register_connection('cluster', [CASSANDRA_IP])

        with ContextQuery(TestModel, connection='cluster') as tm:
            sync_table(tm)

    @classmethod
    def tearDownClass(cls):
        super(ContextQueryConnectionTests, cls).tearDownClass()

        with ContextQuery(TestModel, connection='cluster') as tm:
            drop_table(tm)
        drop_keyspace('ks1', connections=['cluster'])

        # reset the default connection
        conn.unregister_connection('fake_cluster')
        conn.unregister_connection('cluster')
        setup_connection(DEFAULT_KEYSPACE)

    def setUp(self):
        super(BaseCassEngTestCase, self).setUp()

    def test_context_connection_priority(self):
        """
        Tests to ensure the proper connection priority is honored.

        Explicit connection should have higest priority,
        Followed by context query connection
        Default connection should be honored last.

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result priorities should be honored

        @test_category object_mapper
        """
        # model keyspace write/read

        # Set the default connection on the Model
        TestModel.__connection__ = 'cluster'
        with ContextQuery(TestModel) as tm:
            tm.objects.create(partition=1, cluster=1)

        # ContextQuery connection should have priority over default one
        with ContextQuery(TestModel, connection='fake_cluster') as tm:
            with self.assertRaises(NoHostAvailable):
                tm.objects.create(partition=1, cluster=1)

        # Explicit connection should have priority over ContextQuery one
        with ContextQuery(TestModel, connection='fake_cluster') as tm:
            tm.objects.using(connection='cluster').create(partition=1, cluster=1)

        # Reset the default conn of the model
        TestModel.__connection__ = None

        # No model connection and an invalid default connection
        with ContextQuery(TestModel) as tm:
            with self.assertRaises(NoHostAvailable):
                tm.objects.create(partition=1, cluster=1)

    def test_context_connection_with_keyspace(self):
        """
        Tests to ensure keyspace param is honored

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result Invalid request is thrown

        @test_category object_mapper
        """

        # ks2 doesn't exist
        with ContextQuery(TestModel, connection='cluster', keyspace='ks2') as tm:
            with self.assertRaises(InvalidRequest):
                tm.objects.create(partition=1, cluster=1)

class ManagementConnectionTests(BaseCassEngTestCase):

    keyspaces = ['ks1', 'ks2']
    conns = ['cluster']

    @classmethod
    def setUpClass(cls):
        super(ManagementConnectionTests, cls).setUpClass()
        conn.unregister_connection('default')
        conn.register_connection('fake_cluster', ['127.0.0.100'], lazy_connect=True, retry_connect=True, default=True)
        conn.register_connection('cluster', [CASSANDRA_IP])

    @classmethod
    def tearDownClass(cls):
        super(ManagementConnectionTests, cls).tearDownClass()

        # reset the default connection
        conn.unregister_connection('fake_cluster')
        conn.unregister_connection('cluster')
        setup_connection(DEFAULT_KEYSPACE)

    def setUp(self):
        super(BaseCassEngTestCase, self).setUp()

    def test_create_drop_keyspace(self):
        """
        Tests drop and create keyspace with connections explicitly set

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result keyspaces should be created and dropped

        @test_category object_mapper
        """

        # No connection (default is fake)
        with self.assertRaises(NoHostAvailable):
            create_keyspace_simple(self.keyspaces[0], 1)

        # Explicit connections
        for ks in self.keyspaces:
            create_keyspace_simple(ks, 1, connections=self.conns)

        for ks in self.keyspaces:
            drop_keyspace(ks, connections=self.conns)

    def test_create_drop_table(self):
        """
        Tests drop and create Table with connections explicitly set

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result Tables should be created and dropped

        @test_category object_mapper
        """
        for ks in self.keyspaces:
            create_keyspace_simple(ks, 1, connections=self.conns)

        # No connection (default is fake)
        with self.assertRaises(NoHostAvailable):
            sync_table(TestModel)

        # Explicit connections
        sync_table(TestModel, connections=self.conns)

        # Explicit drop
        drop_table(TestModel, connections=self.conns)

        # Model connection
        TestModel.__connection__ = 'cluster'
        sync_table(TestModel)
        TestModel.__connection__ = None

        # No connection (default is fake)
        with self.assertRaises(NoHostAvailable):
            drop_table(TestModel)

        # Model connection
        TestModel.__connection__ = 'cluster'
        drop_table(TestModel)
        TestModel.__connection__ = None

        # Model connection
        for ks in self.keyspaces:
            drop_keyspace(ks, connections=self.conns)

    def test_connection_creation_from_session(self):
        """
        Test to ensure that you can register a connection from a session
        @since 3.8
        @jira_ticket PYTHON-649
        @expected_result queries should execute appropriately

        @test_category object_mapper
        """
        cluster = Cluster([CASSANDRA_IP])
        session = cluster.connect()
        connection_name = 'from_session'
        conn.register_connection(connection_name, session=session)
        self.assertIsNotNone(conn.get_connection(connection_name).cluster.metadata.get_host(CASSANDRA_IP))
        self.addCleanup(conn.unregister_connection, connection_name)
        cluster.shutdown()

    def test_connection_from_hosts(self):
        """
        Test to ensure that you can register a connection from a list of hosts
        @since 3.8
        @jira_ticket PYTHON-692
        @expected_result queries should execute appropriately

        @test_category object_mapper
        """
        connection_name = 'from_hosts'
        conn.register_connection(connection_name, hosts=[CASSANDRA_IP])
        self.assertIsNotNone(conn.get_connection(connection_name).cluster.metadata.get_host(CASSANDRA_IP))
        self.addCleanup(conn.unregister_connection, connection_name)

    def test_connection_param_validation(self):
        """
        Test to validate that invalid parameter combinations for registering connections via session are not tolerated
        @since 3.8
        @jira_ticket PYTHON-649
        @expected_result queries should execute appropriately

        @test_category object_mapper
        """
        cluster = Cluster([CASSANDRA_IP])
        session = cluster.connect()
        with self.assertRaises(CQLEngineException):
            conn.register_connection("bad_coonection1", session=session, consistency="not_null")
        with self.assertRaises(CQLEngineException):
            conn.register_connection("bad_coonection2", session=session, lazy_connect="not_null")
        with self.assertRaises(CQLEngineException):
            conn.register_connection("bad_coonection3", session=session, retry_connect="not_null")
        with self.assertRaises(CQLEngineException):
            conn.register_connection("bad_coonection4", session=session, cluster_options="not_null")
        with self.assertRaises(CQLEngineException):
            conn.register_connection("bad_coonection5", hosts="not_null", session=session)
        cluster.shutdown()

        cluster.shutdown()

        cluster.shutdown()

class BatchQueryConnectionTests(BaseCassEngTestCase):

    conns = ['cluster']

    @classmethod
    def setUpClass(cls):
        super(BatchQueryConnectionTests, cls).setUpClass()

        create_keyspace_simple('ks1', 1)
        sync_table(TestModel)
        sync_table(AnotherTestModel)

        conn.unregister_connection('default')
        conn.register_connection('fake_cluster', ['127.0.0.100'], lazy_connect=True, retry_connect=True, default=True)
        conn.register_connection('cluster', [CASSANDRA_IP])

    @classmethod
    def tearDownClass(cls):
        super(BatchQueryConnectionTests, cls).tearDownClass()

        # reset the default connection
        conn.unregister_connection('fake_cluster')
        conn.unregister_connection('cluster')
        setup_connection(DEFAULT_KEYSPACE)

        drop_keyspace('ks1')

    def setUp(self):
        super(BaseCassEngTestCase, self).setUp()

    def test_basic_batch_query(self):
        """
        Test Batch queries with connections explicitly set

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result queries should execute appropriately

        @test_category object_mapper
        """

        # No connection with a QuerySet (default is a fake one)
        with self.assertRaises(NoHostAvailable):
            with BatchQuery() as b:
                TestModel.objects.batch(b).create(partition=1, cluster=1)

        # Explicit connection with a QuerySet
        with BatchQuery(connection='cluster') as b:
            TestModel.objects.batch(b).create(partition=1, cluster=1)

        # Get an object from the BD
        with ContextQuery(TestModel, connection='cluster') as tm:
            obj = tm.objects.get(partition=1, cluster=1)
            obj.__connection__ = None

        # No connection with a model (default is a fake one)
        with self.assertRaises(NoHostAvailable):
            with BatchQuery() as b:
                obj.count = 2
                obj.batch(b).save()

        # Explicit connection with a model
        with BatchQuery(connection='cluster') as b:
            obj.count = 2
            obj.batch(b).save()

    def test_batch_query_different_connection(self):
        """
        Test BatchQuery with Models that have a different connection

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result queries should execute appropriately

        @test_category object_mapper
        """

        # Testing on a model class
        TestModel.__connection__ = 'cluster'
        AnotherTestModel.__connection__ = 'cluster2'

        with self.assertRaises(CQLEngineException):
            with BatchQuery() as b:
                TestModel.objects.batch(b).create(partition=1, cluster=1)
                AnotherTestModel.objects.batch(b).create(partition=1, cluster=1)

        TestModel.__connection__ = None
        AnotherTestModel.__connection__ = None

        with BatchQuery(connection='cluster') as b:
            TestModel.objects.batch(b).create(partition=1, cluster=1)
            AnotherTestModel.objects.batch(b).create(partition=1, cluster=1)

        # Testing on a model instance
        with ContextQuery(TestModel, AnotherTestModel, connection='cluster') as (tm, atm):
            obj1 = tm.objects.get(partition=1, cluster=1)
            obj2 = atm.objects.get(partition=1, cluster=1)

            obj1.__connection__ = 'cluster'
            obj2.__connection__ = 'cluster2'

            obj1.count = 4
            obj2.count = 4

        with self.assertRaises(CQLEngineException):
            with BatchQuery() as b:
                obj1.batch(b).save()
                obj2.batch(b).save()

    def test_batch_query_connection_override(self):
        """
        Test that we cannot override a BatchQuery connection per model

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result Proper exceptions should be raised

        @test_category object_mapper
        """

        with self.assertRaises(CQLEngineException):
            with BatchQuery(connection='cluster') as b:
                TestModel.batch(b).using(connection='test').save()

        with self.assertRaises(CQLEngineException):
            with BatchQuery(connection='cluster') as b:
                TestModel.using(connection='test').batch(b).save()

        with ContextQuery(TestModel, AnotherTestModel, connection='cluster') as (tm, atm):
            obj1 = tm.objects.get(partition=1, cluster=1)
            obj1.__connection__ = None

        with self.assertRaises(CQLEngineException):
            with BatchQuery(connection='cluster') as b:
                obj1.using(connection='test').batch(b).save()

        with self.assertRaises(CQLEngineException):
            with BatchQuery(connection='cluster') as b:
                obj1.batch(b).using(connection='test').save()

class UsingDescriptorTests(BaseCassEngTestCase):

    conns = ['cluster']
    keyspaces = ['ks1', 'ks2']

    @classmethod
    def setUpClass(cls):
        super(UsingDescriptorTests, cls).setUpClass()

        conn.unregister_connection('default')
        conn.register_connection('fake_cluster', ['127.0.0.100'], lazy_connect=True, retry_connect=True, default=True)
        conn.register_connection('cluster', [CASSANDRA_IP])

    @classmethod
    def tearDownClass(cls):
        super(UsingDescriptorTests, cls).tearDownClass()

        # reset the default connection
        conn.unregister_connection('fake_cluster')
        conn.unregister_connection('cluster')
        setup_connection(DEFAULT_KEYSPACE)

        for ks in cls.keyspaces:
            drop_keyspace(ks)

    def setUp(self):
        super(BaseCassEngTestCase, self).setUp()

    def _reset_data(self):

        for ks in self.keyspaces:
            drop_keyspace(ks, connections=self.conns)
        for ks in self.keyspaces:
            create_keyspace_simple(ks, 1, connections=self.conns)
        sync_table(TestModel, keyspaces=self.keyspaces, connections=self.conns)

    def test_keyspace(self):
        """
        Test keyspace segregation when same connection is used

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result Keyspace segration is honored

        @test_category object_mapper
        """
        self._reset_data()

        with ContextQuery(TestModel, connection='cluster') as tm:

            # keyspace Model class
            tm.objects.using(keyspace='ks2').create(partition=1, cluster=1)
            tm.objects.using(keyspace='ks2').create(partition=2, cluster=2)

            with self.assertRaises(TestModel.DoesNotExist):
                tm.objects.get(partition=1, cluster=1)  # default keyspace ks1
            obj1 = tm.objects.using(keyspace='ks2').get(partition=1, cluster=1)

            obj1.count = 2
            obj1.save()

        with self.assertRaises(NoHostAvailable):
            TestModel.objects.using(keyspace='ks2').get(partition=1, cluster=1)

        obj2 = TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=1, cluster=1)
        self.assertEqual(obj2.count, 2)

        # Update test
        TestModel.objects(partition=2, cluster=2).using(connection='cluster', keyspace='ks2').update(count=5)
        obj3 = TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=2, cluster=2)
        self.assertEqual(obj3.count, 5)

        TestModel.objects(partition=2, cluster=2).using(connection='cluster', keyspace='ks2').delete()
        with self.assertRaises(TestModel.DoesNotExist):
            TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=2, cluster=2)

    def test_connection(self):
        """
        Test basic connection functionality

        @since 3.7
        @jira_ticket PYTHON-613
        @expected_result proper connection should be used

        @test_category object_mapper
        """
        self._reset_data()

        # Model class
        with self.assertRaises(NoHostAvailable):
            TestModel.objects.create(partition=1, cluster=1)

        TestModel.objects.using(connection='cluster').create(partition=1, cluster=1)
        TestModel.objects(partition=1, cluster=1).using(connection='cluster').update(count=2)
        obj1 = TestModel.objects.using(connection='cluster').get(partition=1, cluster=1)
        self.assertEqual(obj1.count, 2)

        obj1.using(connection='cluster').update(count=5)
        obj1 = TestModel.objects.using(connection='cluster').get(partition=1, cluster=1)
        self.assertEqual(obj1.count, 5)

        obj1.using(connection='cluster').delete()
        with self.assertRaises(TestModel.DoesNotExist):
            TestModel.objects.using(connection='cluster').get(partition=1, cluster=1)

class ModelQuerySetNew(ModelQuerySet):
    def __init__(self, *args, **kwargs):
        super(ModelQuerySetNew, self).__init__(*args, **kwargs)
        self._connection = "cluster"

class BaseConnectionTestNoDefault(object):
    conns = ['cluster']

    @classmethod
    def setUpClass(cls):
        conn.register_connection('cluster', [CASSANDRA_IP])
        test_queryset.TestModel.__queryset__ = ModelQuerySetNew
        test_queryset.IndexedTestModel.__queryset__ = ModelQuerySetNew
        test_queryset.IndexedCollectionsTestModel.__queryset__ = ModelQuerySetNew
        test_queryset.TestMultiClusteringModel.__queryset__ = ModelQuerySetNew

        super(BaseConnectionTestNoDefault, cls).setUpClass()
        conn.unregister_connection('default')

    @classmethod
    def tearDownClass(cls):
        conn.unregister_connection('cluster')
        setup_connection(DEFAULT_KEYSPACE)
        super(BaseConnectionTestNoDefault, cls).tearDownClass()
        # reset the default connection

    def setUp(self):
        super(BaseCassEngTestCase, self).setUp()

class TestQuerySetOperationConnection(BaseConnectionTestNoDefault, test_queryset.TestQuerySetOperation):
    """
    Execute test_queryset.TestQuerySetOperation using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestQuerySetDistinctNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetDistinct):
    """
    Execute test_queryset.TestQuerySetDistinct using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestQuerySetOrderingNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetOrdering):
    """
    Execute test_queryset.TestQuerySetOrdering using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestQuerySetCountSelectionAndIterationNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetCountSelectionAndIteration):
    """
    Execute test_queryset.TestQuerySetOrdering using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestQuerySetSlicingNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetSlicing):
    """
    Execute test_queryset.TestQuerySetOrdering using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestQuerySetValidationNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetValidation):
    """
    Execute test_queryset.TestQuerySetOrdering using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestQuerySetDeleteNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetDelete):
    """
    Execute test_queryset.TestQuerySetDelete using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestValuesListNoDefault(BaseConnectionTestNoDefault, test_queryset.TestValuesList):
    """
    Execute test_queryset.TestValuesList using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass

class TestObjectsPropertyNoDefault(BaseConnectionTestNoDefault, test_queryset.TestObjectsProperty):
    """
    Execute test_queryset.TestObjectsProperty using non default connection

    @since 3.7
    @jira_ticket PYTHON-613
    @expected_result proper connection should be used

    @test_category object_mapper
    """
    pass


text:
package com.blazeloader.api.particles;

import net.minecraft.entity.Entity;
import net.minecraft.world.World;

public class ParticleEmitter extends net.minecraft.client.particle.ParticleEmitter {

	private Entity entity;
	private ParticleData particle;

	private int age;
	private int maxAge;

	public ParticleEmitter(World world, Entity e, ParticleData particleData) {
		super(world, e, null);
		entity = e;
		maxAge = 3;
		particle = particleData;
	}

	public void onUpdate() {
        for (int i = 0; i < 16; ++i) {
            double vX = rand.nextFloat() * 2 - 1;
            double vY = rand.nextFloat() * 2 - 1;
            double vZ = rand.nextFloat() * 2 - 1;
            if (vX * vX + vY * vY + vZ * vZ <= 1) {
                double x = entity.posX + vX * entity.width/4;
                double y = entity.getEntityBoundingBox().minY + entity.height/2 + vY * entity.height/4;
                double z = entity.posZ + vZ * entity.width/4;
                ApiParticles.spawnParticle(particle.setPos(x, y, z).setVel(vX, vY + 0.2D, vZ), world);
            }
        }
        if (++age >= maxAge) setExpired();
    }
}


text:
using sapHowmuch.Base.Constants;
using sapHowmuch.Base.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace sapHowmuch.Base.Extensions
{
	/// <summary>
	/// SAP Business One Document extension methods
	/// </summary>
	public static class DocumentExtensions
	{
		public static int AddEx(this SAPbobsCOM.IDocuments documents)
		{
			var returnCode = documents.Add();
			ErrorHelper.HandleErrorWithException(returnCode, "Could not add document");

			return int.Parse(SapStream.DICompany.GetNewObjectKey());
		}

		public static void AddAndLoadEx(this SAPbobsCOM.IDocuments documents)
		{
			var docEntryKey = documents.AddEx();
			if (!documents.GetByKey(docEntryKey))
				throw new Exception($"Could not load document with docEntry {docEntryKey}");
		}

		public static void UpdateEx(this SAPbobsCOM.IDocuments documents)
		{
			var returnCode = documents.Update();
			ErrorHelper.HandleErrorWithException(returnCode, "Could not update document");
		}

		public static IEnumerable<SAPbobsCOM.Document_Lines> AsEnumerable(this SAPbobsCOM.Document_Lines lines)
		{
			var line = -1;
			while (++line < lines.Count)
			{
				lines.SetCurrentLine(line);
				yield return lines;
			}
		}

		// 운송비 (e.g. INV3 : AR Freight (운송비 처리부분)
		public static IEnumerable<SAPbobsCOM.DocumentsAdditionalExpenses> AsEnumerable(this SAPbobsCOM.DocumentsAdditionalExpenses expenses)
		{
			var line = -1;
			while (++line < expenses.Count)
			{
				expenses.SetCurrentLine(line);
				yield return expenses;
			}
		}

		public static bool Search(this SAPbobsCOM.IDocuments document, string table, string where)
		{
			if (string.IsNullOrWhiteSpace(table))
				throw new ArgumentNullException(nameof(table));

			var recordSet = SapStream.DICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset) as SAPbobsCOM.Recordset;
			recordSet.DoQuery($"SELECT * FROM [{table}] WHERE {where}");
			document.Browser.Recordset = recordSet;
			return recordSet.RecordCount != 0;
		}

		public static int CopyTo(this SAPbobsCOM.IDocuments sourceDocument, SAPbobsCOM.BoObjectTypes copyToType, bool copyExpenses = true, Action<SAPbobsCOM.Documents> setObjectProperties = null)
		{
			using (var copyTo = SapStream.DICompany.GetBusinessObject<SAPbobsCOM.Documents>(copyToType))
			{
				var targetDocument = copyTo.Object;

				targetDocument.CardCode = sourceDocument.CardCode;

				setObjectProperties?.Invoke(targetDocument);

				foreach (var sourceLine in sourceDocument.Lines.AsEnumerable())
				{
					sapHowmuchLogger.Debug($"CopyTo.Line: DocEntry={sourceLine.DocEntry}, LineNum={sourceLine.LineNum}, DocObjectCode={sourceDocument.DocObjectCode}");
					targetDocument.Lines.BaseEntry = sourceLine.DocEntry;
					targetDocument.Lines.BaseLine = sourceLine.LineNum;
					targetDocument.Lines.BaseType = (int)sourceDocument.DocObjectCode;
					targetDocument.Lines.Add();
				}

				if (copyExpenses)
				{
					foreach (var sourceExpense in sourceDocument.Expenses.AsEnumerable().Where(e => e.LineTotal > 0))
					{
						sapHowmuchLogger.Debug($"CopyTo.Expense: DocEntry={sourceDocument.DocEntry}, LineNum={sourceExpense.LineNum}, DocObjectCode={sourceDocument.DocObjectCode}");
						targetDocument.Expenses.BaseDocEntry = sourceDocument.DocEntry;
						targetDocument.Expenses.BaseDocLine = sourceExpense.LineNum;
						targetDocument.Expenses.BaseDocType = (int)sourceDocument.DocObjectCode;
						targetDocument.Expenses.Add();
					}
				}

				targetDocument.AddAndLoadEx();

				return targetDocument.DocEntry;
			}
		}

		public static decimal GetWeightInMg(this SAPbobsCOM.Document_Lines line)
		{
			using (var weightMeasures = SapStream.DICompany.GetBusinessObject<SAPbobsCOM.WeightMeasures>(SAPbobsCOM.BoObjectTypes.oWeightMeasures))
			{
				if (weightMeasures.Object.GetByKey(line.Weight1Unit))
					return (decimal)(line.Weight1 * weightMeasures.Object.UnitWeightinmg);

				return 0;
			}
		}

		public static decimal GetWeightInMg(this SAPbobsCOM.IDocumentPackages line)
		{
			using (var weightMeasures = SapStream.DICompany.GetBusinessObject<SAPbobsCOM.WeightMeasures>(SAPbobsCOM.BoObjectTypes.oWeightMeasures))
			{
				if (weightMeasures.Object.GetByKey(line.Units))
					return (decimal)(line.TotalWeight * weightMeasures.Object.UnitWeightinmg);

				return 0;
			}
		}

		public static string GetTableName(this SAPbobsCOM.BoObjectTypes boObjectType)
		{
			var tableConstant = typeof(SboTable).GetFields().FirstOrDefault(x => x.GetCustomAttribute<DescriptionAttribute>().Description == ((int)boObjectType).ToString());

			return tableConstant?.GetRawConstantValue().ToString();
		}

		public static void AddComment(this SAPbobsCOM.IDocuments documents, string comment)
		{
			documents.Comments = documents.Comments.AddNewLine(comment);
		}

		public static string AddNewLine(this string existingText, string newLine)
		{
			var lines = existingText.Split(new[] { "\n" }, StringSplitOptions.None);
			if (lines[lines.Length - 1] != "")
				existingText += $"{Environment.NewLine}{newLine}{Environment.NewLine}";
			else
				existingText += $"{newLine}{Environment.NewLine}";

			return existingText;
		}

		public static int? GetDocEntry(this int docNum, string table)
		{
			using (var query = new SboRecordsetQuery($"SELECT [DocEntry] FROM [{table}] WHERE [DocNum] = {docNum}"))
			{
				if (query.Count == 0) return null;

				return int.Parse(query.Result.First().Item("DocEntry").Value.ToString());
			}
		}
	}
}


text:
package pl.maxmati.tobiasz.mmos.bread.activity;

import android.util.Log;

import pl.maxmati.tobiasz.mmos.bread.api.APIConnector;
import pl.maxmati.tobiasz.mmos.bread.api.resource.ResourceManager;
import pl.maxmati.tobiasz.mmos.bread.api.resource.ResourceUpdate;
import pl.maxmati.tobiasz.mmos.bread.api.session.SessionException;
import pl.maxmati.tobiasz.mmos.bread.api.session.SessionManager;

/**
 * Created by mmos on 21.02.16.
 *
 * @author mmos
 */
public class UpdateCounterTask extends ProgressBarAsyncTask<Void, Void, Integer> {
    private static final String TAG = "UpdateCounterTask";

    private final String resourceName;
    private final int amount;

    private Exception exception;

    public UpdateCounterTask(ProgressBarActivity progressBarActivity, String resourceName, int amount) {
        super(progressBarActivity);
        this.resourceName = resourceName;
        this.amount = amount;
    }

    public Exception getException() {
        return exception;
    }

    @Override
    protected Integer doInBackground(Void... voids) {
        try {
            Log.d(TAG, "Starting update of resource " + resourceName);
            ResourceUpdate resourceUpdate = new ResourceUpdate(amount);
            return ResourceManager.update(new APIConnector(progressBarActivity, SessionManager.restoreSession
                    (progressBarActivity)), resourceName, resourceUpdate);
        } catch (Exception e) {
            exception = e;
            Log.e(TAG, "Resource update failed: " + e.getMessage());
        }
        return null;
    }
}


text:
#ifndef LULLABY_TESTS_UTIL_ENTITY_TEST_H_
#define LULLABY_TESTS_UTIL_ENTITY_TEST_H_

#include <vector>

#include "flatbuffers/flatbuffers.h"
#include "gtest/gtest.h"

// Helper macro to specify an EntityTestTypeTraits using EntityDef and
// ComponentDef.
#define LULL_ENTITY_TEST_TYPE(EntityDef, ComponentDef)              \
  EntityTestTypeTraits<EntityDef, ComponentDef, EntityDef##Builder, \
                       ComponentDef##Builder, ComponentDef##Type,   \
                       ComponentDef##TypeTraits,                    \
                       EnumNames##ComponentDef##Type>

namespace lull {
namespace testing {

// Container class for holding all types and functions related to an EntityDef.
// This allows the EntityDefTest to be parameterized using only 1 template
// parameter.
template <typename EntityDef, typename ComponentDef, typename EntityDefBuilder,
          typename ComponentDefBuilder, typename ComponentDefType,
          template <typename T> class ComponentDefTypeTraits,
          const char* const * (*const enum_component_names_fn)()>
class EntityTestTypeTraits {
 public:
  using entity_type = EntityDef;
  using component_type = ComponentDef;
  using entity_builder_type = EntityDefBuilder;
  using component_builder_type = ComponentDefBuilder;
  using component_union_type = ComponentDefType;

  static const char* const * component_def_type_names() {
    return enum_component_names_fn();
  }
  static const char* component_def_type_name(ComponentDefType type) {
    return enum_component_names_fn()[type];
  }

  template <typename T>
  static const ComponentDefType component_def_type_value() {
    return ComponentDefTypeTraits<T>::enum_value;
  }

  static const EntityDef* get_entity(const void* buf) {
    return flatbuffers::GetRoot<EntityDef>(buf);
  }
};

// Undefined class template that is used to force a pretty compile-time error.
template <typename TypeParam>
class ErrorMustSpecializeWithEntityTestTypeTraits;

// Base class for tests that wish to take advantage of EntityTestTypeTraits
// functionality and operate on EntityDef/ComponentDef types.
//
// Users should derive their typed Entity tests from EntityTest<TypeParam>,
// which should use the specialization defined below.
//
// Non-EntityTestTypeTraits specializations are errors, caused here by
// inheriting from an undefined class template.
template <typename TypeParam>
class EntityTest
    : public ErrorMustSpecializeWithEntityTestTypeTraits<TypeParam> {
};

// EntityTest specialization for EntityTestTypeTraits.  User tests will
// ultimately be subclasses of this specialization.
//
// Users can customize their tests by further specializing on their specific
// types using the LULL_ENTITY_TEST_TYPE macro.  Ex:
//   template <>
//   class EntityTest<LULL_ENTITY_TEST_TYPE(MyEntityDef, MyComponentDef)>
//         : public ::testing::Test {
//      protected:
//       EntityTest() { LOG(INFO) << "Testing MyEntityDef!"; }
//   };
template <typename EntityDef, typename ComponentDef, typename EntityDefBuilder,
          typename ComponentDefBuilder, typename ComponentDefType,
          template <typename T> class ComponentDefTypeTraits,
          const char* const * (*const enum_component_names_fn)()>
class EntityTest<EntityTestTypeTraits<
    EntityDef, ComponentDef, EntityDefBuilder, ComponentDefBuilder,
    ComponentDefType, ComponentDefTypeTraits, enum_component_names_fn>>
    : public ::testing::Test {
};

}  // namespace testing
}  // namespace lull

#endif  // LULLABY_TESTS_UTIL_ENTITY_TEST_H_


text:
import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'

import django
from django.conf import settings
from django.test.utils import get_runner

def runtests():
    try:
        django.setup()
    except AttributeError:
        pass
    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(["tests"])
    sys.exit(bool(failures))

if __name__ == '__main__':
    runtests()


text:
from django.contrib import admin

from job_board.models import Job, JobCategory

class JobCategoryAdmin(admin.ModelAdmin):
    search_fields = ('name',)
    prepopulated_fields = {"slug": ("name",)}
    list_display = ('name', 'description', 'slug')

class JobAdmin(admin.ModelAdmin):
    date_hierarchy = 'posted'
    search_fields = ['title', 'description']
    list_display = ['title', 'job_type', 'category', 'location',
                    'company_name', 'onsite_required', 'posted', 'viewed']
    list_filter = ['posted', 'job_type', 'category', 'onsite_required']
    fieldsets = (
        ('Job Information', {
            'fields': ('title', 'slug', 'job_type', 'category', 'description', ('location', 'onsite_required')),
        }),
        ('Company Information', {
            'fields': ('company_name', ('to_apply'), 'website'),
        }),
    )

admin.site.register(Job, JobAdmin)
admin.site.register(JobCategory, JobCategoryAdmin)


text:
@interface DHCubeTransitionRenderer ()<GLKViewDelegate> {
    GLuint srcFaceEdgeWidthLoc;
    GLuint dstFaceEdgeWidthLoc;
}
@property (nonatomic, strong) DHCubeSourceMesh *sourceMesh;
@property (nonatomic, strong) DHCubeDestinationMesh *destinationMesh;
@property (nonatomic) GLfloat edgeWidth;
@end

@implementation DHCubeTransitionRenderer
#pragma mark - Initialization
- (instancetype) init
{
    self = [super init];
    if (self) {
        self.srcVertexShaderFileName = @"CubeSourceVertex.glsl";
        self.srcFragmentShaderFileName = @"CubeSourceFragment.glsl";
        self.dstVertexShaderFileName = @"CubeDestinationVertex.glsl";
        self.dstFragmentShaderFileName = @"CubeDestinationFragment.glsl";
    }
    return self;
}

#pragma mark - Drawing
- (void) glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClear(GL_COLOR_BUFFER_BIT);

    [self setupMvpMatrixWithView:view];

    glUseProgram(dstProgram);
    glUniform1f(dstPercentLoc, self.percent);
    glUniform1f(dstFaceEdgeWidthLoc, self.edgeWidth);
    glUniform1i(dstDirectionLoc, self.direction);

    glUseProgram(srcProgram);
    glUniform1f(srcPercentLoc, self.percent);
    glUniform1f(srcFaceEdgeWidthLoc, self.edgeWidth);
    glUniform1i(srcDirectionLoc, self.direction);

    for (int i = 0; i < self.columnCount / 2; i++) {
        if (self.percent < .5) {
            [self drawDestinationFaceColumn:i inView:self.animationView];
            [self drawSourceFaceColumn:i inView:self.animationView];
        } else {
            [self drawSourceFaceColumn:i inView:self.animationView];
            [self drawDestinationFaceColumn:i inView:self.animationView];
        }
    }

    for (NSInteger i = self.columnCount; i >= self.columnCount / 2; i--) {
        if (self.percent < .5) {
            [self drawDestinationFaceColumn:i inView:self.animationView];
            [self drawSourceFaceColumn:i inView:self.animationView];
        } else {
            [self drawSourceFaceColumn:i inView:self.animationView];
            [self drawDestinationFaceColumn:i inView:self.animationView];
        }
    }
}

- (void) drawDestinationFaceColumn:(NSInteger)column inView:(GLKView *)view;
{
    glUseProgram(dstProgram);
    [self.destinationMesh prepareToDraw];
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, dstTexture);
    glUniform1i(dstSamplerLoc, 0);
    [self.destinationMesh drawColumnAtIndex:column];
}

- (void) drawSourceFaceColumn:(NSInteger)column inView:(GLKView *)view {
    glUseProgram(srcProgram);
    [self.sourceMesh prepareToDraw];
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, srcTexture);
    glUniform1i(srcSamplerLoc, 0);
    [self.sourceMesh drawColumnAtIndex:column];
}

#pragma mark - Override
- (void) setupGL
{
    [super setupGL];
    glUseProgram(srcProgram);
    srcFaceEdgeWidthLoc = glGetUniformLocation(srcProgram, "u_edgeWidth");

    glUseProgram(dstProgram);
    dstFaceEdgeWidthLoc = glGetUniformLocation(dstProgram, "u_edgeWidth");
}

- (DHSceneMesh *) srcMesh
{
    return self.sourceMesh;
}

- (DHSceneMesh *) dstMesh
{
    return self.destinationMesh;
}

- (void) setupMeshWithFromView:(UIView *)fromView toView:(UIView *)toView
{
    self.sourceMesh = [[DHCubeSourceMesh alloc] initWithView:fromView columnCount:self.columnCount transitionDirection:self.direction];
    self.destinationMesh = [[DHCubeDestinationMesh alloc] initWithView:toView columnCount:self.columnCount transitionDirection:self.direction];
}

- (void) initializeAnimationContext
{
    switch (self.direction) {
        case DHAnimationDirectionTopToBottom:
        case DHAnimationDirectionBottomToTop:
            self.edgeWidth = self.fromView.frame.size.height / self.columnCount;
            break;
        case DHAnimationDirectionLeftToRight:
        case DHAnimationDirectionRightToLeft:
            self.edgeWidth = self.fromView.frame.size.width / self.columnCount;
            break;
        default:
            break;
    }
}

- (NSArray *) allowedDirections
{
    return @[@(DHAllowedAnimationDirectionLeft), @(DHAllowedAnimationDirectionRight), @(DHAllowedAnimationDirectionTop), @(DHAllowedAnimationDirectionBottom)];
}
@end


text:
-   size of volume(performance space)
-   usually NO conductor
-   Group by number
    1.  duet
    2.  trio
    3.  quartet
    4.  quintet
-   group
    1.  string quartet
    2.  piano quartet
    3.  brass quartet
-   Frescobaldi -> Canzona detta la binanchina
    1.  violin
    2.  cornett
    3.  continup
    4.  chitarrone
    5.  harp
    6.  origan
-   Benjamin Britten
    -   young person;s guild to the orchestra
    -   variations and a fugue on a theme of henry prucell
    -   1945 film: intruments of the orchestra
    -   henry purcell, rondeau from abdelazer or the moor's revenge
    -   A-B-A-C-A (rondo)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>VO808X: Namespace Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

VO808X

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Namespace List

Namespace Members

All

Functions

Variables

Typedefs

Enumerations

Enumerator

_

a

b

c

d

e

f

g

h

i

k

l

m

n

o

p

r

s

t

u

v

w

x

- d -

DEATH_TEST_STYLE_FLAG
: gtest_help_test

DEATH_TESTS
: gtest_filter_unittest

DEBUG
: cpp.utils

default
: upload

DEFAULT_GMOCK_ROOT_DIR
: fuse_gmock_files

DEFAULT_GTEST_ROOT_DIR
: fuse_gtest_files

dest
: upload

DISABLED_TESTS
: gtest_filter_unittest

DOT_DOT_REGEX
: pump

Generated by

     1.8.11


text:
<component name="libraryTable">
  <library name="android-support-v4">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/FFmpegExample/libs/android-support-v4.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
<?php

namespace Stopsopa\UtilsBundle\Lib\Exception;

use Exception;

class UtilFormAccessorException extends Exception
{
}


text:
#ifndef V_Sweep_Matrix_Creator_h
#define V_Sweep_Matrix_Creator_h

#include "Inputs_Allowed.h"
#include "Fem_Quadrature.h"
#include "Eigen/Dense"
#include "Matrix_Construction_Exact.h"
#include "Matrix_Construction_Self_Lumping.h"
#include "Matrix_Construction_Trad_Lumping.h"

#include "Cell_Data.h"
#include "Materials.h"
#include "Temperature_Data.h"
#include "K_Intensity.h"
#include "K_Temperature.h"

#include "Intensity_Data.h"
#include "Intensity_Moment_Data.h"

#include <vector>
#include <memory>

/** @file   V_Matrix_Construction.h
  *   @author pmaginot
  *   @brief Provide a base class that constructs mass, reaction, and gradient matrices, as well as upwind vectors
  *     Concrete cases for  SELF_LUMPING , TRAD_LUMPING , and EXACT integration techniques
 */

class V_Sweep_Matrix_Creator
{
public:
  /// Only able to initialize if given an Input_Reader object
  /// constructor defined in Fem_Quadrature.cc
  V_Sweep_Matrix_Creator(const Fem_Quadrature& fem_quadrature,
    Materials& materials,
    const int n_stages,
    const double sn_w,
    const int n_l_mom,
    const Temperature_Data& t_old,
    const Intensity_Data& i_old,
    const K_Temperature& kt,
    const K_Intensity& ki,
    const Temperature_Data& t_star);

  virtual ~V_Sweep_Matrix_Creator(){}

  /** MF needs to update M, r_cv, and spectrium \f$ \sum_{g=0}^G{\mathbf{R}_{\sigma_{a,g}} \mathbf{D}_g}   \f$
    Grey needs to update M, r_cv only
  */
  virtual void update_cell_dependencies(const int cell) = 0;

  /**
    calculate \f$ \bar{\bar{\mathbf{R}}}_{\sigma_{t,g}} \f$ , the isotropic components of \f$ \vec{S}_I \f$, and
    if grey \f$ \mathbf{R}_{\sigma_{s,0}} + \bar{\bar{\nu}}\mathbf{R}_{\sigma_a} \f$ else if MF, calculate
    only \f$ \mathbf{R}_{\sigma_{s,g,0}} \f$ since the scattering source is part of the fixed point iteration
  */
  virtual void update_group_dependencies(const int grp) = 0;

    /** add in the directional dependent components into \f$ \vec{S}_I} \f$ regardless of grey or MF, the directional components are:
    \f[
      \frac{1}{c\Delta a_{ii} } \mathbf{M} \vec{I}_{n,dir,g} + \frac{1}{c a_{ii} }\mathbf{M}
        \sum_{j=1}^{\text{stage} - 1}{a_{ij} \vec{k}_{I,j,dir,grp} }
    \f]
    /// this could alternatively be called update_direction_dependencies, with a get_s_i() function added in above...
  */
  virtual void update_direction_dependencies(const int dir) = 0;

  void construct_l_matrix(const double mu, Eigen::MatrixXd& l_matrix);

  void construct_f_vector(const double mu, Eigen::VectorXd& f_vector);

  /// SDRIK relevant time data (dt doesn't change at different stages, but let's keep it simple)
  void set_time_data( const double dt, const double time_stage, const std::vector<double>& rk_a_of_stage_i, const int stage );

  /// retrieve the already constructed \f$ \bar{\bar{\mathbf{R}}}_{\sigma_{t,g}} \f$.  Constructed in \fn update_group_dependencies
  void get_r_sig_t(Eigen::MatrixXd& r_sig_t) const;

  /** if grey and l_mom = 0, retireve \f$ \mathbf{R}_{\sigma_{s,0}} + \bar{\bar{\nu}}\mathbf{R}_{\sigma_a} \f$, else retrieve
    \f$ \mathbf{R}_{\sigma_{s,g,\text{l_mom}}} \f$ . Matrix created in \fn update_group_dependencies
  */
  void get_r_sig_s(Eigen::MatrixXd& r_sig_s, const int l_mom) const;

  void get_s_i(Eigen::VectorXd& s_i) const;

  void get_mass_inverse(Eigen::MatrixXd& m_inv) const;

  void set_ard_phi_ptr(Intensity_Moment_Data* ard_phi_ptr);

  /// used only by Solution_Saver_K_I
  void calculate_k_i_quantities(void);
  void k_i_get_r_sig_a(Eigen::MatrixXd& r_sig_a) const;
  void k_i_get_r_sig_s_zero(Eigen::MatrixXd& r_sig_s_zero) const;
  void k_i_get_r_sig_t(Eigen::MatrixXd& r_sig_t) const;
  void k_i_get_s_i(Eigen::VectorXd& s_i) const;
  void k_i_get_planck_vec(Eigen::VectorXd& planck) const;

  void get_xi_isotropic(Eigen::VectorXd& xi) const { xi = m_xi_isotropic; return; }

  bool check_all_v_sweep_eigen_variables_for_finite(void);

  void get_mass(Eigen::MatrixXd& mass) const { mass = m_dx_div_2_mass;}

protected:
  /** ****************************************************************
    * Variables that are initialzed in the constructor initialization list
    ****************************************************************
   */
   const MATRIX_INTEGRATION m_matrix_type;

  /// constants needed to build things
  const double m_sn_w; /// needed here to build source terms in linearization
  const int m_n_l_mom;
  const int m_np; /// needed to know the length/size of vectors/matrices

  /// matrices/vectors that hold sweep matrices (end results after calculating linearization, time dependence quantities)
  Eigen::MatrixXd m_r_sig_t;
  std::vector<Eigen::MatrixXd> m_r_sig_s;
  Eigen::VectorXd m_s_i;

  /// matrices needed when calculating k_i
  Eigen::MatrixXd m_k_i_r_sig_t;
  Eigen::MatrixXd m_k_i_r_sig_s_zero;

  /// quantities commonly used in linearization definitions
  /// \f$ \mathbf{R}_{\sigma_{a,g}} \f$ evaluated at t_star
  Eigen::MatrixXd m_r_sig_a;
  /// \f$ \mathbf{I} \f$
  const Eigen::MatrixXd m_identity_matrix;
  /// will actually store the inverse, \f$ \mathbf{R}_{C_v}^{-1} \f$
  Eigen::MatrixXd m_r_cv;
  /// \f$ \mathbf{D}_g \f$
  Eigen::MatrixXd m_d_matrix;
  /**
    \f[
      \text{m_coefficient} = \left[ \mathbf{I} + \text{m_sn_w} \Delta t a_{ii} \mathbf{R}_{C_v}^{-1} \mathbf{R}_{\sigma_{a,g}} \mathbf{D} \right]
    \f]
  */
  Eigen::MatrixXd m_coefficient;

  /// \f$ \mathbf{M} \f$ without \f$ \frac{\Delta x}{2} \f$ term
  Eigen::MatrixXd m_mass;
  /// scaled mass matrix
  Eigen::MatrixXd m_dx_div_2_mass;
  /// inverse of scaled mass matrix
  Eigen::MatrixXd m_mass_inv;

   /// isotropic component of xi_i
  Eigen::VectorXd m_xi_isotropic;
  /// holding source moments (S_T and S_I)
  Eigen::VectorXd m_driving_source;

  /// local vectors of respective Data objects
  Eigen::VectorXd m_t_old_vec;
  Eigen::VectorXd m_t_star_vec;
  Eigen::VectorXd m_k_vec;
  Eigen::VectorXd m_planck_vec;
  Eigen::VectorXd m_temp_vec;

  /// gradient matrices/vectors that are not changed during the sweep process
  /// Passed to Matrix_Construction_Objects at construction, then not modified after that
  Eigen::MatrixXd m_no_mu_pos_l_matrix;
  Eigen::MatrixXd m_no_mu_neg_l_matrix;
  Eigen::VectorXd m_no_mu_pos_f_vector;
  Eigen::VectorXd m_no_mu_neg_f_vector;

  /** can't be const Materials* because when we call for a material property at DFEM integration points, we modify the scratch vector
    m_ that is a member of the Materials object...  but we don't ever want to be able to change this pointer!
  */
  Materials& m_materials;

  const double m_c;

  /// time stepping data that will be used/changed during the search for each intensity
  double m_dt;
  int m_stage;
  double m_time;

  /// pointers that will not change during a problem, and are used regardless of frequency treatment.
  const Temperature_Data& m_t_old_ref;
  const Intensity_Data& m_i_old_ref;
  const K_Temperature& m_kt_ref;
  const K_Intensity& m_ki_ref;

  /// cell data that is used repeatedly (set in V_Sweep_Matrix_Creator::update_cell_dependencies() )
  double m_dx;
  int m_cell_num;

  /// could potentially change, though unlikely...
  const Temperature_Data& m_t_star_ref;
  /// used only by MF, but needs to be available to any V_Sweep_Matrix_Creator object since it is called by a
  /// shared_ptr<V_Sweep_Matrix_Creator>
  Intensity_Moment_Data* m_ard_phi_ptr;

  /// vector of length n_stages that will old the rk_a data (changed at each time step stage)
  std::vector<double> m_rk_a;

  /** ****************************************************************
    * Variables that are initialzed in the constructor body
    **************************************************************** */

  /// builder/lumper of matrices
  std::shared_ptr<V_Matrix_Construction> m_mtrx_builder;

};

#endif


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: oneview_enclosure_facts
short_description: Retrieve facts about one or more Enclosures
description:
    - Retrieve facts about one or more of the Enclosures from OneView.
version_added: "2.5"
requirements:
    - hpOneView >= 2.0.1
author:
    - Felipe Bulsoni (@fgbulsoni)
    - Thiago Miotto (@tmiotto)
    - Adriane Cardozo (@adriane-cardozo)
options:
    name:
      description:
        - Enclosure name.
    options:
      description:
        - "List with options to gather additional facts about an Enclosure and related resources.
          Options allowed: C(script), C(environmentalConfiguration), and C(utilization). For the option C(utilization),
          you can provide specific parameters."

extends_documentation_fragment:
    - oneview
    - oneview.factsparams
'''

EXAMPLES = '''
- name: Gather facts about all Enclosures
  oneview_enclosure_facts:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
  no_log: true
  delegate_to: localhost
- debug: var=enclosures

- name: Gather paginated, filtered and sorted facts about Enclosures
  oneview_enclosure_facts:
    params:
      start: 0
      count: 3
      sort: name:descending
      filter: status=OK
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
  no_log: true
  delegate_to: localhost
- debug: var=enclosures

- name: Gather facts about an Enclosure by name
  oneview_enclosure_facts:
    name: Enclosure-Name
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
  no_log: true
  delegate_to: localhost
- debug: var=enclosures

- name: Gather facts about an Enclosure by name with options
  oneview_enclosure_facts:
    name: Test-Enclosure
    options:
      - script                       # optional
      - environmentalConfiguration   # optional
      - utilization                  # optional
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
  no_log: true
  delegate_to: localhost
- debug: var=enclosures
- debug: var=enclosure_script
- debug: var=enclosure_environmental_configuration
- debug: var=enclosure_utilization

- name: "Gather facts about an Enclosure with temperature data at a resolution of one sample per day, between two
         specified dates"
  oneview_enclosure_facts:
    name: Test-Enclosure
    options:
      - utilization:                   # optional
          fields: AmbientTemperature
          filter:
            - startDate=2016-07-01T14:29:42.000Z
            - endDate=2017-07-01T03:29:42.000Z
          view: day
          refresh: false
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
  no_log: true
  delegate_to: localhost
- debug: var=enclosures
- debug: var=enclosure_utilization
'''

RETURN = '''
enclosures:
    description: Has all the OneView facts about the Enclosures.
    returned: Always, but can be null.
    type: dict

enclosure_script:
    description: Has all the OneView facts about the script of an Enclosure.
    returned: When requested, but can be null.
    type: str

enclosure_environmental_configuration:
    description: Has all the OneView facts about the environmental configuration of an Enclosure.
    returned: When requested, but can be null.
    type: dict

enclosure_utilization:
    description: Has all the OneView facts about the utilization of an Enclosure.
    returned: When requested, but can be null.
    type: dict
'''

from ansible.module_utils.oneview import OneViewModuleBase

class EnclosureFactsModule(OneViewModuleBase):
    argument_spec = dict(name=dict(type='str'), options=dict(type='list'), params=dict(type='dict'))

    def __init__(self):
        super(EnclosureFactsModule, self).__init__(additional_arg_spec=self.argument_spec)

    def execute_module(self):

        ansible_facts = {}

        if self.module.params['name']:
            enclosures = self._get_by_name(self.module.params['name'])

            if self.options and enclosures:
                ansible_facts = self._gather_optional_facts(self.options, enclosures[0])
        else:
            enclosures = self.oneview_client.enclosures.get_all(**self.facts_params)

        ansible_facts['enclosures'] = enclosures

        return dict(changed=False,
                    ansible_facts=ansible_facts)

    def _gather_optional_facts(self, options, enclosure):

        enclosure_client = self.oneview_client.enclosures
        ansible_facts = {}

        if options.get('script'):
            ansible_facts['enclosure_script'] = enclosure_client.get_script(enclosure['uri'])
        if options.get('environmentalConfiguration'):
            env_config = enclosure_client.get_environmental_configuration(enclosure['uri'])
            ansible_facts['enclosure_environmental_configuration'] = env_config
        if options.get('utilization'):
            ansible_facts['enclosure_utilization'] = self._get_utilization(enclosure, options['utilization'])

        return ansible_facts

    def _get_utilization(self, enclosure, params):
        fields = view = refresh = filter = ''

        if isinstance(params, dict):
            fields = params.get('fields')
            view = params.get('view')
            refresh = params.get('refresh')
            filter = params.get('filter')

        return self.oneview_client.enclosures.get_utilization(enclosure['uri'],
                                                              fields=fields,
                                                              filter=filter,
                                                              refresh=refresh,
                                                              view=view)

    def _get_by_name(self, name):
        return self.oneview_client.enclosures.get_by('name', name)

def main():
    EnclosureFactsModule().run()

if __name__ == '__main__':
    main()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
javacardx.framework.math (Java Card API, Connected Edition)
</TITLE>

<META NAME="date" CONTENT="2009-12-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

javacardx.framework.math

Classes

BCDUtil

BigNumber

ParityBit


text:
<?php

namespace app\controllers;

use app\models as Model;
use Ocrend\Kernel\Router\RouterInterface;
use Ocrend\Kernel\Controllers\Controllers;
use Ocrend\Kernel\Controllers\ControllersInterface;

/**
 * Controlador contact/
 *
 * @author DevSystemVzla <devsystemvzla@gmail.com>
*/

class contactController extends Controllers implements ControllersInterface {

    public function __construct(RouterInterface $router) {
        parent::__construct($router);
        // Contenido del controlador...
		echo $this->template->render('contact/contact',array(
			'contact' => (new Model\Contact)->getContactInfo()
		));

    }

}


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

import tiger.GenerationTriggerAnnotation;

/**
 * Convenient help class for build targets to include in srcs to trigger
 * {@link tiger.ComponentGeneratorProcessor}.
 */
@GenerationTriggerAnnotation
public class GenerationTrigger {}


text:
@implementation DFMHotChannelsEntity

+ (NSDictionary *)objectClassInArray
{
    return @{
             @"channels" : NSStringFromClass([ChannelInfo class]),
             };
}

@end


text:
const remark = require('remark')
const refLinks = require('remark-reference-links')
const inlineLinks = require('remark-inline-links')
import { Format, VFile }  from './interfaces'

export const parser = async(md:string, format:Format) => {
    const style = format === 'inline' ? inlineLinks : refLinks
    const res:VFile = await remark().use(style).process(md)
    return res.contents
}

export const formd = async(md:any, format:Format) => {
  parser(md,format)
    .then(res => console.log(res))
}


text:
<?php

namespace com\xcitestudios\Network\Email\Interfaces;

use com\xcitestudios\Generic\Data\Manipulation\Interfaces\SerializationInterface;

/**
 * Interface for an email that is serializable.
 *
 * @package com.xcitestudios.Network
 * @subpackage Email.Interfaces
 */
interface EmailSerializableInterface
    extends EmailInterface, SerializationInterface
{
}


text:
package org.acre.visualizer.graph.popup;

import org.acre.visualizer.graph.AcreGraph;
import org.acre.visualizer.graph.edges.AcreEdge;
import org.acre.visualizer.graph.pdmresult.edges.RoleResultToRoleResultEdge;
import org.acre.visualizer.graph.vertex.AcreVertex;

import java.awt.event.ActionEvent;

/**
 * @author Deepak.Alur@Sun.com
 * @version Dec 22, 2004 10:55:16 PM
 */
public class RoleResultToRoleResultEdgePopup extends GraphPopup {

    public RoleResultToRoleResultEdgePopup(AcreGraph graph,
                                         RoleResultToRoleResultEdge roleResultToRoleResultEdge) {
        super(graph, roleResultToRoleResultEdge, "Role Result Relationship");
    }

    // subclasses to override this method if needed
    protected void handleEdgeAction(ActionEvent e, GraphPopup popup, AcreGraph graph, AcreEdge edge) {
        // todo - implemented method body
        showFeatureNotImplemented();
    }

    // subclasses to override this method if needed
    protected void handleVertexAction(ActionEvent e, GraphPopup popup, AcreGraph graph, AcreVertex vertex) {
        // do nothing
    }

    protected void initializeMenus() {
        // todo - implemented method body
    }
}


text:
declare type ReplaceableForEachCallBack = (value: unknown, key: unknown, object: unknown) => void;
export default class Replaceable {
    object: any;
    type: string;
    constructor(object: any);
    static isReplaceable(obj1: unknown, obj2: unknown): boolean;
    forEach(cb: ReplaceableForEachCallBack): void;
    get(key: any): any;
    set(key: any, value: any): void;
}
export {};


text:
package gemlite.core.internal.context.registryClass;

import gemlite.core.commands.DataStore;
import gemlite.core.internal.support.annotations.GemliteRegistry;
import gemlite.core.internal.support.context.IModuleContext;
import gemlite.core.internal.support.context.RegistryParam;
import gemlite.core.internal.support.events.GemliteEvent;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;

/***
 * regionName -> index tool 1,index tool2
 *
 * @author ynd
 *
 */

@GemliteRegistry(value=ApplicationListener.class)
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ApplicationListenerRegistry extends AbstractGemliteRegistry
{
  private List<ApplicationListener> listeners = new ArrayList<>();

  @Override
  protected void doRegistry(IModuleContext context, RegistryParam param) throws Exception
  {
    String className = param.getClassName();
    Class<ApplicationListener<GemliteEvent>> cls = (Class<ApplicationListener<GemliteEvent>>) context.getLoader()
        .loadClass(className);
    ApplicationListener listener = cls.newInstance();
    listeners.add(listener);
    if (getApplicationEventMulticaster() != null)
      getApplicationEventMulticaster().addApplicationListener(listener);
  }

  private synchronized ApplicationEventMulticaster getApplicationEventMulticaster()
  {
    try
    {
      Field field = DataStore.class.getDeclaredField("mainContext");
      field.setAccessible(true);
      AbstractApplicationContext ctx = (AbstractApplicationContext) field.get(DataStore.getInstance());
      if (ctx == null)
        return null;
      Method m = AbstractApplicationContext.class.getDeclaredMethod("getApplicationEventMulticaster");
      m.setAccessible(true);
      ApplicationEventMulticaster eventCaster = (ApplicationEventMulticaster) m.invoke(ctx);
      field.setAccessible(false);
      m.setAccessible(false);
      return eventCaster;
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public void cleanAll()
  {
    for (ApplicationListener l : listeners)
    {
      getApplicationEventMulticaster().removeApplicationListener(l);
    }

  }

  @Override
  public Object getItem(Object key)
  {
    return null;
  }
}


text:
namespace mojo {
namespace runner {

ChildProcessHost::ChildProcessHost(Context* context,
                                   bool start_sandboxed,
                                   const base::FilePath& app_path)
    : context_(context),
      start_sandboxed_(start_sandboxed),
      app_path_(app_path),
      channel_info_(nullptr) {
  platform_channel_ = platform_channel_pair_.PassServerHandle();
  CHECK(platform_channel_.is_valid());
}

ChildProcessHost::~ChildProcessHost() {
  if (child_process_.IsValid()) {
    LOG(WARNING) << "Destroying ChildProcessHost with unjoined child";
    child_process_.Close();
  }
}

void ChildProcessHost::Start() {
  DCHECK(!child_process_.IsValid());
  DCHECK(platform_channel_.is_valid());

  ScopedMessagePipeHandle handle(embedder::CreateChannel(
      platform_channel_.Pass(),
      base::Bind(&ChildProcessHost::DidCreateChannel, base::Unretained(this)),
      base::ThreadTaskRunnerHandle::Get()));

  controller_.Bind(InterfacePtrInfo<ChildController>(handle.Pass(), 0u));

  CHECK(base::PostTaskAndReplyWithResult(
      context_->task_runners()->blocking_pool(), FROM_HERE,
      base::Bind(&ChildProcessHost::DoLaunch, base::Unretained(this)),
      base::Bind(&ChildProcessHost::DidStart, base::Unretained(this))));
}

int ChildProcessHost::Join() {
  DCHECK(child_process_.IsValid());
  int rv = -1;
  LOG_IF(ERROR, !child_process_.WaitForExit(&rv))
      << "Failed to wait for child process";
  child_process_.Close();
  return rv;
}

void ChildProcessHost::StartApp(
    InterfaceRequest<Application> application_request,
    const ChildController::StartAppCallback& on_app_complete) {
  DCHECK(controller_);

  on_app_complete_ = on_app_complete;
  controller_->StartApp(
      application_request.Pass(),
      base::Bind(&ChildProcessHost::AppCompleted, base::Unretained(this)));
}

void ChildProcessHost::ExitNow(int32_t exit_code) {
  DCHECK(controller_);

  controller_->ExitNow(exit_code);
}

void ChildProcessHost::DidStart(bool success) {
  DVLOG(2) << "ChildProcessHost::DidStart()";

  if (!success) {
    LOG(ERROR) << "Failed to start child process";
    AppCompleted(MOJO_RESULT_UNKNOWN);
    return;
  }
}

bool ChildProcessHost::DoLaunch() {
  const base::CommandLine* parent_command_line =
      base::CommandLine::ForCurrentProcess();
  base::CommandLine child_command_line(parent_command_line->GetProgram());
  child_command_line.AppendArguments(*parent_command_line, false);
  child_command_line.AppendSwitchPath(switches::kChildProcess, app_path_);

  if (start_sandboxed_)
    child_command_line.AppendSwitch(switches::kEnableSandbox);

  embedder::HandlePassingInformation handle_passing_info;
  platform_channel_pair_.PrepareToPassClientHandleToChildProcess(
      &child_command_line, &handle_passing_info);

  base::LaunchOptions options;
#if defined(OS_WIN)
  options.handles_to_inherit = &handle_passing_info;
#elif defined(OS_POSIX)
  handle_passing_info.push_back(std::make_pair(STDIN_FILENO, STDIN_FILENO));
  handle_passing_info.push_back(std::make_pair(STDOUT_FILENO, STDOUT_FILENO));
  handle_passing_info.push_back(std::make_pair(STDERR_FILENO, STDERR_FILENO));
  options.fds_to_remap = &handle_passing_info;
#endif
  DVLOG(2) << "Launching child with command line: "
           << child_command_line.GetCommandLineString();
#if defined(OS_LINUX) && !defined(OS_ANDROID)
  if (start_sandboxed_) {
    child_process_ =
        sandbox::NamespaceSandbox::LaunchProcess(child_command_line, options);
    if (!child_process_.IsValid()) {
      LOG(ERROR) << "Starting the process with a sandbox failed. Missing kernel"
                 << " support.";
      return false;
    }
  } else
#endif
    child_process_ = base::LaunchProcess(child_command_line, options);

  if (!child_process_.IsValid())
    return false;

  platform_channel_pair_.ChildProcessLaunched();
  return true;
}

void ChildProcessHost::AppCompleted(int32_t result) {
  if (!on_app_complete_.is_null()) {
    auto on_app_complete = on_app_complete_;
    on_app_complete_.reset();
    on_app_complete.Run(result);
  }
}

void ChildProcessHost::DidCreateChannel(embedder::ChannelInfo* channel_info) {
  DVLOG(2) << "AppChildProcessHost::DidCreateChannel()";

  CHECK(channel_info);
  channel_info_ = channel_info;
}

}  // namespace runner
}  // namespace mojo


text:
function changeTab(tab, action) {
    port.postMessage({
        tab: parseInt(tab),
        action: action
    });
}

function tabScroll(e) {
    var tabs = document.querySelector('#tabs');
    var active = document.querySelector('.active');
    var tabId = 0;
    if (e.wheelDelta > 0) {
        if (active.previousSibling != null) {
            tabId = active.previousSibling.dataset.id;
        } else {
            tabId = tabs.children[tabs.children.length - 1].dataset.id;
        }
    } else if (e.wheelDelta < 0) {
        if (active.nextSibling != null) {
            tabId = active.nextSibling.dataset.id;
        } else {
            tabId = tabs.children[0].dataset.id;
        }
    }
    changeTab(tabId, 'activate');
    return false;
}

function updateTabs(data) {
    var tabs = document.querySelector('#tabs');
    tabs.innerHTML = data.tabs;
    for (var i = 0; i < tabs.children.length; i++) {
        if (tabs.children[i].dataset.id == data.tabId) {
            tabs.children[i].className += ' active';
        }
        tabs.children[i].onclick = function(e) {
            changeTab(this.dataset.id, e.button == 1 ? 'close' : 'activate');
        };
        tabs.onmousewheel = tabScroll;
    }
}

var port = chrome.runtime.connect({name: 'tabs'});
port.onMessage.addListener(updateTabs);


text:
/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * JSONInstances.java
 * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
 */

package weka.core.json;

import java.util.ArrayList;

import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.core.converters.ConverterUtils.DataSource;

/**
 * Class for transforming Instances objects into JSON
 * objects and vice versa. Missing values get stored as "?".
 *
 * @author  FracPete (fracpete at waikato dot ac dot nz)
 * @version $Revision: 9664 $
 * @see #MISSING_VALUE
 */
public class JSONInstances {

  /** the header section. */
  public final static String HEADER = "header";

  /** the data section. */
  public final static String DATA = "data";

  /** the relation name. */
  public final static String RELATION = "relation";

  /** the attributes object. */
  public final static String ATTRIBUTES = "attributes";

  /** the name attribute. */
  public final static String NAME = "name";

  /** the type attribute. */
  public final static String TYPE = "type";

  /** the class attribute indicator. */
  public final static String CLASS = "class";

  /** the labels attribute. */
  public final static String LABELS = "labels";

  /** the weight attribute. */
  public final static String WEIGHT = "weight";

  /** the dateformat attribute. */
  public final static String DATEFORMAT = "dateformat";

  /** the sparse attribute. */
  public final static String SPARSE = "sparse";

  /** the values attribute. */
  public final static String VALUES = "values";

  /** the separator for index/value in case of sparse instances. */
  public final static String SPARSE_SEPARATOR = ":";

  /** the missing value indicator. */
  public final static String MISSING_VALUE = "?";

  /**
   * Turns the JSON object into an Attribute, if possible.
   *
   * @param att		the JSON object to turn into an Attribute
   * @param classAtt	for storing whether the attribute is the class attribute
   * @return		the Attribute, null in case of an error
   */
  protected static Attribute toAttribute(JSONNode att, boolean[] classAtt) {
    Attribute		result;
    String		name;
    String		type;
    String		dateformat;
    JSONNode		labels;
    ArrayList<String>	values;
    String		label;
    int			i;
    double		weight;

    name   = (String) att.getChild(NAME).getValue("noname");
    type   = (String) att.getChild(TYPE).getValue("");
    weight = (Double) att.getChild(WEIGHT).getValue(new Double(1.0));
    if (type.equals(Attribute.typeToString(Attribute.NUMERIC))) {
      result = new Attribute(name);
    }
    else if (type.equals(Attribute.typeToString(Attribute.NOMINAL))) {
      labels = att.getChild(LABELS);
      values = new ArrayList<String>();
      for (i = 0; i < labels.getChildCount(); i++) {
	label = (String)((JSONNode) labels.getChildAt(i)).getValue();
	if (label.equals("'" + MISSING_VALUE + "'"))
	  values.add(MISSING_VALUE);
	else
	  values.add(label);
      }
      result = new Attribute(name, values);
    }
    else if (type.equals(Attribute.typeToString(Attribute.DATE))) {
      dateformat = (String) att.getChild(DATEFORMAT).getValue("yyyy-MM-dd'T'HH:mm:ss");
      result     = new Attribute(name, dateformat);
    }
    else if (type.equals(Attribute.typeToString(Attribute.STRING))) {
      result = new Attribute(name, (ArrayList<String>) null);
    }
    else {
      System.err.println("Unhandled attribute type '" + type + "'!");
      return null;
    }
    result.setWeight(weight);

    return result;
  }

  /**
   * Turns the JSON Object into an Instance, if possible.
   *
   * @param inst	the JSON object to turn into an Instance
   * @param data	the data so far (only used for header information)
   * @return		the Instance, null in case of an error
   */
  protected static Instance toInstance(JSONNode inst, Instances data) {
    Instance	result;
    boolean	sparse;
    double	weight;
    JSONNode	values;
    int		i;
    int		index;
    int		pos;
    String	value;
    double[]	vals;

    sparse = (Boolean) inst.getChild(SPARSE).getValue(new Boolean(false));
    weight = (Double) inst.getChild(WEIGHT).getValue(new Double(1.0));
    values = inst.getChild(VALUES);
    vals   = new double[data.numAttributes()];
    for (i = 0; i < values.getChildCount(); i++) {
      if (sparse) {
	value = "" + ((JSONNode) values.getChildAt(i)).getValue();
	pos   = value.indexOf(SPARSE_SEPARATOR);
	index = Integer.parseInt(value.substring(0, pos));
	value = value.substring(pos + 1);
      }
      else {
	index = i;
	value = "" + ((JSONNode) values.getChildAt(i)).getValue();
      }

      try {
	if (value.equals(MISSING_VALUE)) {
	  vals[index] = Utils.missingValue();
	}
	else {
	  // unescape '?' labels
	  if (value.equals("'" + MISSING_VALUE + "'"))
	    value = MISSING_VALUE;
	  if (data.attribute(index).isNumeric() && !data.attribute(index).isDate()) {
	    vals[index] = Double.parseDouble(value);
	  }
	  else if (data.attribute(index).isNominal()) {
	    vals[index] = data.attribute(index).indexOfValue(value);
	    if ((vals[index] == -1) && value.startsWith("'") && value.endsWith("'"))
	      vals[index] = data.attribute(index).indexOfValue(Utils.unquote(value));
	    // FIXME backslashes seem to get escaped twice when creating a JSON file?
	    if ((vals[index] == -1) && value.startsWith("'") && value.endsWith("'"))
	      vals[index] = data.attribute(index).indexOfValue(Utils.unbackQuoteChars(Utils.unquote(value)));
	    if (vals[index] == -1) {
	      System.err.println("Unknown label '" + value + "' for attribute #" + (index+1) + "!");
	      return null;
	    }
	  }
	  else if (data.attribute(index).isDate()) {
	    vals[index] = data.attribute(index).parseDate(value);
	  }
	  else if (data.attribute(index).isString()) {
	    vals[index] = data.attribute(index).addStringValue(value);
	  }
	  else {
	    System.err.println("Unhandled attribute type '" + Attribute.typeToString(data.attribute(index).type()) + "'!");
	    return null;
	  }
	}
      }
      catch (Exception e) {
	System.err.println("Error parsing value #" + (index+1) + ": " + e.toString());
	return null;
      }
    }

    if (sparse)
      result = new SparseInstance(weight, vals);
    else
      result = new DenseInstance(weight, vals);
    result.setDataset(data);

    return result;
  }

  /**
   * Turns a JSON object, if possible, into an Instances object.
   *
   * @param json	the JSON object to convert
   * @param onlyHeader	whether to retrieve only the header
   * @return		the generated Instances object, null if not possible
   */
  protected static Instances toInstances(JSONNode json, boolean onlyHeader) {
    Instances	result;
    JSONNode	header;
    JSONNode	attributes;
    JSONNode	data;
    ArrayList<Attribute>	atts;
    Attribute	att;
    Instance	inst;
    int		i;
    int		classIndex;
    boolean[]	classAtt;

    header = json.getChild(HEADER);
    if (header == null) {
      System.err.println("No '" + HEADER + "' section!");
      return null;
    }
    data = json.getChild(DATA);
    if (data == null) {
      System.err.println("No '" + DATA + "' section!");
      return null;
    }

    // attributes
    attributes = header.getChild(ATTRIBUTES);
    if (attributes == null) {
      System.err.println("No '" + ATTRIBUTES + "' array!");
      return null;
    }
    atts       = new ArrayList<Attribute>();
    classAtt   = new boolean[1];
    classIndex = -1;
    for (i = 0; i < attributes.getChildCount(); i++) {
      att = toAttribute((JSONNode) attributes.getChildAt(i), classAtt);
      if (att == null) {
	System.err.println("Could not convert attribute #" + (i+1) + "!");
	return null;
      }
      if (classAtt[0])
	classIndex = i;
      atts.add(att);
    }
    result = new Instances(
	header.getChild(RELATION).getValue("unknown").toString(),
	atts,
	(onlyHeader ? 0 : data.getChildCount()));
    result.setClassIndex(classIndex);

    // data
    if (!onlyHeader) {
      for (i = 0; i < data.getChildCount(); i++) {
	inst = toInstance((JSONNode) data.getChildAt(i), result);
	if (inst == null) {
	  System.err.println("Could not convert instance #" + (i+1) + "!");
	  return null;
	}
	result.add(inst);
      }
    }

    return result;
  }

  /**
   * Turns a JSON object, if possible, into an Instances object.
   *
   * @param json	the JSON object to convert
   * @return		the generated Instances object, null if not possible
   */
  public static Instances toInstances(JSONNode json) {
    return toInstances(json, false);
  }

  /**
   * Turns a JSON object, if possible, into an Instances object (only header).
   *
   * @param json	the JSON object to convert
   * @return		the generated Instances header object, null if not possible
   */
  public static Instances toHeader(JSONNode json) {
    return toInstances(json, true);
  }

  /**
   * Turns the Attribute into a JSON object.
   *
   * @param inst	the corresponding dataset
   * @param att		the attribute to convert
   * @return		the JSON object
   */
  protected static JSONNode toJSON(Instances inst, Attribute att) {
    JSONNode	result;
    JSONNode	labels;
    int		i;

    result = new JSONNode();

    result.addPrimitive(NAME, att.name());
    result.addPrimitive(TYPE, Attribute.typeToString(att));
    result.addPrimitive(CLASS, (att.index() == inst.classIndex()));
    result.addPrimitive(WEIGHT, att.weight());
    if (att.isNominal()) {
      labels = result.addArray(LABELS);
      for (i = 0; i < att.numValues(); i++) {
	if (att.value(i).equals(MISSING_VALUE))
	  labels.addArrayElement("'" + att.value(i) + "'");
	else
	  labels.addArrayElement(att.value(i));
      }
    }
    if (att.isDate())
      result.addPrimitive(DATEFORMAT, att.getDateFormat());

    return result;
  }

  /**
   * Turns the Instance into a JSON object.
   *
   * @param inst	the Instance to convert
   * @return		the JSON object
   */
  protected static JSONNode toJSON(Instance inst) {
    JSONNode	result;
    JSONNode	values;
    int		i;
    boolean	sparse;

    result = new JSONNode();

    sparse = (inst instanceof SparseInstance);
    result.addPrimitive(SPARSE, sparse);
    result.addPrimitive(WEIGHT, inst.weight());
    values = result.addArray(VALUES);
    if (sparse) {
      for (i = 0; i < inst.numValues(); i++) {
	if (inst.isMissing(inst.index(i)))
	  values.addArrayElement(inst.index(i) + SPARSE_SEPARATOR + MISSING_VALUE);
	else if (inst.toString(inst.index(i)).equals("'" + MISSING_VALUE + "'"))
	  values.addArrayElement(inst.index(i) + SPARSE_SEPARATOR + "'" + MISSING_VALUE + "'");  // escape '?' labels
	else
	  values.addArrayElement(inst.index(i) + SPARSE_SEPARATOR + inst.toString(inst.index(i)));
      }
    }
    else {
      for (i = 0; i < inst.numAttributes(); i++) {
	if (inst.isMissing(i))
	  values.addArrayElement(MISSING_VALUE);
	else if (inst.toString(i).equals("'" + MISSING_VALUE + "'"))
	  values.addArrayElement("'" + MISSING_VALUE + "'");  // escape '?' labels
	else
	  values.addArrayElement(inst.toString(i));
      }
    }

    return result;
  }

  /**
   * Turns the Instances object into a JSON object.
   *
   * @param inst	the Instances to turn into a JSON object
   * @return		the JSON object
   */
  public static JSONNode toJSON(Instances inst) {
    JSONNode	result;
    JSONNode	header;
    JSONNode	atts;
    JSONNode	data;
    int		i;

    result = new JSONNode();

    // header
    header = result.addObject(HEADER);
    header.addPrimitive(RELATION, inst.relationName());
    atts = header.addArray(ATTRIBUTES);
    for (i = 0; i < inst.numAttributes(); i++)
      atts.add(toJSON(inst, inst.attribute(i)));

    // data
    data = result.addArray(DATA);
    for (i = 0; i < inst.numInstances(); i++)
      data.add(toJSON(inst.instance(i)));

    return result;
  }

  /**
   * For testing only.
   *
   * @param args	expects a dataset as first parameter
   * @throws Exception	if something goes wrong
   */
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("No dataset supplied!");
      System.exit(1);
    }

    // load dataset
    Instances data = DataSource.read(args[0]);

    // turn Instances into JSON object and output it
    JSONNode json = toJSON(data);
    StringBuffer buffer = new StringBuffer();
    json.toString(buffer);
    System.out.println(buffer.toString());

    // turn JSON object back into Instances and output it
    Instances inst = toInstances(json);
    System.out.println(inst);
  }
}


text:
<?xml version='1.0'?>
<sales xmlns:HTML="http://www.w3.org/Profiles/XHTML-transitional">
    <product id='Travel'>
        <revenue>60</revenue>
        <growth>8</growth>
    </product>
    <product id='Communications'>
        <revenue>45</revenue>
        <growth>-7.8</growth>
    </product>
    <product id='Deception'>
        <revenue>10</revenue>
        <growth>9</growth>
    </product>
    <product id='Munitions'>
        <revenue>4</revenue>
        <growth>-3</growth>
    </product>
</sales>


text:
namespace DotSpatial.Data
{
    /// <summary>
    /// An interface for sending progress messages. Percent is an integer from 0 to 100.
    /// </summary>
    public interface IProgressHandler
    {
        /// <summary>
        /// Progress is the method that should receive a progress message.
        /// </summary>
        /// <param name="key">The message string without any information about the status of completion.</param>
        /// <param name="percent">An integer from 0 to 100 that indicates the condition for a status bar etc.</param>
        /// <param name="message">A string containing both information on what the process is, as well as its completion status.</param>
        void Progress(string key, int percent, string message);
    }
}


text:
#ifndef CachedSVGDocumentReference_h
#define CachedSVGDocumentReference_h

#if ENABLE(SVG) && ENABLE(CSS_FILTERS)

#include "CachedResourceHandle.h"
#include "CachedSVGDocumentClient.h"

namespace WebCore {

class CachedSVGDocument;

class CachedSVGDocumentReference : public CachedSVGDocumentClient {
public:
    CachedSVGDocumentReference(CachedSVGDocument*);
    virtual ~CachedSVGDocumentReference();
    CachedSVGDocument* document() { return m_document.get(); }

private:
    CachedResourceHandle<CachedSVGDocument> m_document;
};

};

#endif // ENABLE(SVG) && ENABLE(CSS_FILTERS)

#endif // CachedSVGDocumentReference_h