text:
package main.swapship.factories;

import main.swapship.GameInfo.Level;
import main.swapship.common.Constants;
import main.swapship.common.DefensiveSpecialType;
import main.swapship.common.OffensiveSpecialType;
import main.swapship.components.DamageComp;
import main.swapship.components.FireRateComp;
import main.swapship.components.HealthComp;
import main.swapship.components.LevelComp;
import main.swapship.components.NonCullComp;
import main.swapship.components.SpatialComp;
import main.swapship.components.TargetComp;
import main.swapship.components.TimeDelComp;
import main.swapship.components.VelocityComp;
import main.swapship.components.other.PathFollowComp;
import main.swapship.components.other.PathTargetComp;
import main.swapship.components.other.SingleSpriteComp;
import main.swapship.components.player.MoveWithPlayerComp;
import main.swapship.components.player.ShipColorsComp;
import main.swapship.components.player.ShipSpritesComp;
import main.swapship.components.player.SpecialComp;
import main.swapship.components.types.PlayerComp;
import main.swapship.util.GameUtil;

import com.artemis.Entity;
import com.artemis.World;
import com.artemis.managers.GroupManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;

public class EntityFactory {

	private static final int NO_HEALTH = -1;

	// Creates a basic ship with a location, velocity, and health
	private static Entity createBasicEntity(World world, float x, float y,
			int width, int height, float vx, float vy, float vmax, int health) {
		Entity e = world.createEntity();

		// Location data
		SpatialComp sc = world.createComponent(SpatialComp.class);
		sc.setValues(x, y, width, height);
		e.addComponent(sc);

		// Velocity data
		VelocityComp vc = world.createComponent(VelocityComp.class);
		vc.setValues(vx, vy, vmax);
		e.addComponent(vc);

		// Health data
		HealthComp hc = world.createComponent(HealthComp.class);
		hc.health = health;
		hc.killable = health != NO_HEALTH;
		e.addComponent(hc);

		return e;
	}

	// Adds levels, damage, and fire rate to an entity
	private static Entity addShipOffense(World world, Entity e, int topL,
			int midL, int botL, int baseDmg, float fireRate) {
		// Level data
		LevelComp lc = world.createComponent(LevelComp.class);
		lc.setValues(topL, midL, botL);
		e.addComponent(lc);

		DamageComp dc = world.createComponent(DamageComp.class);
		// TODO better damage calculation??
		dc.damage = baseDmg;
		e.addComponent(dc);

		FireRateComp frc = world.createComponent(FireRateComp.class);
		frc.setValues(fireRate);
		e.addComponent(frc);

		return e;
	}

	/**
	 * Creates the player, returning so other classes can have easy access to it
	 *
	 * @param world
	 * @return
	 */
	public static Entity createPlayer(World world) {
		Entity e = createBasicEntity(world, Gdx.graphics.getWidth() / 2
				- Constants.SHIP_WIDTH / 2, Constants.Player.MIN_Y,
				Constants.SHIP_WIDTH, Constants.SHIP_HEIGHT,
				Constants.Player.START_VEL, Constants.Player.START_VEL,
				Constants.Player.MAX_MOVE, Constants.Player.BASE_HEALTH);

		addShipOffense(world, e, Constants.Player.BASE_PART_LVL,
				Constants.Player.BASE_PART_LVL, Constants.Player.BASE_PART_LVL,
				Constants.Player.BASE_DAMAGE, Constants.Player.FIRE_RATE);

		// Distinguishing comp
		e.addComponent(world.createComponent(PlayerComp.class));

		// Drawing
		ShipSpritesComp ssc = world.createComponent(ShipSpritesComp.class);
		ssc.setValues(Constants.Player.ARTEMIS_TOP,
				Constants.Player.ARTEMIS_MID, Constants.Player.ARTEMIS_BOT);
		e.addComponent(ssc);

		ShipColorsComp scc = world.createComponent(ShipColorsComp.class);
		scc.setValues(Color.GREEN, Color.RED, Color.BLUE);
		e.addComponent(scc);

		// Testing values
		SpecialComp spc = world.createComponent(SpecialComp.class);
		spc.defensive = DefensiveSpecialType.INVINCIBLITY;
		spc.defensiveCount = Integer.MAX_VALUE;

		spc.offensive = OffensiveSpecialType.BEAM;
		spc.offensiveCount = Integer.MAX_VALUE;
		e.addComponent(spc);

		// Deletion is handled separately
		e.addComponent(world.createComponent(NonCullComp.class));

		world.getManager(GroupManager.class).add(e, Constants.Groups.PLAYER);
		e.addToWorld();
		return e;
	}

	public static void createEnemy(World world) {
		Entity e = createBasicEntity(
				world,
				MathUtils.random(0, Gdx.graphics.getWidth()
						- Constants.SHIP_WIDTH), Gdx.graphics.getHeight(),
				Constants.SHIP_WIDTH, Constants.SHIP_HEIGHT, 0,
				-Constants.Enemy.MAX_MOVE, Constants.Enemy.MAX_MOVE,
				Constants.Enemy.BASE_HEALTH);
		addShipOffense(world, e, 0, 0, 1, Constants.Enemy.BASE_DAMAGE,
				Constants.Enemy.FIRE_RATE);

		SingleSpriteComp ssc = world.createComponent(SingleSpriteComp.class);
		ssc.name = Constants.Enemy.NAMES[MathUtils
				.random(Constants.Enemy.NAMES.length - 1)];
		ssc.tint = Color.GRAY;
		e.addComponent(ssc);

		// Path following ai
		PathFollowComp pfc = world.createComponent(PathFollowComp.class);
		pfc.setValues(PathFactory.createPath());
		e.addComponent(pfc);

		PathTargetComp tc = world.createComponent(PathTargetComp.class);
		tc.target = pfc.path.get(pfc.target);
		e.addComponent(tc);

		// Enemies are deleted when they get to the end of the path
		e.addComponent(world.createComponent(NonCullComp.class));

		world.getManager(GroupManager.class).add(e, Constants.Groups.ENEMY);
		e.addToWorld();
	}

	public static void createBoss(World world, Level level) {
		Entity e = createBasicEntity(world,
				MathUtils.random(0, Gdx.graphics.getWidth() - 144),
				Gdx.graphics.getHeight() - 108, 144, 108, 0, 0, 0,
				Constants.Enemy.BASE_HEALTH);
		addShipOffense(world, e, 0, 0, 1, Constants.Enemy.BASE_DAMAGE,
				Constants.Enemy.FIRE_RATE);

		SingleSpriteComp ssc = world.createComponent(SingleSpriteComp.class);
		ssc.name = "Boss1_V2";
		ssc.tint = level.tint;
		e.addComponent(ssc);

		e.addComponent(world.createComponent(NonCullComp.class));

		world.getManager(GroupManager.class).add(e, Constants.Groups.ENEMY);
		e.addToWorld();
	}

	public static void createShot(World world, float x, float y, int damage,
			Color tint, boolean playerShot) {
		Entity e = createBasicEntity(world, x, y, Constants.Shot.WIDTH,
				Constants.Shot.HEIGHT, 0, Constants.Shot.VEL
						* ((playerShot) ? 1 : -1), 0, NO_HEALTH);

		SingleSpriteComp ssc = world.createComponent(SingleSpriteComp.class);
		ssc.name = Constants.Shot.SHOT_NAME;
		ssc.tint = tint;
		e.addComponent(ssc);

		DamageComp dc = world.createComponent(DamageComp.class);
		dc.damage = damage;
		e.addComponent(dc);

		world.getManager(GroupManager.class).add(
				e,
				playerShot ? Constants.Groups.PLAYER_ATTACK
						: Constants.Groups.ENEMY_ATTACK);
		e.addToWorld();
	}

	/**
	 * Returns whether entity was created or not
	 *
	 * @param world
	 * @param type
	 * @param sourceX
	 * @param sourceY
	 * @return
	 */
	public static boolean createOffensiveSpecial(World world,
			OffensiveSpecialType type, float sourceX, float sourceY) {
		// TODO changed sourceX and sourceY to be bottom left corner of player
		if (type == OffensiveSpecialType.NONE) {
			return false;
		}

		if (type == OffensiveSpecialType.MISSILE) {
			return createMissiles(world, sourceX, sourceY);
		}

		if (type == OffensiveSpecialType.BEAM) {
			createBeam(world, sourceX, sourceY);
		}
		return true;
	}

	public static boolean createDefensiveSpecial(World world,
			DefensiveSpecialType type, float sourceX, float sourceY) {
		if (type == DefensiveSpecialType.NONE) {
			return false;
		}

		if (type == DefensiveSpecialType.SHIELD) {
			createShield(world, sourceX, sourceY);
		}

		if (type == DefensiveSpecialType.INVINCIBLITY) {
			createInvincibility(world, sourceX, sourceY);
		}
		return true;

	}

	private static boolean createMissiles(World world, float sourceX,
			float sourceY) {
		Array<Entity> targets = GameUtil.findRandTargets(world,
				Constants.Groups.ENEMY, Constants.Missile.SPAWN_COUNT);
		// Create a bunch of missiles
		if (targets == null) {
			return false;
		}
		for (Entity target : targets) {
			createMissile(world, sourceX, sourceY, target);
		}
		return true;
	}

	private static void createMissile(World world, float sourceX,
			float sourceY, Entity target) {
		Entity e = createBasicEntity(world, sourceX + Constants.SHIP_WIDTH / 2
				- Constants.Missile.WIDTH / 2, sourceY + Constants.SHIP_HEIGHT,
				Constants.Missile.WIDTH, Constants.Missile.HEIGHT, 0, 0,
				Constants.Missile.VEL, NO_HEALTH);

		DamageComp dc = world.createComponent(DamageComp.class);
		dc.damage = Integer.MAX_VALUE; // Max Value so it's an insta-kill
		e.addComponent(dc);

		TargetComp tc = world.createComponent(TargetComp.class);
		tc.target = target;
		tc.targetGroup = Constants.Groups.ENEMY;
		e.addComponent(tc);

		SingleSpriteComp ssc = world.createComponent(SingleSpriteComp.class);
		ssc.name = Constants.Missile.NAME;
		ssc.tint = Color.WHITE;
		e.addComponent(ssc);

		world.getManager(GroupManager.class).add(e,
				Constants.Groups.PLAYER_ATTACK);
		e.addToWorld();
	}

	private static void createBeam(World world, float srcX, float srcY) {
		// Beams are actually just a bunch of beams
		int numBeams = Gdx.graphics.getHeight() / Constants.Beam.HEIGHT + 1;
		float y = srcY + Constants.SHIP_HEIGHT;
		float x = srcX + Constants.SHIP_WIDTH / 2 - Constants.Beam.WIDTH / 2;
		GroupManager gm = world.getManager(GroupManager.class);
		for (int i = 0; i < numBeams; ++i) {
			Entity e = world.createEntity();
			gm.removeFromAllGroups(e);

			MoveWithPlayerComp mwpc = world
					.createComponent(MoveWithPlayerComp.class);
			mwpc.xDisplace = Constants.SHIP_WIDTH / 2 - Constants.Beam.WIDTH
					/ 2;
			mwpc.yDispace = Constants.SHIP_HEIGHT + Constants.Beam.HEIGHT * i;
			e.addComponent(mwpc);

			SpatialComp sc = world.createComponent(SpatialComp.class);
			sc.setValues(x, y, Constants.Beam.WIDTH, Constants.Beam.HEIGHT);
			e.addComponent(sc);

			SingleSpriteComp ssc = world
					.createComponent(SingleSpriteComp.class);
			ssc.name = Constants.Beam.NAME;
			ssc.tint = Color.WHITE;
			e.addComponent(ssc);

			DamageComp dc = world.createComponent(DamageComp.class);
			dc.damage = Constants.Beam.BASE_DAMAGE;
			e.addComponent(dc);

			HealthComp hc = world.createComponent(HealthComp.class);
			hc.health = Constants.Beam.HEALTH;
			hc.killable = false;
			e.addComponent(hc);

			// Beams are removed after a certain amount of time, so don't cull
			// them
			e.addComponent(world.createComponent(NonCullComp.class));

			TimeDelComp tdc = world.createComponent(TimeDelComp.class);
			tdc.setValues(Constants.Beam.TIME_OUT);
			e.addComponent(tdc);

			gm.add(e, Constants.Groups.PLAYER_ATTACK);
			e.addToWorld();

			y += Constants.Beam.HEIGHT;
		}
	}

	// Method to consolidate shield and invincibility code
	private static Entity createBubble(World world, float sourceX,
			float sourceY, int bubWidth, int bubHeight, String imgName,
			int health) {
		Entity e = world.createEntity();

		MoveWithPlayerComp mwpc = world
				.createComponent(MoveWithPlayerComp.class);
		mwpc.xDisplace = -(bubWidth - Constants.SHIP_WIDTH) / 2;
		mwpc.yDispace = -(bubHeight - Constants.SHIP_HEIGHT) / 2;
		e.addComponent(mwpc);

		SpatialComp sc = world.createComponent(SpatialComp.class);
		sc.setValues(sourceX + mwpc.xDisplace, sourceY + mwpc.yDispace,
				bubWidth, bubHeight);
		e.addComponent(sc);

		SingleSpriteComp ssc = world.createComponent(SingleSpriteComp.class);
		ssc.name = imgName;
		ssc.tint = Color.WHITE;
		e.addComponent(ssc);

		HealthComp hc = world.createComponent(HealthComp.class);
		hc.health = health;
		e.addComponent(hc);

		e.addComponent(world.createComponent(NonCullComp.class));
		world.getManager(GroupManager.class).add(e, Constants.Groups.PLAYER);
		return e;
	}

	private static void createShield(World world, float sourceX, float sourceY) {
		createBubble(world, sourceX, sourceY, Constants.Shield.WIDTH,
				Constants.Shield.HEIGHT, Constants.Shield.NAME,
				Constants.Shield.HEALTH).addToWorld();
	}

	private static void createInvincibility(World world, float sourceX,
			float sourceY) {
		Entity e = createBubble(world, sourceX, sourceY,
				Constants.Invincibility.WIDTH, Constants.Invincibility.HEIGHT,
				Constants.Invincibility.NAME, Constants.Invincibility.HEALTH);

		TimeDelComp tdc = world.createComponent(TimeDelComp.class);
		tdc.setValues(Constants.Invincibility.TIME_OUT);
		e.addComponent(tdc);

		e.addToWorld();
	}

	public static void createExplosion(World world, float x, float y,
			float xVel, float yVel) {
		Entity e = createBasicEntity(world, x, y, Constants.Explosion.WIDTH,
				Constants.Explosion.HEIGHT,
				xVel * Constants.Explosion.VEL_PERC, yVel
						* Constants.Explosion.VEL_PERC, 0, NO_HEALTH);

		SingleSpriteComp ssc = world.createComponent(SingleSpriteComp.class);
		ssc.name = Constants.Explosion.NAME;
		ssc.tint = Color.WHITE;
		e.addComponent(ssc);

		TimeDelComp tdc = world.createComponent(TimeDelComp.class);
		tdc.setValues(Constants.Explosion.LIFE_TIME);
		e.addComponent(tdc);

		e.addToWorld();
	}
}


text:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

  <bean id="ProposalPersonUnit" parent="ProposalPersonUnit-parentBean" />

  <bean id="ProposalPersonUnit-parentBean" abstract="true" parent="BusinessObjectEntry">
    <property name="businessObjectClass" value="org.kuali.kra.proposaldevelopment.bo.ProposalPersonUnit" />
		<property name="objectLabel" value="Proposal Person Unit" />
    <property name="inquiryDefinition" >
      <ref bean="ProposalPersonUnit-inquiryDefinition" />
    </property>
    <property name="lookupDefinition" >
      <ref bean="ProposalPersonUnit-lookupDefinition" />
    </property>
    <property name="titleAttribute" value="unitNumber" />
    <property name="attributes" >
      <list>
        <ref bean="ProposalPersonUnit-proposalNumber" />
        <ref bean="ProposalPersonUnit-proposalPersonNumber" />
        <ref bean="ProposalPersonUnit-unitNumber" />
        <ref bean="ProposalPersonUnit-leadUnit" />
        <ref bean="ProposalPersonUnit-versionNumber" />
      </list>
    </property>
  </bean>

  <bean id="ProposalPersonUnit-proposalNumber" parent="ProposalPersonUnit-proposalNumber-parentBean" />

  <bean id="ProposalPersonUnit-proposalNumber-parentBean" abstract="true" parent="AttributeReferenceDummy-genericSystemId">
    <property name="name" value="proposalNumber" />
    <property name="label" value="Proposal Number" />
    <property name="shortLabel" value="Prop Nbr" />
    <property name="summary" value="Proposal Number" />
    <property name="description" value="Proposal Number" />
  </bean>
  <bean id="ProposalPersonUnit-proposalPersonNumber" parent="ProposalPersonUnit-proposalPersonNumber-parentBean" />

  <bean id="ProposalPersonUnit-proposalPersonNumber-parentBean" abstract="true" parent="AttributeReferenceDummy-genericSystemId">
    <property name="name" value="proposalPersonNumber" />
    <property name="label" value="Proposal Person Number" />
    <property name="shortLabel" value="Prop Per Nbr" />
    <property name="control" >
      <bean parent="HiddenControlDefinition" />
    </property>
    <property name="summary" value="Proposal Person Number" />
    <property name="description" value="Proposal Person Number" />
  </bean>
  <bean id="ProposalPersonUnit-unitNumber" parent="ProposalPersonUnit-unitNumber-parentBean" />

  <bean id="ProposalPersonUnit-unitNumber-parentBean" abstract="true" parent="Unit-unitNumber">
  </bean>
  <bean id="ProposalPersonUnit-leadUnit" parent="ProposalPersonUnit-leadUnit-parentBean" />

  <bean id="ProposalPersonUnit-leadUnit-parentBean" abstract="true" parent="AttributeReferenceDummy-genericBoolean">
    <property name="name" value="leadUnit" />
    <property name="label" value="Is Lead Unit" />
    <property name="shortLabel" value="Lead Unit" />
    <property name="summary" value="Is Lead Unit" />
    <property name="description" value="Is Lead Unit" />
  </bean>
  <bean id="ProposalPersonUnit-versionNumber" parent="ProposalPersonUnit-versionNumber-parentBean" />

  <bean id="ProposalPersonUnit-versionNumber-parentBean" abstract="true" parent="AttributeReferenceDummy-versionNumber">
  </bean>

  <bean id="ProposalPersonUnit-inquiryDefinition" parent="ProposalPersonUnit-inquiryDefinition-parentBean" />

  <bean id="ProposalPersonUnit-inquiryDefinition-parentBean" abstract="true" parent="InquiryDefinition">
    <property name="title" value="Proposal Person Unit" />
    <property name="inquirySections" >
      <list>
        <bean parent="InquirySectionDefinition">
          <property name="title" value="Proposal Person Unit" />
          <property name="numberOfColumns" value="1" />
          <property name="inquiryFields" >
            <list>
              <bean parent="FieldDefinition"
                    p:attributeName="proposalPersonNumber"
                    p:forceInquiry="true" />
              <bean parent="FieldDefinition"
                    p:attributeName="proposalNumber"
                    p:forceInquiry="true" />
              <bean parent="FieldDefinition"
                    p:attributeName="unitNumber"
                    p:forceInquiry="true" />
              <bean parent="FieldDefinition"
                    p:attributeName="leadUnit" />
            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>

  <bean id="ProposalPersonUnit-lookupDefinition" parent="ProposalPersonUnit-lookupDefinition-parentBean" />

  <bean id="ProposalPersonUnit-lookupDefinition-parentBean" abstract="true" parent="LookupDefinition">
    <property name="title" value="Proposal Person Unit" />
    <property name="menubar" value="Main" />

    <property name="defaultSort" >
      <bean parent="SortDefinition">
      </bean>
    </property>
    <property name="lookupFields" >
      <list>
        <bean parent="FieldDefinition"
              p:attributeName="proposalNumber" />
        <bean parent="FieldDefinition"
              p:attributeName="proposalPersonNumber" />
        <bean parent="FieldDefinition"
              p:attributeName="unitNumber" />
        <bean parent="FieldDefinition"
              p:attributeName="leadUnit" />
      </list>
    </property>
    <property name="resultFields" >
      <list>
        <bean parent="FieldDefinition"
              p:attributeName="proposalPersonNumber"
              p:forceInquiry="true" />
        <bean parent="FieldDefinition"
              p:attributeName="proposalNumber"
              p:forceInquiry="true" />
        <bean parent="FieldDefinition"
              p:attributeName="unitNumber"
              p:forceInquiry="true" />
        <bean parent="FieldDefinition"
              p:attributeName="leadUnit" />
      </list>
    </property>
  </bean>
</beans>

redpajama_set_name: RedPajamaGithub


text:
package org.cloudfoundry.community.servicebroker.vrealize.service;

import org.cloudfoundry.community.servicebroker.vrealize.Application;
import org.cloudfoundry.community.servicebroker.vrealize.TestConfig;
import org.cloudfoundry.community.servicebroker.vrealize.persistance.LastOperation;
import org.cloudfoundry.community.servicebroker.vrealize.persistance.VrServiceInstance;
import org.cloudfoundry.community.servicebroker.vrealize.persistance.VrServiceInstanceBinding;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.servicebroker.exception.ServiceBrokerException;
import org.springframework.cloud.servicebroker.exception.ServiceInstanceBindingExistsException;
import org.springframework.cloud.servicebroker.model.OperationState;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
public class VrServiceInstanceBindingServiceTest {

    @Autowired
    @InjectMocks
    VrServiceInstanceBindingService vrServiceInstanceBindingService;

    @Mock
    VrServiceInstanceService vrServiceInstanceService;

    @Resource(name = "sibTemplate")
    private HashOperations<String, String, VrServiceInstanceBinding> repo;

    @Autowired
    @Resource(name = "sibTemplate")
    private RedisTemplate<String, VrServiceInstanceBinding> template;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        VrServiceInstance si = TestConfig.getServiceInstance();
        LastOperation lo = new LastOperation(OperationState.SUCCEEDED, "anOp", false);
        si.withLastOperation(lo);

        when(vrServiceInstanceService.getServiceInstance(Matchers.anyString()))
                .thenReturn(si);

        when(
                vrServiceInstanceService
                        .saveInstance(any(VrServiceInstance.class)))
                .thenReturn(si);

        when(
                vrServiceInstanceService
                        .deleteInstance(any(VrServiceInstance.class)))
                .thenReturn(si);

        Set<String> keys = repo.keys(VrServiceInstanceBindingService.OBJECT_ID);
        for (String key : keys) {
            repo.delete(VrServiceInstanceBindingService.OBJECT_ID, key);
        }
    }

    @After
    public void cleanUp() throws Exception {
        Set<String> keys = repo.keys(VrServiceInstanceBindingService.OBJECT_ID);
        for (String key : keys) {
            repo.delete(VrServiceInstanceBindingService.OBJECT_ID, key);
        }
    }

    @Test
    public void testBinding() throws ServiceBrokerException,
            ServiceInstanceBindingExistsException {

        VrServiceInstanceBinding b = TestConfig.getServiceInstanceBinding();
        assertNotNull(b);
        Map<String, Object> m = b.getCredentials();
        assertNotNull(m);
        assertEquals("mysql://root:secret@aHost:1234/aDB",
                m.get(VrServiceInstance.URI));
        assertNotNull(b.getId());
        assertEquals("anID", b.getServiceInstanceId());
    }
}


text:
# CSS #

## Introduction ##

SilverStripe strives to keep out of a template designer's way as much as possible -
this also extends to how you want to write your CSS.

## Adding CSS to your template ##

You are free to add `<style>` and `<link>` tags to your template (typically `themes/yourtheme/templates/Page.ss`).

SilverStripe provides a management layer for javascript and CSS files on top of that with the [Requirements](/reference/requirements) class,
by adding some simple PHP calls to your controller or template. Some files are automatically included,
depending on what functionality you are using (e.g. SilverStripe forms automatically include `framework/css/Form.css`).

In your controller (e.g. `mysite/code/Page.php`):

	:::php
	class Page_Controller {
		public function init() {
			// either specify the css file manually
			Requirements::css("mymodule/css/my.css", "screen,projection");
			// or mention the css filename and SilverStripe will get the file from the current theme and add it to the template
			Requirements::themedCSS('print', null,'print');
		}
	}

Or in your template (e.g. `themes/yourtheme/templates/Page.ss`):

	:::ss
	<% require css("mymodule/css/my.css") %>

Management through the `Requirements` class has the advantage that modules can include their own CSS files without modifying
your template. On the other hand, you as a template developer can "block" or change certain CSS files that are included from
thirdparty code.

## WYSIWYG editor: typography.css and editor.css

This stylesheet is used to "namespace" rules which just apply in a rendered site and the WYSIWYG-editor of the CMS. This
is needed to get custom styles in the editor without affecting the remaining CMS-styles.

An example of a good location to use `class="typography"` is the container element to your WYSIWYG-editor field. The
`$Content` WYSIWYG editor field already comes with SilverStripe out-of-the-box:

	:::html
	<!--
	   This is a good way, you're only applying class="typography"
	   to where the WYSIWYG editor is, and not the entire layout.
	-->
	`<div id="Main">`
	   `<div id="LeftContent">`
	      `<p>`We have a lot of content to go here.`</p>`
	   `</div>`

	   `<div id="Content" class="typography">`
	      $Content
	   `</div>`
	`</div>`

The `typography.css` file should contain only styling for these elements (related to the WYSIWYG editor):

   * **Headers (h1 - h6)**
   * **Text (p, blockquote, pre)**
   * **Lists (ul, li)**
   * **CSS alignment (img.left, .left, .right etc)**
   * **Tables**
   * **Miscellaneous (hr etc)**

The advantages are that it's fully styled, as a default starting point which you can easily tweak. It also doesn't
affect the CMS styling at all (except for the WYSIWYG), which is what we want.

It's also separated from the rest of the layout. If you wanted to change typography only, for where you usually edit the
content you don't need to go wading through other CSS files related to the actual layout.

To get these styles working in the CMS. Eg you use a font you want in the CMS area you need to create an editor.css
file. Then with this file you can define styles for the CMS or just import the styles from typography. Unlike
`typography.css`, `editor.css` is NOT included in the front end site. So this is  `themes/your_theme/css/editor.css`

	:::css
	/* Import the common styles from typography like link colors. */
	@import 'typography.css';

	/* We want the backend editor to have a bigger font as well though */
	.typography * { font-size: 200% }

See [typography](/reference/typography) for more information.

## Related ##

 * [javascript](javascript)
 * ["Compass" module](http://silverstripe.org/compass-module/): Allows writing CSS in SASS/LESS syntax, with better code management through mixins, includes and variables
 * [Reference: CMS Architecture](../reference/cms-architecture)
 * [Howto: Extend the CMS Interface](../howto/extend-cms-interface)


text:
using System;
using System.Collections;
using System.Diagnostics;
using PHP.Core.Reflection;

#if SILVERLIGHT
using PHP.CoreCLR;
#endif

namespace PHP.Core
{
	#region RuntimeChainElement

	///
	/// An abstract element of <see cref="PhpRuntimeChain"/>.
	///
	[Serializable]
	public abstract class RuntimeChainElement
	{
		///
		/// Applies the element on a given variable (Read semantics).
		///
		/// <param name="var">The variable.</param>
		/// <param name="context">Script context.</param>
		/// <param name="caller">Class context.</param>
		/// <returns>The resulting value.</returns>
		public abstract object Get(object var, ScriptContext context, DTypeDesc caller);

		///
		/// Applies the element on a given variable (ReadRef semantics).
		///
		/// <param name="var">The variable.</param>
		/// <param name="context">Script context.</param>
		/// <param name="caller">Class context.</param>
		/// <returns>The resulting value.</returns>
		public abstract PhpReference GetRef(ref object var, ScriptContext context, DTypeDesc caller);

		///
		/// Performs the ensure operation on an variable to make it suitable for current element application.
		///
		/// <param name="var">The variable.</param>
		/// <param name="context">Script context.</param>
		/// <param name="caller">Class context.</param>
		/// <returns>The new variable value.</returns>
		public abstract object EnsureVariable(ref object var, ScriptContext context, DTypeDesc caller);

		///
        /// Performs the ensure operation on this element to make it suitable for <see cref="Next"/> element
		/// application.
		///
		/// <param name="var">The variable.</param>
		/// <param name="context">Script context.</param>
		/// <param name="caller">Class context.</param>
		/// <returns>The new element value.</returns>
		public abstract object Ensure(object var, ScriptContext context, DTypeDesc caller);

		///
		/// Applies the element on a given variable (ReadRef semantics) that has already been ensured to have
		/// the suitable type.
		///
		/// <param name="var">The variable.</param>
		/// <param name="context">Script context.</param>
		/// <param name="caller">Class context.</param>
		/// <returns>The resulting value.</returns>
		public abstract PhpReference GetEnsuredRef(object var, ScriptContext context, DTypeDesc caller);

		///
		/// Returns the name of the chain element.
		///
		public abstract object Name
		{
			get;
		}

		///
		/// Next <see cref="RuntimeChainElement"/> in the chain.
		///
		public RuntimeChainElement Next;
	}

	#endregion

	#region RuntimeChainProperty

	///
	/// Represents an object property access (->).
	///
	[Serializable]
	public class RuntimeChainProperty : RuntimeChainElement
	{
		///
		/// Creates a new <see cref="RuntimeChainProperty"/> with a given name.
		///
		/// <param name="name">The field name.</param>
		public RuntimeChainProperty(string name)
		{
			this.name = name;
		}

		///
		/// Applies the field access on a given variable (Read semantics).
		///
		public override object Get(object var, ScriptContext context, DTypeDesc caller)
		{
			return Operators.GetProperty(var, name, caller, false);
		}

		///
		/// Applies the field access on a given variable (ReadRef semantics).
		///
		public override PhpReference GetRef(ref object var, ScriptContext context, DTypeDesc caller)
		{
			return Operators.GetPropertyRef(ref var, name, caller, context);
		}

		///
		/// Performs the ensure operation on an variable to make it a <see cref="DObject"/>.
		///
		public override object EnsureVariable(ref object var, ScriptContext context, DTypeDesc caller)
		{
			return Operators.EnsureVariableIsObject(ref var, context);
		}

		///
        /// Performs the ensure operation on this field to make it suitable for <see cref="RuntimeChainElement.Next"/> element
		/// application.
		///
		public override object Ensure(object var, ScriptContext context, DTypeDesc caller)
		{
			Debug.Assert(Next is RuntimeChainProperty || Next is RuntimeChainItem || Next is RuntimeChainNewItem);

			if (Next is RuntimeChainProperty) return Operators.EnsurePropertyIsObject((DObject)var, name, caller, context);
			else return Operators.EnsurePropertyIsArray((DObject)var, name, caller);
		}

		///
		/// Applies the field access on a given variable (ReadRef semantics) that has already been ensured to
		/// be <see cref="DObject"/>.
		///
		public override PhpReference GetEnsuredRef(object var, ScriptContext context, DTypeDesc caller)
		{
			return Operators.GetObjectPropertyRef((DObject)var, name, caller);
		}

		/// The name of the property.
		private string name;

		/// Returns the name of the property.
		public override object Name
		{
			get
			{ return name; }
		}
	}

	#endregion

	#region RuntimeChainItem

	///
	/// Represents an array item access ([x]).
	///
	[Serializable]
	public class RuntimeChainItem : RuntimeChainElement
	{
		///
		/// Returns the name of the item (index).
		///
		public override object Name
		{
			get { return key.Object; }
		}

		///
		/// The key.
		///
		private IntStringKey key;

		///
		/// Creates a new <see cref="RuntimeChainItem"/> with a given key.
		///
		public RuntimeChainItem(IntStringKey key)
		{
			this.key = key;
		}

		///
		/// Applies the item access on a given variable (Read semantics).
		///
		public override object Get(object var, ScriptContext context, DTypeDesc caller)
		{
			if (key.IsString)
				return Operators.GetItem(var, key.String, Operators.GetItemKinds.Get);
			else
				return Operators.GetItem(var, key.Integer, Operators.GetItemKinds.Get);
		}

		///
		/// Applies the item access on a given variable (ReadRef semantics).
		///
		public override PhpReference GetRef(ref object var, ScriptContext context, DTypeDesc caller)
		{
			return Operators.GetItemRef(Name, ref var);
		}

		///
		/// Performs the ensure operation on an variable to make it a <see cref="PhpArray"/>.
		///
		public override object EnsureVariable(ref object var, ScriptContext context, DTypeDesc caller)
		{
			return Operators.EnsureVariableIsArray(ref var);
		}

		///
        /// Performs the ensure operation on this item to make it suitable for <see cref="RuntimeChainElement.Next"/> element
		/// application.
		///
		public override object Ensure(object var, ScriptContext context, DTypeDesc caller)
		{
			Debug.Assert(Next is RuntimeChainProperty || Next is RuntimeChainItem || Next is RuntimeChainNewItem);

			if (Next is RuntimeChainProperty)
				return ((PhpArray)var).EnsureItemIsObject(Name, context);
			else
				return ((PhpArray)var).EnsureItemIsArray(Name);
		}

		///
		/// Applies the item access on a given variable (ReadRef semantics) that has already been ensured to
		/// be <see cref="PhpArray"/>.
		///
		public override PhpReference GetEnsuredRef(object var, ScriptContext context, DTypeDesc caller)
		{
			return ((PhpArray)var).GetArrayItemRef(Name);
		}
	}

	#endregion

	#region RuntimeChainNewItem

	///
	/// Represents an array item access ([]).
	///
	[Serializable]
	public class RuntimeChainNewItem : RuntimeChainElement
	{
		///
		/// Creates a new <see cref="RuntimeChainNewItem"/>.
		///
		public RuntimeChainNewItem()
		{ }

		///
		/// Throws an error because [] cannot be used in read context.
		///
		public override object Get(object var, ScriptContext context, DTypeDesc caller)
		{
			PhpException.Throw(PhpError.Error, CoreResources.operator_array_access_used_for_reading);
			return null;
		}

		///
		/// Applies the new item access on a given variable (ReadRef semantics).
		///
		public override PhpReference GetRef(ref object var, ScriptContext context, DTypeDesc caller)
		{
			PhpReference reference = new PhpReference();
			Operators.SetItem(reference, ref var);
			return reference;
		}

		///
		/// Performs the ensure operation on an variable to make it a <see cref="PhpArray"/>.
		///
		public override object EnsureVariable(ref object var, ScriptContext context, DTypeDesc caller)
		{
			return Operators.EnsureVariableIsArray(ref var);
		}

		///
        /// Performs the ensure operation on the new item to make it suitable for <see cref="RuntimeChainElement.Next"/> element
		/// application.
		///
		public override object Ensure(object var, ScriptContext context, DTypeDesc caller)
		{
			Debug.Assert(Next is RuntimeChainProperty || Next is RuntimeChainItem || Next is RuntimeChainNewItem);

			if (Next is RuntimeChainProperty)
			{
				DObject std = Library.stdClass.CreateDefaultObject(context);
				((PhpArray)var).Add(std);
				return std;
			}
			else
			{
				PhpArray arr = new PhpArray();
				((PhpArray)var).Add(arr);
				return arr;
			}
		}

		///
		/// Applies the new item access on a given variable (ReadRef semantics) that has already been ensured to
		/// be <see cref="PhpArray"/>.
		///
		public override PhpReference GetEnsuredRef(object var, ScriptContext context, DTypeDesc caller)
		{
			PhpReference reference = new PhpReference();
			((PhpArray)var).Add(reference);
			return reference;
		}

		/// Returns null as new item ([]) has no name.
		public override object Name
		{
			get
			{ return null; }
		}
	}

	#endregion

	#region PhpRuntimeChain

	///
	/// Represents an operator chain at runtime.
	///
	/// <remarks>
	/// When a compile-time unknown function invocation is encountered and it has a complex parameter consisting of
	/// an operator chain, evaluation of the chain must be postponed to run-time. Only at run-time it becomes
	/// clear whether the chain's outcome should be an object or a <see cref="PhpReference"/> (formal parameter
	/// equipped with the &) which leads to somewhat different evaluation procedure.
	/// </remarks>
	[Serializable]
	public class PhpRuntimeChain
	{
		///
		/// Creates a new <see cref="PhpRuntimeChain"/> operating on a given variable.
		///
		/// <param name="var">The variable.</param>
		public PhpRuntimeChain(object var)
		{
			this.Variable = var;
		}

		///
		/// Creates a new <see cref="PhpRuntimeChain"/> operating on a given variable in a given class context.
		///
		/// <param name="var">The variable.</param>
		/// <param name="caller">The class context.</param>
		public PhpRuntimeChain(object var, DTypeDesc caller)
		{
			this.Variable = var;
			this.Caller = caller;
		}

		///
		/// Extends this chain with an object field access.
		///
		/// <param name="name">The name of the field.</param>
		[Emitted]
		public void AddField(string name)
		{
			if (lastElement != null)
			{
				RuntimeChainElement element = new RuntimeChainProperty(name);
				lastElement.Next = element;
				lastElement = element;
			}
			else Chain = lastElement = new RuntimeChainProperty(name);
		}

		///
		/// Extends this chain with an array item access.
		///
		/// <param name="name">The name of the item (index).</param>
		[Emitted]
		public void AddItem(object name)
		{
			IntStringKey key;
			if (Convert.ObjectToArrayKey(name, out key))
			{
				if (lastElement != null)
				{
					RuntimeChainElement element = new RuntimeChainItem(key);
					lastElement.Next = element;
					lastElement = element;
				}
				else
					Chain = lastElement = new RuntimeChainItem(key);
			}
			else
				PhpException.IllegalOffsetType();
		}

		///
		/// Extends this chain with a "new field item" ([]) access.
		///
		[Emitted]
		public void AddItem()
		{
			if (lastElement != null)
			{
				RuntimeChainElement element = new RuntimeChainNewItem();
				lastElement.Next = element;
				lastElement = element;
			}
			else Chain = lastElement = new RuntimeChainNewItem();
		}

		///
		/// Extends this chain with a <see cref="RuntimeChainElement"/>.
		///
		/// <param name="element">The element.</param>
		public void Add(RuntimeChainElement element)
		{
			if (lastElement != null)
			{
				lastElement.Next = element;
				lastElement = element;
			}
			else Chain = lastElement = element;
		}

		///
		/// Evaluates this chain as if it had the <see cref="PHP.Core.Compiler.AST.AccessType.Read"/> access type.
		///
		/// <param name="context">Current script context.</param>
		/// <returns>The result of chain evaluation.</returns>
		public object GetValue(ScriptContext context)
		{
			// dereference the PhpReference
			object var = PhpVariable.Dereference(Variable);

			RuntimeChainElement element = Chain;
			while (element != null)
			{
				// GetProperty/GetItem
				var = element.Get(var, context, Caller);
				element = element.Next;
			}
			return var;
		}

		///
		/// Evaluates this chain as if it had the <see cref="PHP.Core.Compiler.AST.AccessType.ReadRef"/> access type.
		///
		/// <param name="context">Current script context.</param>
		/// <returns>The result of chain evaluation.</returns>
		public PhpReference GetReference(ScriptContext context)
		{
			PhpReference reference;

			RuntimeChainElement element = Chain;
			if (element == null)
			{
				// if we are just wrapping the variable with a PhpReference, make a copy
				reference = Variable as PhpReference;
				if (reference == null) reference = new PhpReference(PhpVariable.Copy(Variable, CopyReason.Unknown));

				return reference;
			}

			// make sure that we have a PhpReference
			reference = PhpVariable.MakeReference(Variable);

			if (element == lastElement)
			{
				// GetPropertyRef/GetItemRef
				return element.GetRef(ref reference.value, context, Caller);
			}

			// EnsureVariableIsObject/EnsureVariableIsArray
			object var = element.EnsureVariable(ref reference.value, context, Caller);
			if (var == null) return new PhpReference();

			while (element.Next != null)
			{
				// Ensure{Field,Item}Is{Object,Array}
				var = element.Ensure(var, context, Caller);
				if (var == null) return new PhpReference();

				element = element.Next;
			}

			// GetObjectPropertyRef/GetArrayItemRef
			return element.GetEnsuredRef(var, context, Caller);
		}

		///
		/// The variable on which the chain is applied.
		///
		internal object Variable;

		///
		/// The class context in which the chain should be evaluated.
		///
		internal DTypeDesc Caller;

		///
		/// Head of the linked list of <see cref="RuntimeChainElement"/>s representing field and item names
		/// applied to the <see cref="Variable"/> in the lexical order.
		///
		internal RuntimeChainElement Chain;

		///
		/// The lastly added element or null if there are no elements yet.
		///
		private RuntimeChainElement lastElement;
	}

	#endregion

	#region PhpSetterChainArray Proxy

	[Serializable]
	internal sealed class PhpSetterChainArray : PhpArray
	{
		internal PhpSetterChainArray()
		{
		}

		#region Operators

        protected override object GetArrayItemOverride(object key, bool quiet)
		{
			Debug.Fail("N/A");
			throw null;
		}

		protected override void SetArrayItemOverride(object key, object value)
		{
			IntStringKey array_key;
			ScriptContext context = ScriptContext.CurrentContext; // TODO: context -> field

			// extend and finish the setter chain if one already exists
			if (!Convert.ObjectToArrayKey(key, out array_key))
			{
				PhpException.IllegalOffsetType();
				context.AbortSetterChain(true);
				return;
			}

			context.ExtendSetterChain(new RuntimeChainItem(array_key));
			context.FinishSetterChain(value);
			return;
		}

        protected override PhpReference GetArrayItemRefOverride()
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
			return new PhpReference();
		}

        protected override PhpReference GetArrayItemRefOverride(object key)
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
			return new PhpReference();
		}

        protected override PhpReference GetArrayItemRefOverride(int key)
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
			return new PhpReference();
		}

        protected override PhpReference GetArrayItemRefOverride(string key)
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
			return new PhpReference();
		}

        protected override void SetArrayItemOverride(object value)
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
		}

        protected override void SetArrayItemOverride(int key, object value)
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
		}

        protected override void SetArrayItemOverride(string key, object value)
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
		}

        protected override void SetArrayItemRefOverride(object key, PhpReference value)
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
		}

        protected override PhpArray EnsureItemIsArrayOverride()
		{
			ScriptContext.CurrentContext.AbortSetterChain(false);
			return null;
		}

        protected override DObject EnsureItemIsObjectOverride(ScriptContext context)
		{
			// setter chain:
			ScriptContext.CurrentContext.AbortSetterChain(false);
			return null;
		}

		protected override PhpArray EnsureItemIsArrayOverride(object key)
		{
			ScriptContext context = ScriptContext.CurrentContext;

			IntStringKey array_key;

			if (!Convert.ObjectToArrayKey(key, out array_key))
			{
				PhpException.IllegalOffsetType();
				context.AbortSetterChain(true);
				return null;
			}

			// extend the setter chain if one already exists:
			context.ExtendSetterChain(new RuntimeChainItem(array_key));

			return this;
		}

        protected override DObject EnsureItemIsObjectOverride(object key, ScriptContext/*!*/ context)
		{
			IntStringKey array_key;

			if (!Convert.ObjectToArrayKey(key, out array_key))
			{
				PhpException.IllegalOffsetType();
				context.AbortSetterChain(true);
				return null;
			}

			// extend the setter chain if one already exists
			context.ExtendSetterChain(new RuntimeChainItem(array_key));

			return ScriptContext.SetterChainSingletonObject;

		}

		#endregion
	}

	#endregion
}


text:
package trace

import (
	"net/http"
	"testing"

	"github.com/fabiolb/fabio/config"
	opentracing "github.com/opentracing/opentracing-go"
	mocktracer "github.com/opentracing/opentracing-go/mocktracer"
	zipkin "github.com/openzipkin-contrib/zipkin-go-opentracing"
	zipkintypes "github.com/openzipkin-contrib/zipkin-go-opentracing/types"
)

const testServiceName = "TEST-SERVICE"

func TestCreateCollectorHTTP(t *testing.T) {
	if CreateCollector("http", "", "") == nil {
		t.Error("CreateCollector returned nil value.")
		t.FailNow()
	}
}

func TestCreateSpanNoGlobalTracer(t *testing.T) {
	opentracing.SetGlobalTracer(nil)
	req, _ := http.NewRequest("GET", "http://example.com", nil)

	if CreateSpan(req, &config.Tracing{ServiceName: "fabiolb-test", SpanName: "{{.Method}} {{.Path}}"}) != nil {
		t.Error("CreateSpan returned a non-nil result using a nil global tracer.")
		t.Fail()
	}
}

func TestCreateSpanWithNoParent(t *testing.T) {
	tracer, _ := zipkin.NewTracer(nil)
	opentracing.SetGlobalTracer(tracer)

	req, _ := http.NewRequest("GET", "http://example.com", nil)
	if CreateSpan(req, &config.Tracing{ServiceName: "fabiolb-test", SpanName: "{{.Method}} {{.Path}}"}) == nil {
		t.Error("Received nil span while a global tracer was set.")
		t.FailNow()
	}
}

func TestCreateSpanWithParent(t *testing.T) {
	mt := mocktracer.New()
	opentracing.SetGlobalTracer(mt)
	globalTracer := opentracing.GlobalTracer()
	parentSpan := globalTracer.StartSpan(testServiceName)

	requestIn, _ := http.NewRequest("GET", "http://example.com", nil)
	mt.Inject(parentSpan.Context(),
		opentracing.HTTPHeaders,
		opentracing.HTTPHeadersCarrier(requestIn.Header),
	)

	if CreateSpan(requestIn, &config.Tracing{ServiceName: "fabiolb-test", SpanName: "{{.Method}} {{.Path}}"}) == nil {
		t.Error("Received a nil span while a global tracer was set.")
		t.FailNow()
	}
}

func TestInitializeTracer(t *testing.T) {
	opentracing.SetGlobalTracer(nil)
	InitializeTracer(&config.Tracing{TracingEnabled: true, CollectorType: "http"})
	if opentracing.GlobalTracer() == nil {
		t.Error("InitializeTracer set a nil tracer.")
		t.FailNow()
	}
}

func TestInitializeTracerWhileDisabled(t *testing.T) {
	opentracing.SetGlobalTracer(nil)
	InitializeTracer(&config.Tracing{TracingEnabled: false, CollectorType: "http"})
	if opentracing.GlobalTracer() != nil {
		t.Error("InitializeTracer set a tracer while tracing was disabled.")
		t.FailNow()
	}
}

func TestInjectHeaders(t *testing.T) {
	mt := mocktracer.New()
	opentracing.SetGlobalTracer(mt)
	globalTracer := opentracing.GlobalTracer()
	span := globalTracer.StartSpan(testServiceName)

	req, _ := http.NewRequest("GET", "http://example.com", nil)
	InjectHeaders(span, req)

	if req.Header.Get("Mockpfx-Ids-Traceid") == "" {
		t.Error("Inject did not set the Traceid in the request.")
		t.Fail()
	}
	if req.Header.Get("Mockpfx-Ids-Spanid") == "" {
		t.Error("Inject did not set the Spanid in the request.")
		t.Fail()
	}
}

func TestInjectHeadersWithParentSpan(t *testing.T) {
	parentSpanId := uint64(12345)
	parentSpanContext := zipkin.SpanContext{
		SpanID:  parentSpanId,
		TraceID: zipkintypes.TraceID{High: uint64(1234), Low: uint64(4321)},
	}

	tracer, _ := zipkin.NewTracer(nil)
	opentracing.SetGlobalTracer(tracer)
	globalTracer := opentracing.GlobalTracer()
	childSpan := globalTracer.StartSpan(testServiceName+"-CHILD", opentracing.ChildOf(parentSpanContext))

	req, _ := http.NewRequest("GET", "http://example.com", nil)
	InjectHeaders(childSpan, req)

	if req.Header.Get("X-B3-Traceid") == "" {
		t.Error("Inject did not set the Traceid in the request.")
		t.Fail()
	}
	if req.Header.Get("X-B3-Spanid") == "" {
		t.Error("Inject did not set the Spanid in the request.")
		t.Fail()
	}
	if req.Header.Get("X-B3-Parentspanid") != "0000000000003039" {
		t.Error("Inject did not set the correct Parentspanid in the request.")
		t.Fail()
	}
	if req.Header.Get("x-B3-Traceid") != "00000000000004d200000000000010e1" {
		t.Error("Inject did not reuse the Traceid from the parent span")
		t.Fail()
	}
}

func TestSpanName(t *testing.T) {
	req, _ := http.NewRequest("GET", "http://example.com/demo", nil)

	if spanName("{{.Method}} {{.Host}} {{.Path}}", req) != "GET example.com /demo" {
		t.Error("spanName did not properly render the supported template")
		t.Fail()
	}

	if spanName("{{.Invalid", req) != "{{.Invalid" {
		t.Error("spanName did not return the unrendered string of the invalid template")
		t.Fail()
	}

	if spanName("{{.Unsupported}}", req) != "{{.Unsupported}}" {
		t.Error("spanName did not return the unrendered string of the unsupported template")
		t.Fail()
	}
}


text:
package org.oncoblocks.centromere.web.exceptions;

import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;

/**
 * Simple representation of a web services exception.  Returns to the user an HTTP status code,
 *   API-specific error code, user message, developer message, and URL for more information.
 *
 * @author woemler
 */
public class RestError {

	private final HttpStatus status;
	private final Integer code;
	private final String message;
	private final String developerMessage;
	private final String moreInfoUrl;

	public RestError(HttpStatus status, Integer code, String message, String developerMessage,
			String moreInfoUrl) {
		Assert.notNull(status,"HttpStatus argument cannot be null.");
		this.status = status;
		this.code = code;
		this.message = message;
		this.developerMessage = developerMessage;
		this.moreInfoUrl = moreInfoUrl;
	}

	public HttpStatus getStatus() {
		return status;
	}

	public Integer getCode() {
		return code;
	}

	public String getMessage() {
		return message;
	}

	public String getDeveloperMessage() {
		return developerMessage;
	}

	public String getMoreInfoUrl() {
		return moreInfoUrl;
	}

}


text:
package org.hibernate.jpamodelgen.test.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation allowing to specify which classes should be passed to the annotation processor for compilation.
 *
 * @author Hardy Ferentschik
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface WithClasses {
	Class<?>[] value();

	/**
	 * @return an array of classes which should be complied prior to compiling the actual test classes
	 */
	Class<?>[] preCompile() default { };
}


text:
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';

const SearchResults = ({searchResults, titleAttribute}) => {
    if (!searchResults) {
        return (

{'Loading...'}

        );
    }

    return (

            {searchResults.results.map((result, index) =>
{result[titleAttribute]}
)}

    );
};

SearchResults.displayName = 'SearchResults';

SearchResults.propTypes = {
    searchResults: PropTypes.object,
    titleAttribute: PropTypes.string.isRequired
};

const mapStateToProps = (state) => ({
    searchResults: state.searchResults
});

export default connect(
    mapStateToProps
)(SearchResults);


text:
layout: post
title: Настройка сети linux
date: '2018-01-21 18:00:00'tags:
- linux
- network
---

## Вывести все сетевые интерфейсы:
```code
$ ifconfig -a
$ sudo nano /etc/network/interfaces

## Configuración de dirección IP dinámica para el interfaz eth0

auto eth0
iface eth0 inet dhcp
```
$ sudo /etc/init.d/networking restart

$ sudo ifconfig eth0 down
$ sudo ifconfig eth0 up

ethtool eth0

#настройка сети
ifconfig up
ethtool <iface>
ifconfig <iface> dhcp
exampel /etc/network/interface


text:
import logging
from collections import deque
from datetime import datetime
from typing import Dict, Optional, Tuple

from dateutil.tz import tzutc

from alamo_alerter.preprocessor import AlertPreprocessor
from alamo_alerter.utils import (
    FAILED_STATUSES,
    OK_STATUSES,
    RESULT_FAILED,
    RESULT_OK,
    RESULT_UNKNOWN,
    RESULT_UNKNOWN_FAILED,
    RESULT_UNKNOWN_OK,
    CachedResult,
    CheckInstance,
    DebounceAnalyser,
    ErrorRateAnalyser,
    decouple_error_rate
)
from alamo_common import stats

logger = logging.getLogger(__name__)

class AlamoAlerter(object):
    driver = None

    def __init__(self, driver, notification, statsd):
        self.driver = driver
        self.notification = notification
        self.statsd = statsd
        self._preprocessor = AlertPreprocessor()

    @stats.timer(hostname=True)
    def get_cached_result(self,
                          check_uuid: str, trigger_uuid: str, debounce: int):
        """Get cached result for check.
        It regenerates cache when it is empty for specific check.
        Extra value is required to distinguish when send `trigger`
        and when check just failed but trigger was already sent.

        True - means fail.

        :param check_uuid: check uuid
        :param trigger_uuid: trigger uuid
        :param debounce:
        :rtype : deque
        """
        # we need 'Extra' value
        debounce += 1

        results = self.driver.get_result(check_uuid, trigger_uuid, debounce)
        results = deque(reversed(results), debounce)

        return results

    @stats.increment()
    @stats.timer(hostname=True)
    def analyze_result(self, results: deque,
                       debounce: int,
                       repeat_every: int,
                       rate_loss: int=0,
                       rate_window: int=0) -> Tuple[int, Optional[str]]:
        """Analyze result according to check definition."""
        result_length = len(results)
        results_list = list(results)
        if result_length < debounce and result_length < rate_loss:
            # not enough values to proceed with analyzis
            return RESULT_OK, None
        debounce_analyser = DebounceAnalyser(results_list, debounce)
        rate_analyser = ErrorRateAnalyser(results_list, rate_loss, rate_window)

        debounce_fails = debounce_analyser.fails()
        prev_debounce_status = debounce_analyser.previous_result()

        error_rate_fails = rate_analyser.fails()
        prev_error_rate_status = rate_analyser.previous_result()

        prev_statuses = set([prev_debounce_status, prev_error_rate_status])

        if error_rate_fails or debounce_fails:
            if not prev_statuses - OK_STATUSES:
                # previously was OK, now fails => trigger
                return RESULT_FAILED, 'trigger'

        latest_result = results.pop()
        # keeping old behaviour when first element was removed:
        if len(results) == debounce:
            results.popleft()

        # even if error rate fails, if latest check is OK we want to report OK
        # otherwise error rate never resolves
        if (error_rate_fails and latest_result.status in FAILED_STATUSES) \
                or debounce_fails:
            try:
                prev_alert_sent = results_list[-(repeat_every + 1)].alert_sent
            except IndexError:
                prev_alert_sent = False
            event = 'trigger' if prev_alert_sent else None
            return RESULT_FAILED, event

        all_previous_fail = all(
            result.status in FAILED_STATUSES
            for result in list(results)[-debounce:])
        # Hysteresis:
        # if now is ok, but before either debounce or error rate was failing
        if (not error_rate_fails) and (latest_result.status == RESULT_OK):
            if all_previous_fail and prev_debounce_status in FAILED_STATUSES \
                    or prev_error_rate_status in FAILED_STATUSES:

                if latest_result.hysteresis != RESULT_OK:
                    return RESULT_FAILED, None

                elif latest_result.hysteresis == RESULT_OK:
                    return RESULT_OK, 'resolve'

        previous_are_ok = all(r.status in OK_STATUSES for r in results)
        if previous_are_ok and latest_result.status == RESULT_FAILED:
            return RESULT_FAILED, None

        return RESULT_OK, None

    @stats.increment()
    @stats.timer(hostname=True)
    def send_alert(self, check, trigger, event_type):
        """Trigger notification backend to send and event.

        :param check: CheckInstance instance
        :param trigger: Object instance
        :param event_type: str `trigger` or `resolve`
        """
        self._preprocessor.load()
        self._preprocessor.preprocess(check, trigger, event_type)
        self.notification.send(check, trigger, event_type)

    def translate_unknown_status(self, cached_results, trigger):
        if trigger.result.status == RESULT_UNKNOWN:
            try:
                prev_result = cached_results[-1]
                if prev_result.status in FAILED_STATUSES:
                    trigger.result.status = RESULT_UNKNOWN_FAILED
                    trigger.result.message = prev_result.message
                else:
                    trigger.result.status = RESULT_UNKNOWN_OK
            except IndexError:
                trigger.result.status = RESULT_UNKNOWN_OK

    @stats.timer(hostname=True)
    def execute(self, check: Dict) -> Tuple[int, Optional[str]]:
        events_to_sent = []
        check = CheckInstance(check)
        logger.debug(
            'Executing alerter task for check=`%s`.', check.id,
            extra={'check_id': check.id}
        )
        status, event_type = RESULT_UNKNOWN, None
        for trigger in check.triggers:
            debounce = trigger.debounce or check.debounce or 1
            debounce = max(int(debounce), 1)
            repeat = trigger.repeat_every or 0
            rate_loss, rate_window = decouple_error_rate(trigger.error_rate)
            cached_results = self.get_cached_result(
                check.uuid, trigger.uuid, max(debounce, repeat, rate_window)
            )
            self.translate_unknown_status(cached_results, trigger)
            cached_results.append(CachedResult(
                trigger.result.status,
                getattr(trigger.result, 'hysteresis', RESULT_OK),
                False, ""
            ))

            status, event_type = self.analyze_result(
                cached_results, debounce, repeat, rate_loss, rate_window
            )

            # if trigger status is known and overall status returned from
            # `analyze_result` method is failed, then change trigger status
            # to that value
            if status == RESULT_FAILED and trigger.result.status == RESULT_OK:
                trigger.result.status = status
            # in case hysteresis has status 1, but everything is ok, we should
            # erase trigger.result.message
            elif status == RESULT_OK and \
                    trigger.result.hysteresis in FAILED_STATUSES:
                trigger.result.message = ''

            if event_type:
                events_to_sent.append((event_type, trigger))

            kw = dict(worker_fqdn=check.worker_fqdn)
            if trigger.meta.links.graphite_url:
                kw['graphite_url'] = trigger.meta.links.graphite_url.href
            self.driver.save_result(
                check.uuid, trigger,
                check.scheduled_time,
                check.execution_time,
                datetime.now(tz=tzutc()),
                bool(event_type),
                check.service_id,
                **kw
            )

        for event_type, trigger in events_to_sent:
            self.send_alert(check, trigger, event_type)

        return status, event_type


text:
      Google App Engine Boilerplate

      Félicitations vous êtes sur votre page propulsée par Boilerplate de Google App Engine.

Apprenez pourquoi ça swing avec Boilerplate
      ou simplement téléchargez le Code Source
      pour vous aider à créer votre application.


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Form [component] - SUIT</title>
<link rel="stylesheet" href="../build/test.css">

SUIT CSS: Form component tests

.Form

renders descendant `fieldset` without any border, margin, or padding

        <form class="Form">
            <fieldset class="Form-field">Fieldset</fieldset>
        </form>

renders standard form

        <form class="Form">

                Label
                <input class="Form-input" placeholder="Input">

                Label
                <textarea class="Form-input">Textarea</textarea>

                <select class="Form-input">
                    <option>Select</option>
                </select>

        </form>

.Form-input

does something else

        <input class="Form-input" placeholder="Input">

.Form-field--stacked

does something else

.Form--inline

does something else

        <form class="Form Form--inline">

                Email
                <input class="Form-input" id="email1" type="email" placeholder="Email">

                Password
                <input class="Form-input" id="password1" type="password" placeholder="Password">

                <input id="remember1" type="checkbox">
                Remember me

                <button type="submit" class="Button">Sign in</button>

        </form>

.Form (requires Grid, Button, utils-dimension, utils-display, utils-text

does something else

        <form class="Form">

                        Choose username

                        <input class="Form-input" id="name2" placeholder="">
                        Too short

                        Password

                        <input class="Form-input" id="password2">
                        Very strong

                        Pick a category

                        <select class="Form-input" id="cat2">
                            <option>Mustaches of the world</option>
                            <option>Long lost music</option>
                            <option>Interesting colours</option>
                        </select>

                        <input id="remember" type="checkbox">
                        Remember me

                            <button type="submit" class="Button">Sign up</button>

        </form>

.Form stacked (requires Button, utils-display)

does something else

        <form class="Form">

                Email
                <input class="Form-input" id="email3" type="email" placeholder="Email">
                Success and error message on the side when there is space

                Password
                <input class="Form-input" id="password3" type="password" placeholder="Password">

Success and error message underneath

                Country
                <select class="Form-input" id="country3">
                    <option>UK</option>
                    <option>US</option>
                    <option>France</option>
                </select>

                Additional details
                <textarea class="Form-input" id="extra3" placeholder="Your comment"></textarea>

                    <input type="radio" name="radioname"> Yes

                    <input type="radio" name="radioname"> No

                <input type="checkbox" id="remember3">
                Remember me

                    <button type="submit" class="Button">Sign in</button>

        </form>


text:
<?php
/**
 * Created by PhpStorm.
 * User: toby
 * Date: 23/02/15
 * Time: 13:15
 */

namespace CubicMushroom\Slim\Middleware\DoctrineORMMiddleware\Exception;

class InvalidArgumentException extends AbstractException
{

    /**
     * @var string
     */
    protected $reason;

    /**
     * @param array $additionalProperties
     *
     * @return string
     */
    protected static function getDefaultMessage(array $additionalProperties)
    {
        $message = 'Invalid argument provided';

        if (isset($additionalProperties['reason'])) {
            $message .= ' - ' . $additionalProperties['reason'];
        }

        return $message;
    }

    // -----------------------------------------------------------------------------------------------------------------
    // Getters and Setters
    // -----------------------------------------------------------------------------------------------------------------

    /**
     * @return string
     */
    public function getReason()
    {
        return $this->reason;
    }

    /**
     * @param string $reason
     *
     * @return $this
     */
    public function setReason($reason)
    {
        $this->reason = $reason;

        return $this;
    }
}


text:
[![Build Status](https://secure.travis-ci.org/Fetcher/g11n.png)](http://travis-ci.org/Fetcher/g11n) [![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/Fetcher/g11n)

Globalization (g11n) is a Ruby Gem for easy language file handling aimed at internationalized projects.

The developers of g11n are well aware of the existence of both i18n and r18n Ruby Gems, but wanted a new approach (specially in terms of simplicity) and this is the answer.

## Usage

G11n assumes you will have a series of language files written in YAML in an accessible folder to your project, named after each language's locale and followed by the YAML extension. Both `.yaml` and `.yml` extensions are recognized.

The default path for that folder is `translations/`. So, for example, if you have a file named `translations/it.yaml` that reads as...

```yaml
# ./translations/it.yaml
home:
  title: La pasta della nonna
  menu:
    preparation: Comme farla
    eating: Comme si mangia
    wine: Con che si accompagna
```

... you can, in your project, insert the following code and get the internationalized strings:

```ruby
# .script.rb
require "g11n"

G11n.locale :it                             # Configures G11n to use italian. Default is "en"
G11n.locale                                 # => :it

G11n.t.home.title                           # => "La pasta della nonna"
G11n.t.home.menu.wine                       # => "Con che si accompagna"
```

## Installation

    gem install g11n

### Or when using Bundler

Add this line to your application's Gemfile:

    gem 'g11n'

And then execute:

    bundle install

## Configuring

Configuration is straight forward. You are using another directory for your language files? Just `G11n.path "your/path"`. You want to change the locale? `G11n.locale :yours`.

For example, a translations file in a non-standard folder:

```yaml
# ./i18ns/ru.yml
home:
  land: Российская Федерация
```

And a script in the base folder:

```ruby
# ./script.rb
require "g11n"

G11n.path "i18ns"
G11n.locale :ru

G11n.t.home.land                           # => "Российская Федерация"
```

Also, the `G11n::DSL` module can be included in any object of class you want to use the `#t` method more confortably.

## Use it in Sinatra
The G11n DSL (the `#t` and `#translate` methods) are available as a module unimaginatively called `G11n::DSL`. You can of course include it into your helpers as easy as:

```ruby
# .app.rb
require 'sinatra'
require 'g11n'

helpers G11n::DSL

G11n.locale :es

get '/' do
  t.welcome                             # => "¡Bienvenido, amigo!"
                                        # as described in es.yaml
end
```

```yaml
# .translations/es.yaml
welcome: ¡Bienvenido, amigo!
```

It works in modular style too.

## Future
- Change the Configuration DSL so #translations_path or #translations or something like that is used to set the path, so that the full DSL can be included as helper in Sinatra. Deprecate Configuration#path
- Add support to reload. Store "last read" date and reload the file if changed. Disable in production mode (good reason to add Sinatra Extension: disabling in production and autoincluding the DSL)
- Document usage of Ruby's `String` interpolation in G11n
- Add support for named string interpolation using the same `%` operator. Add an alias to the `%` interpolation operation, some method name easier to remember (even if its longer)
- Add support for string arguments to get further Rails I18n compatibility
- Add flag to activate Rails I18n compatibility mode
- Add support for locale as argument of Translator#translate

### Date, number, ... helpers
Rails provide a nice functionality for number and date helpers that, since relays on words, ends up needing internationalizations. G11n is compatible with Rails I18n approach, that uses YAML, but not entirely since G11n uses different files for each locale.

In the case that a helper library that doesn't depend on Rails with those methods its found in the wild, G11n should be someway be made compatible.

### Package Managers! Dictionaries!
Related to the helpers above... well, is known that many words need to be translated only once. A package manager for G11n will do the trick of getting a lot of translations easier.

Of course, since one cannot know the handler for certain word in every case, G11n should also implement a Chain of Responsibility to discover standard handlers if none is defined.

## Testing

Cucumber features and RSpec specs are provided to check functionality.

## License

Copyright (C) 2012 Fetcher

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


text:
<?php

namespace Google\Service\Dataflow;

class WorkerHealthReport extends \Google\Collection
{
  protected $collection_key = 'pods';
  /**
   * @var string
   */
  public $msg;
  /**
   * @var array[]
   */
  public $pods;
  /**
   * @var string
   */
  public $reportInterval;
  /**
   * @var string
   */
  public $vmBrokenCode;
  /**
   * @var bool
   */
  public $vmIsBroken;
  /**
   * @var bool
   */
  public $vmIsHealthy;
  /**
   * @var string
   */
  public $vmStartupTime;

  /**
   * @param string
   */
  public function setMsg($msg)
  {
    $this->msg = $msg;
  }
  /**
   * @return string
   */
  public function getMsg()
  {
    return $this->msg;
  }
  /**
   * @param array[]
   */
  public function setPods($pods)
  {
    $this->pods = $pods;
  }
  /**
   * @return array[]
   */
  public function getPods()
  {
    return $this->pods;
  }
  /**
   * @param string
   */
  public function setReportInterval($reportInterval)
  {
    $this->reportInterval = $reportInterval;
  }
  /**
   * @return string
   */
  public function getReportInterval()
  {
    return $this->reportInterval;
  }
  /**
   * @param string
   */
  public function setVmBrokenCode($vmBrokenCode)
  {
    $this->vmBrokenCode = $vmBrokenCode;
  }
  /**
   * @return string
   */
  public function getVmBrokenCode()
  {
    return $this->vmBrokenCode;
  }
  /**
   * @param bool
   */
  public function setVmIsBroken($vmIsBroken)
  {
    $this->vmIsBroken = $vmIsBroken;
  }
  /**
   * @return bool
   */
  public function getVmIsBroken()
  {
    return $this->vmIsBroken;
  }
  /**
   * @param bool
   */
  public function setVmIsHealthy($vmIsHealthy)
  {
    $this->vmIsHealthy = $vmIsHealthy;
  }
  /**
   * @return bool
   */
  public function getVmIsHealthy()
  {
    return $this->vmIsHealthy;
  }
  /**
   * @param string
   */
  public function setVmStartupTime($vmStartupTime)
  {
    $this->vmStartupTime = $vmStartupTime;
  }
  /**
   * @return string
   */
  public function getVmStartupTime()
  {
    return $this->vmStartupTime;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(WorkerHealthReport::class, 'Google_Service_Dataflow_WorkerHealthReport');


text:
package org.efix.message.field;

import org.efix.util.ByteSequence;
import org.efix.util.ByteSequenceWrapper;

public class QuoteCondition {

    public static final ByteSequence RESERVED_SAM = ByteSequenceWrapper.of("0");
    public static final ByteSequence NO_ACTIVE_SAM = ByteSequenceWrapper.of("1");
    public static final ByteSequence RESTRICTED = ByteSequenceWrapper.of("2");
    public static final ByteSequence OPEN_ACTIVE = ByteSequenceWrapper.of("A");
    public static final ByteSequence CLOSED_INACTIVE = ByteSequenceWrapper.of("B");
    public static final ByteSequence EXCHANGE_BEST = ByteSequenceWrapper.of("C");
    public static final ByteSequence CONSOLIDATED_BEST = ByteSequenceWrapper.of("D");
    public static final ByteSequence LOCKED = ByteSequenceWrapper.of("E");
    public static final ByteSequence CROSSED = ByteSequenceWrapper.of("F");
    public static final ByteSequence DEPTH = ByteSequenceWrapper.of("G");
    public static final ByteSequence FAST_TRADING = ByteSequenceWrapper.of("H");
    public static final ByteSequence NON_FIRM = ByteSequenceWrapper.of("I");
    public static final ByteSequence OUTRIGHT_PRICE = ByteSequenceWrapper.of("J");
    public static final ByteSequence IMPLIED_PRICE = ByteSequenceWrapper.of("K");
    public static final ByteSequence MANUAL_SLOW_QUOTE = ByteSequenceWrapper.of("L");
    public static final ByteSequence DEPTH_ON_OFFER = ByteSequenceWrapper.of("M");
    public static final ByteSequence DEPTH_ON_BID = ByteSequenceWrapper.of("N");
    public static final ByteSequence CLOSING = ByteSequenceWrapper.of("O");
    public static final ByteSequence NEWS_DISSEMINATION = ByteSequenceWrapper.of("P");
    public static final ByteSequence TRADING_RANGE = ByteSequenceWrapper.of("Q");
    public static final ByteSequence ORDER_INFLUX = ByteSequenceWrapper.of("R");
    public static final ByteSequence DUE_TO_RELATED = ByteSequenceWrapper.of("S");
    public static final ByteSequence NEWS_PENDING = ByteSequenceWrapper.of("T");
    public static final ByteSequence ADDITIONAL_INFO = ByteSequenceWrapper.of("U");
    public static final ByteSequence ADDITIONAL_INFO_DUE_TO_RELATED = ByteSequenceWrapper.of("V");
    public static final ByteSequence RESUME = ByteSequenceWrapper.of("W");
    public static final ByteSequence VIEW_OF_COMMON = ByteSequenceWrapper.of("X");
    public static final ByteSequence VOLUME_ALERT = ByteSequenceWrapper.of("Y");
    public static final ByteSequence ORDER_IMBALANCE = ByteSequenceWrapper.of("Z");
    public static final ByteSequence EQUIPMENT_CHANGEOVER = ByteSequenceWrapper.of("a");
    public static final ByteSequence NO_OPEN = ByteSequenceWrapper.of("b");
    public static final ByteSequence REGULAR_ETH = ByteSequenceWrapper.of("c");
    public static final ByteSequence AUTOMATIC_EXECUTION = ByteSequenceWrapper.of("d");
    public static final ByteSequence AUTOMATIC_EXECUTION_ETH = ByteSequenceWrapper.of("e");
    public static final ByteSequence FAST_MARKET_ETH = ByteSequenceWrapper.of("f");
    public static final ByteSequence INACTIVE_ETH = ByteSequenceWrapper.of("g");
    public static final ByteSequence ROTATION = ByteSequenceWrapper.of("h");
    public static final ByteSequence ROTATION_ETH = ByteSequenceWrapper.of("i");
    public static final ByteSequence HALT = ByteSequenceWrapper.of("j");
    public static final ByteSequence HALT_ETH = ByteSequenceWrapper.of("k");
    public static final ByteSequence DUE_TO_NEWS_DISSEMINATION = ByteSequenceWrapper.of("l");
    public static final ByteSequence DUE_TO_NEWS_PENDING = ByteSequenceWrapper.of("m");
    public static final ByteSequence TRADING_RESUME = ByteSequenceWrapper.of("n");
    public static final ByteSequence OUT_OF_SEQUENCE = ByteSequenceWrapper.of("o");
    public static final ByteSequence BID_SPECIALIST = ByteSequenceWrapper.of("p");
    public static final ByteSequence OFFER_SPECIALIST = ByteSequenceWrapper.of("q");
    public static final ByteSequence BID_OFFER_SPECIALIST = ByteSequenceWrapper.of("r");
    public static final ByteSequence END_OF_DAY_SAM = ByteSequenceWrapper.of("s");
    public static final ByteSequence FORBIDDEN_SAM = ByteSequenceWrapper.of("t");
    public static final ByteSequence FROZEN_SAM = ByteSequenceWrapper.of("u");
    public static final ByteSequence PREOPENING_SAM = ByteSequenceWrapper.of("v");
    public static final ByteSequence OPENING_SAM = ByteSequenceWrapper.of("w");
    public static final ByteSequence OPEN_SAM = ByteSequenceWrapper.of("x");
    public static final ByteSequence SURVEILLANCE_SAM = ByteSequenceWrapper.of("y");
    public static final ByteSequence SUSPENDED_SAM = ByteSequenceWrapper.of("z");
    public static final ByteSequence NO_MARKET_ACTIVITY = ByteSequenceWrapper.of("1000");
    public static final ByteSequence NO_DATA_AVAILABLE = ByteSequenceWrapper.of("1001");
    public static final ByteSequence NOT_APPLICABLE = ByteSequenceWrapper.of("1002");
    public static final ByteSequence AMOUNT_THRESHOLD_EXCEEDED = ByteSequenceWrapper.of("1003");

}


text:
@interface PodsDummy_MARNetwork : NSObject
@end
@implementation PodsDummy_MARNetwork
@end


text:
package com.github.twitch4j.helix.domain;

import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Data
@Setter(AccessLevel.PRIVATE)
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class TeamMember extends Team {

    /**
     * User ID of the broadcaster.
     */
    private String broadcasterId;

    /**
     * Display name of the broadcaster.
     */
    private String broadcasterName;

    /**
     * Login of the broadcaster.
     */
    private String broadcasterLogin;

}


text:
describe 'TzRule'
	describe 'creating a rule object from a tzdata line'
		rule = new Whendle.TzRule('Rule	Tunisia	1939	only	-	Apr	15	23:00s	1:00	S')

		it 'should have a NAME value'
			rule.NAME.should.be 'Tunisia'
		end

		it 'should have a FROM value'
			rule.FROM.should.be '1939'
		end

		it 'should have a TO value'
			rule.TO.should.be 'only'
		end

		it 'should have a TYPE value'
			rule.TYPE.should.be '-'
		end

		it 'should have an IN value'
			rule.IN.should.be 'Apr'
		end

		it 'should have an ON value'
			rule.ON.should.be '15'
		end

		it 'should have an AT value'
			rule.AT.should.be '23:00'
		end

		it 'should have a SAVE value'
			rule.SAVE.should.be '1:00'
		end

		it 'should have a LETTERS value'
			rule.LETTERS.should.be 'S'
		end
	end
end


text:
out = java.lang.System.out;

var SysUtility = {
    restPost : function restPost(url, params, settings, data) {
        var restCaller = new com.kahuna.logic.lib.rest.RestCaller(this);
        var result = restCaller.post(url, params, settings, data);
        return result;
    },

    restGet : function restGet(url, params, settings) {
        var restCaller = new com.kahuna.logic.lib.rest.RestCaller(this);
        var result = restCaller.get(url, params, settings);
        return result;
    }
};

// load the class
load("StormpathSecurityProvider.js");

// configuration needed for testing
var configSetup = {
    stormpathID : "OUXKJKKW82ZX2IRMTPPBVYDQX",
    stormpathSecret: "F99Sz5llVDM0Y4X7FVSZCgYGTos5rJ2/A5nPLkB476U",
    stormpathLoginID : "5u5PQe9griTl6Ey386yXzz"
};

// this is how the server creates the security object
var stormObject = stormpathSecurityProviderCreate();
stormObject.configure(configSetup);

var payload = {
    username: "David",
    password: "Password$1"
};

out.println("------------- testing authenticate with good payload");
var result = stormObject.authenticate(payload);
out.println(JSON.stringify(result, null, 2));
out.println("-------------");

out.println("------------- testing authenticate with bad payload");
badPayload = {
    username: "DavidBAD",
    password: "Password$1"
};

result = stormObject.authenticate(badPayload);
out.println(JSON.stringify(result, null, 2));
out.println("-------------");

out.println("------------- testing getAllGroups");
result = stormObject.getAllGroups();
out.println(JSON.stringify(result, null, 2));
out.println("-------------");

out.println("------------- testing getLoginInfo");
result = stormObject.getLoginInfo();
out.println(JSON.stringify(result, null, 2));
out.println("First field is " + result.fields[0].name);
out.println("-------------");

out.println("------------- testing getConfigInfo");
result = stormObject.getConfigInfo();
out.println(JSON.stringify(result, null, 2));
out.println("First config prop is " + result.fields[0].name);
out.println("-------------");


text:
import sys
from itertools import chain

import load_path
from mordred import descriptors
from mordred._base.descriptor import is_descriptor_class

load_path.nop()

class Generator(object):
    def __init__(self, mdl):
        self.mdl = mdl

    def header(self):
        h = self.mdl.__name__ + ' module'
        yield h
        yield '=' * len(h)
        yield ''

    def descriptor(self, desc):
        excludes = set([
            'as_argument', 'calculate', 'coord', 'dependencies', 'fail',
            'is_descriptor_class', 'mol', 'parameters', 'preset',
            'rethrow_na', 'rethrow_zerodiv'
        ])
        docs = [m for m in dir(desc) if m[:1] != '_' if m not in excludes]

        yield '.. autoclass:: {}.{}'.format(self.mdl.__name__, desc.__name__)
        yield '    :members: {}'.format(', '.join(docs))
        yield '    :undoc-members:'
        yield '    :show-inheritance:'
        yield ''

    def member(self, member):
        if is_descriptor_class(member):
            for line in self.descriptor(member):
                yield line
        else:
            raise ValueError('unknown member {} in {}'.format(member, self.mdl.__name__))

    def members(self):
        for m in self.mdl.__all__:
            for line in self.member(getattr(self.mdl, m)):
                yield line

    def module(self):
        yield '.. automodule:: {}'.format(self.mdl.__name__)

    def print(self, file=sys.stdout):
        for line in chain(self.header(), self.module(), self.members()):
            print(line, file=file)

if __name__ == '__main__':
    print('Submodules')
    print('----------')
    print('')
    print('.. toctree::')

    for mdl in descriptors.all:
        print('    ' + mdl.__name__)
        with open('api/{}.rst'.format(mdl.__name__), 'w') as f:
            Generator(mdl).print(file=f)


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context">

</beans>


text:
#ifndef PANGOLIN_THREADED_WRITE_H
#define PANGOLIN_THREADED_WRITE_H

#include <iostream>
#include <streambuf>
#include <fstream>

#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>

namespace pangolin
{

class threadedfilebuf : public std::streambuf
{
public:
    threadedfilebuf(const std::string& filename, unsigned int buffer_size_bytes);
    ~threadedfilebuf();

    void operator()();

protected:
    //! Override streambuf::xsputn for asynchronous write
    std::streamsize xsputn(const char * s, std::streamsize n);

    std::filebuf file;
    char* mem_buffer;
    int mem_size;
    int mem_max_size;
    int mem_start;
    int mem_end;

    boost::mutex update_mutex;
    boost::condition_variable cond_queued;
    boost::condition_variable cond_dequeued;
    boost::thread write_thread;
};

}

#endif // PANGOLIN_THREADED_WRITE_H


text:
package cmwell.ctrl.hc

import akka.util.Timeout
import cmwell.ctrl.config.Config._
import cmwell.ctrl.controllers.CmwellController
import cmwell.ctrl.server._
import cmwell.ctrl.tasks.TaskExecutorActor
import k.grid.dmap.impl.inmem.InMemDMap
import k.grid.service.ServiceInitInfo
import k.grid.Grid
import org.slf4j.LoggerFactory

import scala.concurrent.Await
import scala.util.{Failure, Success, Try}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by michael on 4/11/16.
 */
object HealthControl {
  private val clusterLogger = LoggerFactory.getLogger("cluster_state")

  lazy val services = Map("CassandraMonitorActor" -> ServiceInitInfo(classOf[CassandraMonitorActor], None, Grid.hostName, 0, hcSampleInterval),
                     "DcMonitorActor" -> ServiceInitInfo(classOf[DcMonitorActor], None, Grid.hostName, 0, hcSampleInterval),
                     "HealthActor" -> ServiceInitInfo(classOf[HealthActor], None))

  def init: Unit = {
    import akka.pattern.ask
    implicit val timeout = Timeout(3.seconds)

    def joinCtrlGrid: Unit = {
      val forceMajor = sys.env.get("FORCE").isDefined
      clusterLogger.info(s"force majour is $forceMajor")
      Try(Await.result(cmwell.util.concurrent.retry(10, 5.seconds){ HealthActor.ref ? NodeJoinRequest(host) }.mapTo[JoinResponse], 30.seconds)) match {
        case Success(r) =>
          clusterLogger.info(s"$host got $r from the cluster $clusterName")
          r match {
            case response if forceMajor =>
              clusterLogger.info(s"$host received response $response from the cluster $clusterName. Doing force majour will boot cm-well components.")
              HealthActor.ref ! RemoveFromDownNodes(host)
              CmwellController.start
            case JoinOk =>
              CmwellController.start
            case JoinShutdown =>
              //CmwellController.clearData
              sys.exit(0)
            case JoinBootComponents =>
              CmwellController.start
          }
        case Failure(err) =>
          clusterLogger.error(err.getMessage, err)
          clusterLogger.info(s"$host didn't receive response from the cluster $clusterName, will boot cm-well components.")
          CmwellController.start
      }
    }

    Grid.create(classOf[CommandActor], commandActorName)

    Grid.create(classOf[WebMonitorActor], "WebMonitorActor", Grid.hostName, 0, hcSampleInterval)
    Grid.create(classOf[BatchMonitorActor], "BatchMonitorActor", Grid.hostName, 0, batchSampleInterval)
    Grid.create(classOf[ElasticsearchMonitorActor], "ElasticsearchMonitorActor", Grid.hostName, 0, hcSampleInterval)
    Grid.create(classOf[SystemMonitorActor], "SystemMonitorActor", Grid.hostName, 0, hcSampleInterval)
    Grid.create(classOf[ZookeeperMonitorActor], "ZookeeperMonitorActor", Grid.hostName, 0, hcSampleInterval)
    Grid.create(classOf[KafkaMonitorActor], "KafkaMonitorActor", Grid.hostName, 0, hcSampleInterval)

    Grid.create(classOf[PingActor], "PingActor")
    Grid.serviceRef(TaskExecutorActor.name)
    //Thread.sleep(20000)
   // Grid.system.scheduler.scheduleOnce(20.seconds) {
      joinCtrlGrid
      InMemDMap.aggregate("knownHosts", host)
    //}
  }
}