text:
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// PolymorphismOperations operations.
    /// </summary>
    public partial interface IPolymorphismOperations
    {
        /// <summary>
        /// Get complex types that are polymorphic
        /// </summary>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Fish>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
        /// <summary>
        /// Put complex types that are polymorphic
        /// </summary>
        /// <param name='complexBody'>
        /// Please put a salmon that looks like this:
        /// {
        /// 'fishtype':'Salmon',
        /// 'location':'alaska',
        /// 'iswild':true,
        /// 'species':'king',
        /// 'length':1.0,
        /// 'siblings':[
        /// {
        /// 'fishtype':'Shark',
        /// 'age':6,
        /// 'birthday': '2012-01-05T01:00:00Z',
        /// 'length':20.0,
        /// 'species':'predator',
        /// },
        /// {
        /// 'fishtype':'Sawshark',
        /// 'age':105,
        /// 'birthday': '1900-01-05T01:00:00Z',
        /// 'length':10.0,
        /// 'picture': new Buffer([255, 255, 255, 255,
        /// 254]).toString('base64'),
        /// 'species':'dangerous',
        /// },
        /// {
        /// 'fishtype': 'goblin',
        /// 'age': 1,
        /// 'birthday': '2015-08-08T00:00:00Z',
        /// 'length': 30.0,
        /// 'species': 'scary',
        /// 'jawsize': 5
        /// }
        /// ]
        /// };
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
        /// <summary>
        /// Put complex types that are polymorphic, attempting to omit
        /// required 'birthday' field - the request should not be allowed
        /// from the client
        /// </summary>
        /// <param name='complexBody'>
        /// Please attempt put a sawshark that looks like this, the client
        /// should not allow this data to be sent:
        /// {
        /// "fishtype": "sawshark",
        /// "species": "snaggle toothed",
        /// "length": 18.5,
        /// "age": 2,
        /// "birthday": "2013-06-01T01:00:00Z",
        /// "location": "alaska",
        /// "picture": base64(FF FF FF FF FE),
        /// "siblings": [
        /// {
        /// "fishtype": "shark",
        /// "species": "predator",
        /// "birthday": "2012-01-05T01:00:00Z",
        /// "length": 20,
        /// "age": 6
        /// },
        /// {
        /// "fishtype": "sawshark",
        /// "species": "dangerous",
        /// "picture": base64(FF FF FF FF FE),
        /// "length": 10,
        /// "age": 105
        /// }
        /// ]
        /// }
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(Fish complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
    }
}


text:
#include "soundex/charutil.h"

#include <cctype>
#include <string>

namespace gherkin_demo {

char CharUtil::lower(const char letter) {
  return std::tolower(static_cast<unsigned char>(letter));
}

bool CharUtil::isVowel(const char letter) {
  static std::string vowels("aeiouy");
  return vowels.find(lower(letter)) != std::string::npos;
}

} /* namespace gherkin_demo */

redpajama_set_name: RedPajamaGithub


text:
* [What is a Feature Branch?](what-is-a-feature-branch.md)
  * [Why Make one?](why-make-one.md)
  * [Picking a Name](picking-a-name.md)
  * [Creating Your Feature Branch](creating-your-feature-branch.md)
  * [One Feature, One Branch](one-feature-one-branch.md)
  * [Recap: 5 Elements of a Good Feature Branch](recap-5-elements-of-a-good-feature-branch.md)


text:
package org.jboss.pnc.restclient.websocket;

import java.util.function.Consumer;

/**
 * Dispatchers are labeled Consumers of generic String WebSocket messages.
 *
 * @author Jan Michalov
 */
public interface Dispatcher extends Consumer<String> {
}


text:
package net.runelite.client.plugins.objectindicators;

import com.google.common.base.Strings;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.Stroke;
import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.DecorativeObject;
import net.runelite.api.GameObject;
import net.runelite.api.GroundObject;
import net.runelite.api.ObjectComposition;
import net.runelite.api.TileObject;
import net.runelite.api.WallObject;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.outline.ModelOutlineRenderer;
import net.runelite.client.util.ColorUtil;

class ObjectIndicatorsOverlay extends Overlay
{
	private final Client client;
	private final ObjectIndicatorsConfig config;
	private final ObjectIndicatorsPlugin plugin;
	private final ModelOutlineRenderer modelOutlineRenderer;

	@Inject
	private ObjectIndicatorsOverlay(Client client, ObjectIndicatorsConfig config, ObjectIndicatorsPlugin plugin,
		ModelOutlineRenderer modelOutlineRenderer)
	{
		this.client = client;
		this.config = config;
		this.plugin = plugin;
		this.modelOutlineRenderer = modelOutlineRenderer;
		setPosition(OverlayPosition.DYNAMIC);
		setPriority(OverlayPriority.LOW);
		setLayer(OverlayLayer.ABOVE_SCENE);
	}

	@Override
	public Dimension render(Graphics2D graphics)
	{
		Stroke stroke = new BasicStroke((float) config.borderWidth());
		for (ColorTileObject colorTileObject : plugin.getObjects())
		{
			TileObject object = colorTileObject.getTileObject();
			Color color = colorTileObject.getColor();

			if (object.getPlane() != client.getPlane())
			{
				continue;
			}

			ObjectComposition composition = colorTileObject.getComposition();
			if (composition.getImpostorIds() != null)
			{
				// This is a multiloc
				composition = composition.getImpostor();
				// Only mark the object if the name still matches
				if (composition == null
					|| Strings.isNullOrEmpty(composition.getName())
					|| "null".equals(composition.getName())
					|| !composition.getName().equals(colorTileObject.getName()))
				{
					continue;
				}
			}

			if (color == null || !config.rememberObjectColors())
			{
				// Fallback to the current config if the object is marked before the addition of multiple colors
				color = config.markerColor();
			}

			if (config.highlightHull())
			{
				renderConvexHull(graphics, object, color, stroke);
			}

			if (config.highlightOutline())
			{
				modelOutlineRenderer.drawOutline(object, (int)config.borderWidth(), color, config.outlineFeather());
			}

			if (config.highlightClickbox())
			{
				Shape clickbox = object.getClickbox();
				if (clickbox != null)
				{
					Color clickBoxColor = ColorUtil.colorWithAlpha(color, color.getAlpha() / 12);
					OverlayUtil.renderPolygon(graphics, clickbox, color, clickBoxColor, stroke);
				}
			}

			if (config.highlightTile())
			{
				Polygon tilePoly = object.getCanvasTilePoly();
				if (tilePoly != null)
				{
					Color tileColor = ColorUtil.colorWithAlpha(color, color.getAlpha() / 12);
					OverlayUtil.renderPolygon(graphics, tilePoly, color, tileColor, stroke);
				}
			}
		}

		return null;
	}

	private void renderConvexHull(Graphics2D graphics, TileObject object, Color color, Stroke stroke)
	{
		final Shape polygon;
		Shape polygon2 = null;

		if (object instanceof GameObject)
		{
			polygon = ((GameObject) object).getConvexHull();
		}
		else if (object instanceof WallObject)
		{
			polygon = ((WallObject) object).getConvexHull();
			polygon2 = ((WallObject) object).getConvexHull2();
		}
		else if (object instanceof DecorativeObject)
		{
			polygon = ((DecorativeObject) object).getConvexHull();
			polygon2 = ((DecorativeObject) object).getConvexHull2();
		}
		else if (object instanceof GroundObject)
		{
			polygon = ((GroundObject) object).getConvexHull();
		}
		else
		{
			polygon = object.getCanvasTilePoly();
		}

		if (polygon != null)
		{
			OverlayUtil.renderPolygon(graphics, polygon, color, stroke);
		}

		if (polygon2 != null)
		{
			OverlayUtil.renderPolygon(graphics, polygon2, color, stroke);
		}
	}
}


text:
import {Manifest} from '../../manifest.js';
import {assert} from '../../../platform/chai-web.js';
import {PolicyRetentionMedium, PolicyAllowedUsageType} from '../policy.js';
import {assertThrowsAsync} from '../../../testing/test-util.js';
import {mapToDictionary} from '../../../utils/lib-utils.js';
import {TtlUnits, Persistence, Encryption, Capabilities, Ttl} from '../../capabilities.js';
import {IngressValidation} from '../ingress-validation.js';
import {deleteFieldRecursively} from '../../../utils/lib-utils.js';
import {EntityType, SingletonType, CollectionType, ReferenceType, TupleType, TypeVariable} from '../../../types/lib-types.js';

const customAnnotation = `
annotation custom
  targets: [Policy, PolicyTarget, PolicyField]
  retention: Source
  doc: 'custom annotation for testing'
`;

const personSchema = `
schema Person
  name: Text
  age: Number
  friends: [&Friend {name: Text, age: Number}]
`;

async function parsePolicy(str: string) {
  const manifest = await Manifest.parse(customAnnotation + personSchema + str);
  assert.lengthOf(manifest.policies, 1);
  return manifest.policies[0];
}

describe('policy', () => {
  it('can round-trip to string', async () => {
    const manifestString = `
${customAnnotation.trim()}
${personSchema.trim()}
@intendedPurpose(description: 'test')
@egressType(type: 'Logging')
@custom
policy MyPolicy {
  @maxAge(age: '2d')
  @allowedRetention(medium: 'Ram', encryption: false)
  @allowedRetention(medium: 'Disk', encryption: true)
  @custom
  from Person access {
    @allowedUsage(label: 'raw', usageType: 'join')
    @allowedUsage(label: 'truncated', usageType: 'egress')
    friends {
      @allowedUsage(label: 'redacted', usageType: '*')
      @custom
      age,
    },
    @custom
    name,
  }
  config SomeConfig {
    abc: '123'
    def: '456'
  }
}`.trim();
    const manifest = await Manifest.parse(manifestString);
    assert.strictEqual(manifest.toString(), manifestString);
  });

  it('rejects duplicate policy names', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {}
policy MyPolicy {}
`), 'A policy named MyPolicy already exists.');
  });

  it('policy annotations work', async () => {
    const policy = await parsePolicy(`
@intendedPurpose('test')
@egressType('Logging')
@custom
policy MyPolicy {}
`);
    assert.strictEqual(policy.name, 'MyPolicy');
    assert.strictEqual(policy.description, 'test');
    assert.strictEqual(policy.egressType, 'Logging');
    assert.lengthOf(policy.customAnnotations, 1);
    assert.strictEqual(policy.customAnnotations[0].name, 'custom');
  });

  it('handles missing policy annotations', async () => {
    const policy = await parsePolicy(`
policy MyPolicy {}
`);
    assert.isNull(policy.description);
    assert.isNull(policy.egressType);
  });

  it('allows arbitrary egress types', async () => {
    const policy = await parsePolicy(`
@egressType('SomeInventedEgressType')
policy MyPolicy {}
`);
    assert.strictEqual(policy.egressType, 'SomeInventedEgressType');
  });

  it('policy target annotations work', async () => {
    const policy = await parsePolicy(`
policy MyPolicy {
  @allowedRetention(medium: 'Disk', encryption: true)
  @allowedRetention(medium: 'Ram', encryption: false)
  @maxAge('2d')
  @custom
  from Person access {}
}`);
    assert.lengthOf(policy.targets, 1);
    const target = policy.targets[0];
    assert.strictEqual(target.schemaName, 'Person');
    assert.deepStrictEqual(target.retentions, [
      {
        medium: PolicyRetentionMedium.Disk,
        encryptionRequired: true,
      },
      {
        medium: PolicyRetentionMedium.Ram,
        encryptionRequired: false,
      },
    ]);
    assert.strictEqual(target.maxAge.count, 2);
    assert.strictEqual(target.maxAge.units, TtlUnits.Days);
    assert.lengthOf(target.customAnnotations, 1);
    assert.strictEqual(target.customAnnotations[0].name, 'custom');
  });

  it('handles missing target annotations', async () => {
    const policy = await parsePolicy(`
policy MyPolicy {
  from Person access {}
}
`);
    const target = policy.targets[0];
    assert.strictEqual(target.maxAge.millis, 0);
    assert.isEmpty(target.fields);
    assert.isEmpty(target.customAnnotations);
  });

  it('rejects unknown target types', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from UnknownType access {}
}`), `Unknown type name: UnknownType.`);
  });

  it('rejects duplicate targets', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from Person access {}
  from Person access {}
}`), `A definition for 'Person' already exists.`);
  });

  it('rejects duplicate retentions', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  @allowedRetention(medium: 'Ram', encryption: true)
  @allowedRetention(medium: 'Ram', encryption: true)
  from Person access {}
}`), '@allowedRetention has already been defined for Ram.');
  });

  it('rejects unknown retention mediums', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  @allowedRetention(medium: 'SomethingElse', encryption: false)
  from Person access {}
}`), 'Expected one of: Ram, Disk. Found: SomethingElse.');
  });

  it('rejects invalid maxAge', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  @maxAge('4x')
  from Person access {}
}`), 'Invalid ttl: 4x');
  });

  it('policy field annotations work', async () => {
    const policy = await parsePolicy(`
policy MyPolicy {
  from Person access {
    @allowedUsage(label: 'redacted', usageType: 'egress')
    @allowedUsage(label: 'redacted', usageType: 'join')
    @custom
    friends {
      @allowedUsage(label: 'truncated', usageType: 'join')
      @custom
      name,

      @allowedUsage(label: 'raw', usageType: '*')
      age,
    }
  }
}`);
    const fields = policy.targets[0].fields;
    assert.lengthOf(fields, 1);

    const friends = fields[0];
    assert.strictEqual(friends.name, 'friends');
    assert.deepStrictEqual(friends.allowedUsages, [
      {
        usage: PolicyAllowedUsageType.Egress,
        label: 'redacted',
      },
      {
        usage: PolicyAllowedUsageType.Join,
        label: 'redacted',
      },
    ]);
    assert.lengthOf(friends.customAnnotations, 1);
    assert.strictEqual(friends.customAnnotations[0].name, 'custom');

    const subfields = friends.subfields;
    assert.lengthOf(subfields, 2);
    const [name, age] = subfields;

    assert.strictEqual(name.name, 'name');
    assert.deepStrictEqual(name.allowedUsages, [{
      usage: PolicyAllowedUsageType.Join,
      label: 'truncated',
    }]);
    assert.lengthOf(name.customAnnotations, 1);
    assert.strictEqual(name.customAnnotations[0].name, 'custom');

    assert.strictEqual(age.name, 'age');
    assert.deepStrictEqual(age.allowedUsages, [{
      usage: PolicyAllowedUsageType.Any,
      label: '',
    }]);
    assert.lengthOf(age.customAnnotations, 0);
  });

  it('rejects unknown fields and subfields', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from Person access {
    unknownField,
  }
}`), /Schema 'Person \{.*\}' does not contain field 'unknownField'/);
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from Person access {
    friends {
      unknownField,
    }
  }
}`), /Schema 'Friend \{.*\}' does not contain field 'unknownField'/);
  });

  it('rejects unknown usage types', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from Person access {
    @allowedUsage(label: 'redacted', usageType: 'SomethingElse')
    age,
  }
}`), 'Expected one of: *, egress, join. Found: SomethingElse.');
  });

  it('rejects duplicate usage types', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from Person access {
    @allowedUsage(label: 'redacted', usageType: 'egress')
    @allowedUsage(label: 'redacted', usageType: 'egress')
    age,
  }
}`), `Usage of label 'redacted' for usage type 'egress' has already been allowed.`);
  });

  it('rejects duplicate fields', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from Person access {
    abc,
    abc,
  }
}`), `A definition for 'abc' already exists.`);
  });

  it('rejects duplicate subfields', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  from Person access {
    friends,
    friends {
      name
    }
  }
}`), `A definition for 'friends' already exists.`);
  });

  it('allowed usages defaults to any', async () => {
    const policyStr = `
policy MyPolicy {
  from Person access {
    age,
  }
}`.trim();
    const policy = await parsePolicy(policyStr);
    assert.deepStrictEqual(policy.targets[0].fields[0].allowedUsages, [{
      label: '',
      usage: PolicyAllowedUsageType.Any,
    }]);

    assert.strictEqual(policy.toManifestString(), policyStr);
  });

  it('policy configs work', async () => {
    const policy = await parsePolicy(`
policy MyPolicy {
  config MyConfig {
    abc: '123'
    def: '456'
  }
}`);
    assert.lengthOf(policy.configs, 1);
    const config = policy.configs[0];
    assert.strictEqual(config.name, 'MyConfig');
    assert.deepStrictEqual(mapToDictionary(config.metadata), {
      abc: '123',
      def: '456',
    });
  });

  it('rejects duplicate configs', async () => {
    await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
  config Abc {}
  config Abc {}
}`), `A definition for 'Abc' already exists.`);
  });

  it('converts to capabilities', async () => {
    const target = (await parsePolicy(`
policy MyPolicy {
  @allowedRetention(medium: 'Disk', encryption: true)
  @allowedRetention(medium: 'Ram', encryption: false)
  @maxAge('2d')
  @custom
  from Person access {}
}`)).targets[0];
    const capabilities = target.toCapabilities();
    assert.lengthOf(capabilities, 2);
    assert.isTrue(capabilities[0].isEquivalent(Capabilities.create([
        Persistence.onDisk(), new Encryption(true), Ttl.days(2)])),
        `Unexpected capabilities: ${capabilities[0].toDebugString()}`);
    assert.isTrue(capabilities[1].isEquivalent(
        Capabilities.create([Persistence.inMemory(), new Encryption(false), Ttl.days(2)])),
        `Unexpected capabilities: ${capabilities[1].toDebugString()}`);
  });

  it('restricts types according to policy', async () => {
    const manifest = await Manifest.parse(`
      schema Address
        number: Number
        street: Text
        city: Text
        country: Text

      schema Person
        name: Text
        phone: Text
        address: &Address
        otherAddresses: [&Address {street, city, country}]

      policy MyPolicy {
        from Person access {
          name,
          address {
            number
            street,
            city
          },
          otherAddresses {city, country}
        }
      }`);
    const policy = manifest.policies[0];
    const schema = policy.targets[0].getMaxReadSchema();
    const expectedSchemas = (await Manifest.parse(`
      schema Address
        number: Number
        street: Text
        city: Text
        country: Text

      schema Person
        name: Text
        address: &Address {number, street, city}
        otherAddresses: [&Address {city, country}]
      `)).schemas;
    deleteFieldRecursively(schema, 'location');
    deleteFieldRecursively(expectedSchemas, 'location');
    assert.deepEqual(schema, expectedSchemas['Person']);
  });

  it('restricts inline types according to policy', async () => {
    const manifest = await Manifest.parse(`
      schema Address
        number: Number
        street: Text
        city: Text
        country: Text

      schema Name
        first: Text
        last: Text

      schema Person
        name: inline Name
        phone: Text
        addresses: List<inline Address>

      policy MyPolicy {
        from Person access {
          name {
            last
          },
          addresses {
            number
            street,
            city
          },
        }
      }`);
    const policy = manifest.policies[0];
    const schema = policy.targets[0].getMaxReadSchema();
    const expectedSchemas = (await Manifest.parse(`
      schema Person
        name: inline Name {last: Text}
        addresses: List<inline Address {number: Number, street: Text, city: Text}>
      `)).schemas;
    deleteFieldRecursively(schema, 'location');
    deleteFieldRecursively(expectedSchemas['Person'], 'location');
    assert.deepEqual(schema, expectedSchemas['Person']);
  });

  it('restricts deeply nested schemas according to policy', async () => {
      const manifest = await Manifest.parse(`
        schema Name
          first: Text
          last: Text

        schema Address
          number: Number
          street: Text
          city: Text
          state: Text

        schema Person
          name: inline Name
          address: &Address

        schema Group
          persons: List<inline Person>

        policy MyPolicy {
          from Group access {
            persons {
              name {
                last
              },
              address {
                city
              }
            }
          }
        }`);
      const ingressValidation = new IngressValidation(manifest.policies);
      const maxReadSchemas = ingressValidation.maxReadSchemas;
      const expectedSchemas = (await Manifest.parse(`
        schema Name
          last: Text

        schema Address
          city: Text

        schema Person
          name: inline Name
          address: &Address

        schema Group
          persons: List<inline Person>
      `)).schemas;
    deleteFieldRecursively(maxReadSchemas['Group'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(expectedSchemas['Group'], 'location', {replaceWithNulls: true});
      assert.deepEqual(maxReadSchemas['Group'], expectedSchemas['Group']);
      // `Person` and `Name` are only referred to as an inline entities.
      // Therefore, they can only be written via `Group`. So, it is not
      // included in the max read schemas.
      //
      // On the other hand `Address` is a reference, and therefore, the
      // data might be written into a different store directly.
      // Therefore, we need to make sure that fields made accessible through
      // this policy are preserved by ingress restricting.
      assert.isFalse('Person' in maxReadSchemas);
      assert.isFalse('Name' in maxReadSchemas);
      assert.deepEqual(maxReadSchemas['Address'], expectedSchemas['Address']);
  });

  const manifestWithMultiplePolicies = `
    schema Address
      number: Number
      street: Text
      city: Text
      zip: Number
      state: Text
      country: Text

    schema Person
      name: Text
      phone: Text
      address: &Address
      otherAddresses: [&Address {street, city, country}]

    schema SensitiveInfo
      name: Text
      ssn: Text

    policy PolicyOne {
      from Person access {
        name,
        address {
          number,
          street
        }
      }
    }

    policy PolicyTwo {
      from Person access {
        address {
          street,
          city
        },
        otherAddresses {city}
      }
    }

    policy PolicyThree {
      from Person access {
        name,
        otherAddresses {country}
      }
    }

    policy PolicyFour {
      from Address access {
        state
      }
    }`;

  const maxReadSchemasForMultiplePolicies = `
    schema Address
      number: Number
      street: Text
      city: Text
      state: Text
      country: Text

    schema Person
      name: Text
      address: &Address {number, street, city}
      otherAddresses: [&Address {city, country}]
  `;

  it('restricts types according to multiple policies', async () => {
    const policies =
      (await Manifest.parse(manifestWithMultiplePolicies)).policies;
    const ingressValidation = new IngressValidation(policies);
    const maxReadSchemas = ingressValidation.maxReadSchemas;
    const expectedSchemas =
      (await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
    deleteFieldRecursively(maxReadSchemas['Person'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(maxReadSchemas['Address'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(expectedSchemas['Address'], 'location', {replaceWithNulls: true});
    assert.deepEqual(maxReadSchemas['Person'], expectedSchemas['Person']);
    assert.deepEqual(maxReadSchemas['Address'], expectedSchemas['Address']);
  });

  it('does not add nested inline entities to max read schemas', async () => {
    const manifest = await Manifest.parse(`
      schema Address
        number: Number
        street: Text
        city: Text
        country: Text

      schema Name
        first: Text
        last: Text

      schema Person
        name: inline Name
        phone: Text
        addresses: List<inline Address>

      policy MyPolicy {
        from Person access {
          name {
            last
          },
          addresses {
            number
            street,
            city
          },
        }
      }

      policy AddressPolicy {
        from Address access {
            city,
            country
        }
      }`);
    const ingressValidation = new IngressValidation(manifest.policies);
    const maxReadSchemas = ingressValidation.maxReadSchemas;
    const expectedSchemas = (await Manifest.parse(`
      schema Address
        city: Text
        country: Text

      schema Person
        name: inline Name {last: Text}
        addresses: List<inline Address {number: Number, street: Text, city: Text}>
    `)).schemas;
    deleteFieldRecursively(maxReadSchemas['Person'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(maxReadSchemas['Address'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(expectedSchemas['Address'], 'location', {replaceWithNulls: true});
    assert.deepEqual(maxReadSchemas['Person'], expectedSchemas['Person']);
    assert.deepEqual(maxReadSchemas['Address'], expectedSchemas['Address']);
    // 'Name' is not in `maxReadSchemas` because it only appears as
    // an inline entity.
    assert.isFalse('Name' in maxReadSchemas);
  });

  it('adds references in inline entities to max read schema', async () => {
      const manifest = await Manifest.parse(`
        schema Name
          first: Text
          last: Text

        schema Person
          name: &Name
          phone: Text

        schema Group
          persons: List<inline Person>

        policy MyPolicy {
          from Group access {
            persons {
              name {
                last
              }
            }
          }
        }`);
      const ingressValidation = new IngressValidation(manifest.policies);
      const maxReadSchemas = ingressValidation.maxReadSchemas;
      const expectedSchemas = (await Manifest.parse(`
        schema Name
          last: Text

        schema Person
          name: &Name

        schema Group
          persons: List<inline Person>
      `)).schemas;
      deleteFieldRecursively(maxReadSchemas['Group'], 'location', {replaceWithNulls: true});
      deleteFieldRecursively(expectedSchemas['Group'], 'location', {replaceWithNulls: true});
      assert.deepEqual(maxReadSchemas['Group'], expectedSchemas['Group']);
      // `Person` is only referred to as an inline entity. Therefore, it
      // can only be written via `Group`. So, it is not included in the
      // max read schemas.
      //
      // On the other hand `Name` is a reference, and therefore, the
      // data might be written into a different store directly.
      // Therefore, we need to make sure that fields made accessible through
      // this policy are preserved by ingress restricting.
      assert.isFalse('Person' in maxReadSchemas);
      assert.deepEqual(maxReadSchemas['Name'], expectedSchemas['Name']);
    });

  it('returns max read type according to multiple policies', async () => {
    const manifest = await Manifest.parse(manifestWithMultiplePolicies);
    const expectedSchemas =
      (await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
    const ingressValidation = new IngressValidation(manifest.policies);
    deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(expectedSchemas['Address'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(manifest.schemas['Person'], 'location', {replaceWithNulls: true});
    deleteFieldRecursively(manifest.schemas['Address'], 'location', {replaceWithNulls: true});
    const manifestPerson = new EntityType(manifest.schemas['Person']);
    const manifestAddress = new EntityType(manifest.schemas['Address']);
    const maxReadPerson = new EntityType(expectedSchemas['Person']);
    const maxReadAddress = new EntityType(expectedSchemas['Address']);

    // Entity type.
    assert.deepEqual(
      ingressValidation.getMaxReadType(manifestPerson),
      maxReadPerson);

    // Singleton type.
    assert.deepEqual(
      ingressValidation.getMaxReadType(new SingletonType(manifestPerson)),
      new SingletonType(maxReadPerson));

    // Reference type.
    assert.deepEqual(
      ingressValidation.getMaxReadType(new ReferenceType(manifestPerson)),
      new ReferenceType(maxReadPerson));

    // Tuple type.
    const manifestTuple = new TupleType([manifestPerson, manifestAddress]);
    const maxReadTuple = new TupleType([maxReadPerson, maxReadAddress]);
    assert.deepEqual(
      ingressValidation.getMaxReadType(manifestTuple),
      maxReadTuple);

    // Collection type.
    const manifestCollection = new CollectionType(manifestPerson);
    const maxReadCollection = new CollectionType(maxReadPerson);
    assert.deepEqual(
      ingressValidation.getMaxReadType(manifestCollection),
      maxReadCollection);
  });

  it('updates the write constraint of a type variable to get max read type',
     async () => {
       const manifest = await Manifest.parse(manifestWithMultiplePolicies);
       const expectedSchemas =
         (await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
       const ingressValidation = new IngressValidation(manifest.policies);
       deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
       deleteFieldRecursively(manifest.schemas['Person'], 'location', {replaceWithNulls: true});
       const manifestPerson = new EntityType(manifest.schemas['Person']);
       const maxReadPerson = new EntityType(expectedSchemas['Person']);
       const manifestCollection = new CollectionType(manifestPerson);
       const maxReadCollection = new CollectionType(maxReadPerson);

       // Type variable.
       // Only the canWriteSuperset will be replaced with the max read type.
       const typeVar = TypeVariable.make(
         '',
         /* canWriteSuperset = */manifestCollection,
         /* canReadSubset = */manifestCollection);
       const maxReadTypeVar = TypeVariable.make(
         '',
         /* canWriteSuperset = */maxReadCollection,
         /* canReadsubset = */manifestCollection);
       assert.deepEqual(ingressValidation.getMaxReadType(typeVar), maxReadTypeVar);

       const noWriteTypeVar = TypeVariable.make(
         '',
         /* canWriteSuperset = */manifestCollection,
         /* canReadSubset = */null);
       assert.deepEqual(ingressValidation.getMaxReadType(noWriteTypeVar), noWriteTypeVar);
     });

  it('returns correct type variable when write constraint is <= max read type',
     async () => {
       const manifest = await Manifest.parse(manifestWithMultiplePolicies);
       const expectedSchemas =
         (await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
       const manifestPerson = new EntityType(manifest.schemas['Person']);
       const ingressValidation = new IngressValidation(manifest.policies);

       // This represents a type that is a subset of the maxReadPerson.
       const personSubsetSchema = (await Manifest.parse(`
         schema Address
           number: Number
           street: Text
           city: Text
           state: Text
           country: Text

         schema Person
           address: &Address {number, city}
           otherAddresses: [&Address {city}]
       `)).schemas['Person'];

       // Sanity checks to ensure `personSubsetSchema` is subset of maxPersonSchema.
       deleteFieldRecursively(personSubsetSchema, 'location', {replaceWithNulls: true});
       assert.isTrue(
         expectedSchemas['Person'].isAtLeastAsSpecificAs(personSubsetSchema));
       assert.isFalse(
         personSubsetSchema.isAtLeastAsSpecificAs(expectedSchemas['Person']));
       const personSubset = new EntityType(personSubsetSchema);
       const subsetTypeVar = TypeVariable.make(
         '',
         /* canWriteSuperset = */manifestPerson,
         /* canReadSubset = */personSubset);
       const expectedTypeVar = TypeVariable.make(
         '',
         /* canWriteSuperset = */personSubset,
         /* canReadSubset = */personSubset);
       assert.deepEqual(
         ingressValidation.getMaxReadType(subsetTypeVar), expectedTypeVar);
     });

  const createTypeVarForSchema = async (
    name: string,
    writeSupersetFields: string|null,
    readSubsetFields: string|null
  ) => {
    // Create a type variable with the given strings as the write and
    // read fields of a schema `A`.
    const parseSchema = async (fields: string | null) => {
      if (fields == null) return null;
      const schema = (await Manifest.parse(`schema ${name} { ${fields} }`)).schemas['A'];
      deleteFieldRecursively(schema, 'location', {replaceWithNulls: true});
      return new EntityType(schema);
    };
    const canWriteSuperset = await parseSchema(writeSupersetFields);
    const canReadSubset = await parseSchema(readSubsetFields);
    return TypeVariable.make('', canWriteSuperset, canReadSubset);
  };

  it('updates write w/ max read type that is consistent with read', async () => {
    const manifest = await Manifest.parse(`
      schema A {a: Text, b:Text, c: Text, d: Text}

      policy P {
        from A access {a, b}
      }
    `);
    const ingressValidation = new IngressValidation(manifest.policies);
    const typeVar = await createTypeVarForSchema('A', null, 'a: Text, d: Text');
    const expected = await createTypeVarForSchema('A', 'a: Text', 'a: Text, d: Text');
    assert.deepEqual(
      ingressValidation.getMaxReadType(typeVar), expected);
  });

  it('updates write w/ max read type that is consistent with read (inline)', async () => {
    const manifest = await Manifest.parse(`
      schema A
        foo: inline Foo {a: Text, b: Text, c: Text, d: Text}

      policy P {
        from A access {
          foo {a, b}
        }
      }
    `);
    const ingressValidation = new IngressValidation(manifest.policies);
    const typeVar = await createTypeVarForSchema(
      'A', null, 'foo: inline Foo {a: Text, d: Text}');
    // The expected max read type variable should have `A { foo {a} }` for writeSuperset.
    const expected = await createTypeVarForSchema(
      'A',
      'foo: inline Foo {a: Text}',
      'foo: inline Foo {a: Text, d: Text}');

    // See getMaxReadType() implementation and `maxReadA` above.
    assert.deepEqual(
      ingressValidation.getMaxReadType(typeVar), expected);
  });

  it('uses resolved type of a typevar to get max read type', async () => {
    const manifest = await Manifest.parse(`
      schema A
        foo: inline Foo {a: Text, b: Text, c: Text, d: Text}

      policy P {
        from A access {
          foo {a, b}
        }
      }
    `);
    const ingressValidation = new IngressValidation(manifest.policies);
    const typeVar = await createTypeVarForSchema(
      'A',
      'foo: inline Foo {a: Text, d: Text}',
      'foo: inline Foo {a: Text, d: Text}');
    assert(typeVar.maybeResolve());
    const expected = await createTypeVarForSchema(
      'A',
      'foo: inline Foo {a: Text, b: Text}',
      null);
    assert.deepEqual(
      ingressValidation.getMaxReadType(typeVar), expected);
  });

  it('returns null for max read type if type has inaccessible schemas', async () => {
    const manifest = await Manifest.parse(manifestWithMultiplePolicies);
    const ingressValidation = new IngressValidation(manifest.policies);
    const manifestPerson = new EntityType(manifest.schemas['Person']);
    const manifestSensitiveInfo =
      new EntityType(manifest.schemas['SensitiveInfo']);

    // Entity type.
    assert.isNull(
      ingressValidation.getMaxReadType(manifestSensitiveInfo));

    // Singleton type.
    assert.isNull(
      ingressValidation.getMaxReadType(
        new SingletonType(manifestSensitiveInfo)));

    // Reference type.
    assert.isNull(
      ingressValidation.getMaxReadType(
        new ReferenceType(manifestSensitiveInfo)));

    // Tuple type.
    assert.isNull(
      ingressValidation.getMaxReadType(
        new TupleType([manifestPerson, manifestSensitiveInfo])));

    // Collection type.
    assert.isNull(
      ingressValidation.getMaxReadType(
        new CollectionType(manifestSensitiveInfo)));

    // Type variable.
    const typeVar = TypeVariable.make(
      '',
      /* canWriteSuperset = */manifestSensitiveInfo,
      /* canReadSubset = */manifestSensitiveInfo);

    // Unresolved type variable
    assert(!typeVar.isResolved());
    assert.isNull(ingressValidation.getMaxReadType(typeVar));

    // Resolved Type variable.
    assert(typeVar.maybeResolve());
    assert.isNull(ingressValidation.getMaxReadType(typeVar));
  });

  it('returns error details if type has inaccessible schemas', async () => {
    const manifest = await Manifest.parse(manifestWithMultiplePolicies);
    const ingressValidation = new IngressValidation(manifest.policies);
    const manifestPerson = new EntityType(manifest.schemas['Person']);
    const manifestSensitiveInfo =
      new EntityType(manifest.schemas['SensitiveInfo']);
    const errors = [];
    assert.isNull(
      ingressValidation.getMaxReadType(manifestSensitiveInfo, errors));
    assert.isTrue(errors.length === 1);
    assert.deepEqual(errors[0], `Schema 'SensitiveInfo' is not mentioned in policy`);
  });
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.Storage;
using Azure.Storage.Files.DataLake;
using Azure.Storage.Files.DataLake.Models;
using Azure.Storage.Sas;
using NUnit.Framework;

namespace Azure.Storage.Files.DataLake.Samples
{
    /// <summary>
    /// Demonstrate various authorization and authentication mechanisms.
    ///
    /// For more information, see
    /// https://docs.microsoft.com/en-us/azure/storage/common/storage-auth
    /// </summary>
    public class Sample02_Auth : SampleTest
    {
        /// <summary>
        /// Anonymously access a public DataLake File.
        ///
        /// You can enable anonymous, public read access to a container and its
        /// blobs in Azure Blob storage.  By doing so, you can grant read-only
        /// access to these resources without sharing your account key, and
        /// without requiring a shared access signature (SAS).
        ///
        /// Public read access is best for scenarios where you want certain
        /// blobs to always be available for anonymous read access.  For more
        /// fine-grained control, you can create a shared access signature.
        /// </summary>
        [Test]
        public async Task AnonymousAuthAsync()
        {
            // Make StorageSharedKeyCredential to pass to the serviceClient
            string accountName = StorageAccountName;
            string accountKey = StorageAccountKey;
            Uri serviceUri = StorageAccountBlobUri;
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);

            // Get a reference to a service Client
            DataLakeServiceClient service = new DataLakeServiceClient(serviceUri, sharedKeyCredential);

            // Get a reference to a filesystem named "sample-filesystem"
            DataLakeFileSystemClient filesystem = service.GetFileSystemClient(Randomize("sample-filesystem"));
            try
            {
                // Create a file that can be accessed publicly
                await filesystem.CreateAsync(PublicAccessType.FileSystem);
                DataLakeFileClient file = filesystem.GetFileClient(Randomize("sample-file"));
                await file.CreateAsync();

                // Append data to the file
                string fileContent = "File Content";
                await file.AppendAsync(new MemoryStream(Encoding.UTF8.GetBytes(fileContent)), 0);
                await file.FlushAsync(fileContent.Length);

                // Anonymously access a blob given its URI
                Uri endpoint = file.Uri;
                DataLakeFileClient anonymous = new DataLakeFileClient(endpoint);

                // Make a service request to verify we've successfully authenticated
                await anonymous.GetPropertiesAsync();
            }
            finally
            {
                await filesystem.DeleteAsync();
            }
        }

        /// <summary>
        /// Use a shared key to access a Storage Account.
        ///
        /// Shared Key authorization relies on your account access keys and
        /// other parameters to produce an encrypted signature string that is
        /// passed on the request in the Authorization header.
        /// </summary>
        [Test]
        public async Task SharedKeyAuthAsync()
        {
            // Get a Storage account name, shared key, and endpoint Uri.
            //
            // You can obtain both from the Azure Portal by clicking Access
            // Keys under Settings in the Portal Storage account blade.
            //
            // You can also get access to your account keys from the Azure CLI
            // with:
            //
            //     az storage account keys list --account-name <account_name> --resource-group <resource_group>
            //
            string accountName = StorageAccountName;
            string accountKey = StorageAccountKey;
            Uri serviceUri = StorageAccountBlobUri;

            // Make StorageSharedKeyCredential to pass to the serviceClient
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);

            // Get a reference to a service Client
            DataLakeServiceClient service = new DataLakeServiceClient(serviceUri, sharedKeyCredential);

            // Make a service request to verify we've successfully authenticated
            await service.CreateFileSystemAsync("sample-filesystem-sharedkey");
            await service.DeleteFileSystemAsync("sample-filesystem-sharedkey");
        }

        /// <summary>
        /// Use a shared access signature to acces a Storage Account.
        ///
        /// A shared access signature (SAS) is a URI that grants restricted
        /// access rights to Azure Storage resources. You can provide a shared
        /// access signature to clients who should not be trusted with your
        /// storage account key but to whom you wish to delegate access to
        /// certain storage account resources. By distributing a shared access
        /// signature URI to these clients, you can grant them access to a
        /// resource for a specified period of time, with a specified set of
        /// permissions.
        /// </summary>
        [Test]
        public async Task SharedAccessSignatureAuthAsync()
        {
            // Create a service level SAS that only allows reading from service
            // level APIs
            AccountSasBuilder sas = new AccountSasBuilder
            {
                Protocol = SasProtocol.None,
                Services = AccountSasServices.Blobs,
                ResourceTypes = AccountSasResourceTypes.All,
                StartsOn = DateTimeOffset.UtcNow.AddHours(-1),
                ExpiresOn = DateTimeOffset.UtcNow.AddHours(1),
                IPRange = new SasIPRange(IPAddress.None, IPAddress.None)
            };
            // Allow read access
            sas.SetPermissions(AccountSasPermissions.List);

            // Create a SharedKeyCredential that we can use to sign the SAS token
            StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // Build a SAS URI
            UriBuilder sasUri = new UriBuilder(StorageAccountBlobUri);
            sasUri.Query = sas.ToSasQueryParameters(credential).ToString();

            // Create a client that can authenticate with the SAS URI
            DataLakeServiceClient service = new DataLakeServiceClient(sasUri.Uri);

            // Make a service request to verify we've successfully authenticated
            await service.GetFileSystemsAsync().FirstAsync();

            // Try to create a new container (which is beyond our
            // delegated permission)
            RequestFailedException ex =
                Assert.ThrowsAsync<RequestFailedException>(
                    async () => await service.CreateFileSystemAsync(Randomize("sample-filesystem")));
            Assert.AreEqual(403, ex.Status);
        }

        /// <summary>
        /// Use an Active Directory token to access a Storage account.
        ///
        /// Azure Storage provides integration with Azure Active Directory
        /// (Azure AD) for identity-based authentication of requests to the
        /// Blob and Queue services. With Azure AD, you can use role-based
        /// access control (RBAC) to grant access to your Azure Storage
        /// resources to users, groups, or applications. You can grant
        /// permissions that are scoped to the level of an individual
        /// container or queue.
        ///
        /// To learn more about Azure AD integration in Azure Storage, see
        /// https://docs.microsoft.com/en-us/azure/storage/common/storage-auth-aad
        /// </summary>
        [Test]
        public async Task ActiveDirectoryAuthAsync()
        {
            // Create a token credential that can use our Azure Active
            // Directory application to authenticate with Azure Storage
            TokenCredential credential =
                new ClientSecretCredential(
                    ActiveDirectoryTenantId,
                    ActiveDirectoryApplicationId,
                    ActiveDirectoryApplicationSecret,
                    new TokenCredentialOptions() { AuthorityHost = ActiveDirectoryAuthEndpoint });

            // Create a client that can authenticate using our token credential
            DataLakeServiceClient service = new DataLakeServiceClient(ActiveDirectoryBlobUri, credential);

            // Make a service request to verify we've successfully authenticated
            await service.CreateFileSystemAsync("sample-filesystem-aad");
            await service.DeleteFileSystemAsync("sample-filesystem-aad");
        }
    }
}


text:
from datetime import datetime

import mock
from mock import Mock

from paasta_tools.autoscaling import ec2_fitness
from paasta_tools.mesos_tools import SlaveTaskCount

def test_sort_by_total_tasks():
    mock_slave_1 = Mock(
        task_counts=SlaveTaskCount(count=3, slave=Mock(), batch_count=0)
    )
    mock_slave_2 = Mock(
        task_counts=SlaveTaskCount(count=2, slave=Mock(), batch_count=1)
    )
    mock_slave_3 = Mock(
        task_counts=SlaveTaskCount(count=5, slave=Mock(), batch_count=0)
    )
    ret = ec2_fitness.sort_by_total_tasks([mock_slave_1, mock_slave_2, mock_slave_3])
    assert ret == [mock_slave_3, mock_slave_1, mock_slave_2]

def test_sort_by_running_batch_count():
    mock_slave_1 = Mock(
        task_counts=SlaveTaskCount(count=3, slave=Mock(), batch_count=1)
    )
    mock_slave_2 = Mock(
        task_counts=SlaveTaskCount(count=2, slave=Mock(), batch_count=2)
    )
    mock_slave_3 = Mock(
        task_counts=SlaveTaskCount(count=5, slave=Mock(), batch_count=3)
    )
    ret = ec2_fitness.sort_by_running_batch_count(
        [mock_slave_1, mock_slave_2, mock_slave_3]
    )
    assert ret == [mock_slave_3, mock_slave_2, mock_slave_1]

def test_sort_by_health_system_instance_health_system_status_failed():
    mock_slave_1 = Mock(name="slave1")
    mock_slave_1.task_counts = SlaveTaskCount(count=3, slave=Mock(), batch_count=1)
    mock_slave_1.instance_status = {
        "Events": [
            {
                "Code": "instance-reboot",
                "Description": "string",
                "NotBefore": datetime(2015, 1, 1),
                "NotAfter": datetime(2015, 1, 1),
            }
        ],
        "SystemStatus": {"Status": "impaired"},
        "InstanceStatus": {"Status": "ok"},
    }
    mock_slave_2 = Mock(name="slave2")
    mock_slave_2.task_counts = (SlaveTaskCount(count=3, slave=Mock(), batch_count=1),)
    mock_slave_2.instance_status = {
        "Events": [
            {
                "Code": "instance-reboot",
                "Description": "string",
                "NotBefore": datetime(2015, 1, 1),
                "NotAfter": datetime(2015, 1, 1),
            }
        ],
        "SystemStatus": {"Status": "ok"},
        "InstanceStatus": {"Status": "ok"},
    }
    ret = ec2_fitness.sort_by_system_instance_health([mock_slave_1, mock_slave_2])
    assert ret == [mock_slave_2, mock_slave_1]

def test_sort_by_upcoming_events():
    mock_slave_1 = Mock()
    mock_slave_1.task_counts = SlaveTaskCount(count=3, slave=Mock(), batch_count=1)
    mock_slave_1.instance_status = {
        "Events": [],
        "SystemStatus": {"Status": "ok"},
        "InstanceStatus": {"Status": "ok"},
    }
    mock_slave_2 = Mock()
    mock_slave_2.task_counts = SlaveTaskCount(count=3, slave=Mock(), batch_count=1)
    mock_slave_2.instance_status = {
        "Events": [
            {
                "Code": "instance-reboot",
                "Description": "string",
                "NotBefore": datetime(2015, 1, 1),
                "NotAfter": datetime(2015, 1, 1),
            }
        ],
        "SystemStatus": {"Status": "ok"},
        "InstanceStatus": {"Status": "ok"},
    }
    ret = ec2_fitness.sort_by_upcoming_events([mock_slave_1, mock_slave_2])
    assert ret == [mock_slave_1, mock_slave_2]

def test_sort_by_fitness_calls_all_sorting_funcs():
    with mock.patch(
        "paasta_tools.autoscaling.ec2_fitness.sort_by_system_instance_health",
        autospec=True,
    ) as mock_sort_by_system_instance_health, mock.patch(
        "paasta_tools.autoscaling.ec2_fitness.sort_by_upcoming_events", autospec=True
    ) as mock_sort_by_upcoming_events, mock.patch(
        "paasta_tools.autoscaling.ec2_fitness.sort_by_running_batch_count",
        autospec=True,
    ) as mock_sort_by_running_batch_count, mock.patch(
        "paasta_tools.autoscaling.ec2_fitness.sort_by_total_tasks", autospec=True
    ) as mock_sort_by_total_tasks:
        instances = []
        ec2_fitness.sort_by_ec2_fitness(instances)
        assert mock_sort_by_total_tasks.called
        assert mock_sort_by_running_batch_count.called
        assert mock_sort_by_upcoming_events.called
        assert mock_sort_by_system_instance_health.called

def test_sort_by_fitness():
    mock_slave_1 = Mock(name="slave1")
    mock_slave_1.task_counts = SlaveTaskCount(count=3, slave=Mock(), batch_count=1)
    mock_slave_1.instance_status = {
        "Events": [],
        "SystemStatus": {"Status": "impaired"},
        "InstanceStatus": {"Status": "ok"},
    }
    mock_slave_2 = Mock(name="slave2")
    mock_slave_2.task_counts = SlaveTaskCount(count=3, slave=Mock(), batch_count=1)
    mock_slave_2.instance_status = {
        "Events": [
            {
                "Code": "instance-reboot",
                "Description": "foo",
                "NotBefore": datetime(2015, 1, 1),
                "NotAfter": datetime(2015, 1, 1),
            }
        ],
        "SystemStatus": {"Status": "ok"},
        "InstanceStatus": {"Status": "ok"},
    }
    mock_slave_3 = Mock(name="slave3")
    mock_slave_3.task_counts = SlaveTaskCount(count=2, slave=Mock(), batch_count=3)
    mock_slave_3.instance_status = {
        "Events": [],
        "SystemStatus": {"Status": "ok"},
        "InstanceStatus": {"Status": "ok"},
    }
    mock_slave_4 = Mock(name="slave4")
    mock_slave_4.task_counts = SlaveTaskCount(count=3, slave=Mock(), batch_count=1)
    mock_slave_4.instance_status = {
        "Events": [],
        "SystemStatus": {"Status": "ok"},
        "InstanceStatus": {"Status": "ok"},
    }
    mock_slave_5 = Mock(name="slave5")
    mock_slave_5.task_counts = SlaveTaskCount(count=1, slave=Mock(), batch_count=1)
    mock_slave_5.instance_status = {
        "Events": [],
        "SystemStatus": {"Status": "ok"},
        "InstanceStatus": {"Status": "ok"},
    }
    ret = ec2_fitness.sort_by_ec2_fitness(
        [mock_slave_1, mock_slave_2, mock_slave_3, mock_slave_4, mock_slave_5]
    )

    # we expect this order for the following reason:
    # mock_slave_1 is impaired and so should be killed asap
    # mock_slave_2 has an upcoming event
    # mock_slave_5 and mock_slave_4 have the fewest batch tasks, and so should be killed before
    # mock_slave_3 (we cant drain batch tasks, so try and save them)
    # mock_slave_5 has fewer tasks than mock_slave_4, and so is a better candidate for killing
    assert ret == [mock_slave_3, mock_slave_4, mock_slave_5, mock_slave_2, mock_slave_1]


text:
{% extends "master.html" %}
{% load i18n %}

{% block head %}

{% endblock head %}

{% block submenu %}
{% endblock submenu %}

{% block contents %}

Project Repositories

Repository	Description

{% for repo in repos %}

	{{ repo.title }}
	{{ repo.desc }}

{% endfor %}

{% endblock contents %}


text:
begin
  require 'markaby'
rescue LoadError => e
  raise MissingLibrary, "Markaby could not be loaded (is it installed?): #{e.message}"
end

module Capcode
  class Mab < Markaby::Builder
    include Views
  end

  module Helpers
    def render_markaby( f, opts = {} ) #:nodoc:
      f = f.to_s
      layout = opts.delete(:layout)||:layout

      # Update options
      (Capcode::Configuration.options[:markaby] || {}).merge(opts).each do |k, v|
        Markaby::Builder.set(k, v)
      end

      assigns = {}
      self.instance_variables.delete_if {|x| ["@response", "@env", "@request"].include?(x) }.each do |ivar|
        assigns[ivar.gsub( /^@/, "" )] = self.instance_variable_get(ivar)
      end

      __mab = Mab.new(assigns.merge( opts ), self) {
        if self.respond_to?(layout)
          self.send(layout.to_s) { |*args|
            # @@__ARGS__ = args
            Capcode::Helpers.args = args
            self.send(f)
          }
        else
          self.send(f)
        end
      }
      __mab.to_s
    end
  end
end


text:
var expect = require("chai").expect;
var instructions = require("../../src/day-07/instructions");
var circuitBuilder = require("../../src/day-07/circuit-builder");

describe("Circuit Builder", () => {
  it("can build an out-of-order AND instruction", () => {
    var builtCircuit = circuitBuilder.fromInstructions([instruction("x AND y -> d"), instruction("123 -> x"), instruction("456 -> y")]);
    expect(builtCircuit.x.signal).to.equal(123);
    expect(builtCircuit.y.signal).to.equal(456);
    expect(builtCircuit.d.signal === undefined).to.equal(true);
    expect(builtCircuit.d.gate.type).to.equal("AND");
    expect(builtCircuit.d.gate.in1).to.equal("x");
    expect(builtCircuit.d.gate.in2).to.equal("y");
  });

  it("can override a wire to a signal", () => {
    var builtCircuit = circuitBuilder.fromInstructions([instruction("x AND 456 -> d"), instruction("123 -> x")]);
    builtCircuit.override("d", 36);
    expect(builtCircuit.x.signal).to.equal(123);
    expect(builtCircuit.d.signal).to.equal(36);
    expect(builtCircuit.d.gate === undefined).to.equal(true);
  });
});

var instruction = (i) => instructions.fromString(i);


text:
/*global define:false*/
define(['text!plugins/richtext/template.html', 'plugins/richtext/model', 'text!plugins/richtext/setupTemplate.html'],
    function (richTextPluginTemplate, richTextPluginModel, setupTemplate) {
        'use strict';

        return {
            name : 'richTextPlugin',
            ModelType : richTextPluginModel,
            modelData : {
                min : 1,
                max : 1,
                options : false,
                label : '',
                type : 'richtext',
                dataType : 'string',
                validation : [],
                value : ''
            },
            listeners : [
                ['channels.views', 'pluginWrapperSortStart', 'sortStart'],
                ['channels.views', 'pluginWrapperSortStop', 'stopSort']
            ],
            template : richTextPluginTemplate,
            setupTemplate : setupTemplate,
            wrapper: false
        };
    });


text:
require 'bus_factor/version'
require 'json'
require 'bundler'
require 'rest-client'
Bundler.require :all

module BusFactor
  class << self
    Result = Struct.new(:name, :emails) do
      def to_s(length_chars: 2, spec_chars:15)
        fs = "%#{length_chars}s, %#{spec_chars}s: %s"
        format(
          fs,
          emails.length,
          name,
          emails.join(', ')
        )
      end
    end

    # TODO: how often updated?
    def worst
      sorted_specs.map do |spec|
        Result.new(
          spec.name,
          owners_of(spec).map { |o| o['email'] }
        )
      end
    end

    def sorted_specs
      specs = Bundler.locked_gems.specs.map(&:__materialize__)
      specs.sort_by do |spec|
        owners_of(spec).length
      end
      specs
    end

    def owners_of(geem)
      geem = geem.name if geem.respond_to? :name
      owner_cache[geem]
    end

    def owner_cache
      @owner_cache ||= Hash.new do |hash, key|
        uri = "https://rubygems.org/api/v1/gems/#{key}/owners.json"
        hash[key] = JSON.parse(RestClient.get uri)
      end
    end
  end
end


text: Web front end for quasimodo


text:
using namespace llvm;

void circular_raw_ostream::write_impl(const char *Ptr, size_t Size) {
  if (BufferSize == 0) {
    TheStream->write(Ptr, Size);
    return;
  }

  // Write into the buffer, wrapping if necessary.
  while (Size != 0) {
    unsigned Bytes =
      std::min(unsigned(Size), unsigned(BufferSize - (Cur - BufferArray)));
    memcpy(Cur, Ptr, Bytes);
    Size -= Bytes;
    Cur += Bytes;
    if (Cur == BufferArray + BufferSize) {
      // Reset the output pointer to the start of the buffer.
      Cur = BufferArray;
      Filled = true;
    }
  }
}

void circular_raw_ostream::flushBufferWithBanner() {
  if (BufferSize != 0) {
    // Write out the buffer
    TheStream->write(Banner, std::strlen(Banner));
    flushBuffer();
  }
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace PdfiumViewer
{
    internal class PdfLibrary : IDisposable
    {
        private static readonly object _syncRoot = new object();
        private static PdfLibrary _library;

        public static void EnsureLoaded()
        {
            lock (_syncRoot)
            {
                if (_library == null)
                    _library = new PdfLibrary();
            }
        }

        private bool _disposed;

        private PdfLibrary()
        {
            NativeMethods.FPDF_AddRef();
        }

        ~PdfLibrary()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                NativeMethods.FPDF_Release();

                _disposed = true;
            }
        }
    }
}


text:
namespace Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition
{
    /// <summary>
    /// Receivers action definition allowing to set each receiver's configuration.
    /// </summary>
    /// <typeparam name="ParentT">The next stage of the definition.</typeparam>
    public interface IActionDefinition<ParentT>
    {

        /// <summary>
        /// Attaches the defined receivers to the Action Group configuration.
        /// </summary>
        /// <return>The next stage of the definition.</return>
        ParentT Attach();

        /// <summary>
        /// Sets the Azure Automation Runbook notification receiver.
        /// </summary>
        /// <param name="automationAccountId">The automationAccountId value to set.</param>
        /// <param name="runbookName">The runbookName value to set.</param>
        /// <param name="webhookResourceId">The webhookResourceId value to set.</param>
        /// <param name="isGlobalRunbook">The isGlobalRunbook value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithAutomationRunbook(string automationAccountId, string runbookName, string webhookResourceId, bool isGlobalRunbook);

        /// <summary>
        /// Sets the Azure Functions receiver.
        /// </summary>
        /// <param name="functionAppResourceId">The functionAppResourceId value to set.</param>
        /// <param name="functionName">The functionName value to set.</param>
        /// <param name="httpTriggerUrl">The httpTriggerUrl value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithAzureFunction(string functionAppResourceId, string functionName, string httpTriggerUrl);

        /// <summary>
        /// Sets the email receiver.
        /// </summary>
        /// <param name="emailAddress">The email Address value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithEmail(string emailAddress);

        /// <summary>
        /// Sets the ITSM receiver.
        /// </summary>
        /// <param name="workspaceId">The workspaceId value to set.</param>
        /// <param name="connectionId">The connectionId value to set.</param>
        /// <param name="ticketConfiguration">The ticketConfiguration value to set.</param>
        /// <param name="region">The region value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithItsm(string workspaceId, string connectionId, string ticketConfiguration, string region);

        /// <summary>
        /// Sets the Logic App receiver.
        /// </summary>
        /// <param name="logicAppResourceId">The logicAppResourceId value to set.</param>
        /// <param name="callbackUrl">The callbackUrl value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithLogicApp(string logicAppResourceId, string callbackUrl);

        /// <summary>
        /// Sets the Azure Mobile App Push Notification  receiver.
        /// </summary>
        /// <param name="emailAddress">The emailAddress value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithPushNotification(string emailAddress);

        /// <summary>
        /// Sets the SMS receiver.
        /// </summary>
        /// <param name="countryCode">The countryCode value to set.</param>
        /// <param name="phoneNumber">The phoneNumber value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithSms(string countryCode, string phoneNumber);

        /// <summary>
        /// Sets the Voice notification receiver.
        /// </summary>
        /// <param name="countryCode">The countryCode value to set.</param>
        /// <param name="phoneNumber">The phoneNumber value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithVoice(string countryCode, string phoneNumber);

        /// <summary>
        /// Sets the Webhook receiver.
        /// </summary>
        /// <param name="serviceUri">The serviceUri value to set.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition.IActionDefinition<ParentT> WithWebhook(string serviceUri);
    }
}


text:
%% Unit statute_mile (mi)
%
% See also: statute_mile

function mile = mi

mile = statute_mile;


text:
- mvn verify
- mvn versions:display-dependency-updates
- mvn versions:display-plugin-updates
- update HISTORY.md
- change version in pom.xml
- push and wait for build
- create tag jdependency-VERSION
- push and wait for build
- login to https://oss.sonatype.org/
- staging repositories
- close
- release


text:
NewRelic instrumentation for [Webmachine][webmachine].

## Installation

Add this line to your application's Gemfile:

    gem 'newrelic-webmachine'

And then execute:

    $ bundle

## Usage

In your application's boot process, e.g. in `config.ru`

    require 'newrelic-webmachine'

Assuming you've configured NewRelic correctly, you should now see requests handled by Webmachine traced in NewRelic.

## Contributing

Made it better?  Please submit a [pull request][github-pr].

1. Fork it.
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

[webmachine]: https://github.com/seancribbs/webmachine-ruby
[github-pr]: https://github.com/mdub/newrelic-webmachine


text:
sub, sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline; }

button, input, optgroup, select, textarea {
  color: inherit;
  font: inherit;
  margin: 0; }

html {
  font-family: sans-serif; }
  html input[type="button"] {
    cursor: pointer; }
  html input[disabled] {
    cursor: default; }

body {
  margin: 0; }

article {
  display: block; }

aside {
  display: block; }

details {
  display: block; }

figcaption {
  display: block; }

figure {
  display: block;
  margin: 1em 40px; }

footer {
  display: block; }

header {
  display: block; }

hgroup {
  display: block; }

main {
  display: block; }

menu {
  display: block; }

nav {
  display: block; }

section {
  display: block; }

summary {
  display: block; }

audio {
  display: inline-block;
  vertical-align: baseline; }
  audio:not([controls]) {
    display: none;
    height: 0; }

canvas {
  display: inline-block;
  vertical-align: baseline; }

progress {
  display: inline-block;
  vertical-align: baseline; }

video {
  display: inline-block;
  vertical-align: baseline; }

[hidden] {
  display: none; }

template {
  display: none; }

a {
  background-color: transparent; }
  a:active {
    outline: 0; }
  a:hover {
    outline: 0; }

abbr[title] {
  border-bottom: 1px dotted; }

b {
  font-weight: bold; }

strong {
  font-weight: bold; }

dfn {
  font-style: italic; }

h1 {
  font-size: 2em;
  margin: 0.67em 0; }

mark {
  background: #ff0;
  color: #000; }

small {
  font-size: 80%; }

sub {
  bottom: -0.25em; }

sup {
  top: -0.5em; }

img {
  border: 0; }

hr {
  box-sizing: content-box;
  height: 0; }

pre {
  overflow: auto;
  font-family: monospace, monospace;
  font-size: 1em; }

code {
  font-family: monospace, monospace;
  font-size: 1em; }

kbd {
  font-family: monospace, monospace;
  font-size: 1em; }

samp {
  font-family: monospace, monospace;
  font-size: 1em; }

button {
  overflow: visible;
  text-transform: none;
  cursor: pointer; }

input {
  line-height: normal; }

optgroup {
  font-weight: bold; }

select {
  text-transform: none; }

textarea {
  overflow: auto; }

input[type="reset"] {
  cursor: pointer; }

input[type="submit"] {
  cursor: pointer; }

button[disabled] {
  cursor: default; }

button::-moz-focus-inner {
  border: 0;
  padding: 0; }

input::-moz-focus-inner {
  border: 0;
  padding: 0; }

input[type="checkbox"] {
  box-sizing: border-box;
  padding: 0; }

input[type="radio"] {
  box-sizing: border-box;
  padding: 0; }

input[type="number"]::-webkit-inner-spin-button {
  height: auto; }

input[type="number"]::-webkit-outer-spin-button {
  height: auto; }

input[type="search"] {
  box-sizing: content-box; }

fieldset {
  border: 1px solid #c0c0c0;
  margin: 0 2px;
  padding: 0.35em 0.625em 0.75em; }

legend {
  border: 0;
  padding: 0; }

table {
  border-collapse: collapse;
  border-spacing: 0; }

td {
  padding: 0; }

th {
  padding: 0; }

svg:not(:root) {
  overflow: hidden; }


text:
import { ProxyOptions } from './proxy-options';

export class Proxy {
    static initOptions(opts: ProxyOptions, version: number): number;
}


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file   FTEC_ProxyConsumer.h
 *
 *  $Id: FTEC_ProxyConsumer.h 935 2008-12-10 21:47:27Z mitza $
 *
 *  @author Huang-Ming Huang <hh1@cse.wustl.edu>
 */
//=============================================================================
#ifndef TAO_FTEC_PROXYCONSUMER_H
#define TAO_FTEC_PROXYCONSUMER_H

#include "orbsvcs/Event/EC_Default_ProxyConsumer.h"
#include "ace/SString.h"
#include "orbsvcs/FtRtecEventChannelAdminC.h"
#include "orbsvcs/FtRtEvent/EventChannel/Request_Context_Repository.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

class TAO_FTEC_ProxyPushConsumer : public TAO_EC_Default_ProxyPushConsumer
{
  typedef TAO_EC_Default_ProxyPushConsumer Inherited;
public:
  typedef RtecEventChannelAdmin::ProxyPushConsumer Interface;
  typedef FtRtecEventChannelAdmin::ProxyPushConsumerStat State;
  typedef POA_RtecEventChannelAdmin::ProxyPushConsumer_ptr Skeleton;

  TAO_FTEC_ProxyPushConsumer (TAO_EC_Event_Channel_Base* event_channel);

  virtual void activate (
     RtecEventChannelAdmin::ProxyPushConsumer_ptr &proxy);

    // = The RtecEventChannelAdmin::ProxyPushConsumer methods...
  virtual void connect_push_supplier (
                RtecEventComm::PushSupplier_ptr push_supplier,
                const RtecEventChannelAdmin::SupplierQOS& qos);
  virtual void disconnect_push_consumer (void);

  const FtRtecEventChannelAdmin::ObjectId& id() const;
  void get_state(FtRtecEventChannelAdmin::ProxyPushConsumerStat& state);
  void set_state(const FtRtecEventChannelAdmin::ProxyPushConsumerStat& state);

  typedef void (FtRtecEventChannelAdmin::EventChannelFacade::*RollbackOperation)
    (const FtRtecEventChannelAdmin::ObjectId&);

  static const RollbackOperation rollback_obtain;
private:
  FtRtecEventChannelAdmin::ObjectId_var object_id_;
};

TAO_END_VERSIONED_NAMESPACE_DECL

#endif


text:
from __future__ import unicode_literals

from subprocess import PIPE, Popen

def kpsewhich(filename):
    p = Popen(['kpsewhich', filename], stdout=PIPE, stderr=PIPE)
    path = p.communicate()[0].rstrip()
    if p.returncode == 0:
        return path


text:
<?xml version="1.0" ?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
-->

<!-- schema file for testing sorting/faceting/functions on single-valued DV with missing values -->

<schema name="schema-docValuesMissing" version="1.5">
  <types>
    <fieldType name="int" class="solr.TrieIntField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="float" class="solr.TrieFloatField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="long" class="solr.TrieLongField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldtype name="date" class="solr.TrieDateField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldtype name="string" class="solr.StrField" />
  </types>

  <fields>
    <field name="id" type="string" required="true" />

    <field name="floatdv"               type="float" indexed="false" stored="false" docValues="true"/>
    <field name="floatdv_missingfirst"  type="float" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <field name="floatdv_missinglast"   type="float" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <field name="intdv"                 type="int" indexed="false" stored="false" docValues="true"/>
    <field name="intdv_missingfirst"    type="int" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <field name="intdv_missinglast"     type="int" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <field name="doubledv"              type="double" indexed="false" stored="false" docValues="true"/>
    <field name="doubledv_missingfirst" type="double" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <field name="doubledv_missinglast"  type="double" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <field name="longdv"                type="long" indexed="false" stored="false" docValues="true"/>
    <field name="longdv_missingfirst"   type="long" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <field name="longdv_missinglast"    type="long" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <field name="datedv"                type="date" indexed="false" stored="false" docValues="true"/>
    <field name="datedv_missingfirst"   type="date" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <field name="datedv_missinglast"    type="date" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <field name="stringdv"              type="string" indexed="false" stored="false" docValues="true"/>
    <field name="stringdv_missingfirst" type="string" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <field name="stringdv_missinglast"  type="string" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <dynamicField name="*_floatdv"               type="float" indexed="false" stored="false" docValues="true"/>
    <dynamicField name="*_floatdv_missingfirst"  type="float" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <dynamicField name="*_floatdv_missinglast"   type="float" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <dynamicField name="*_intdv"                 type="int" indexed="false" stored="false" docValues="true"/>
    <dynamicField name="*_intdv_missingfirst"    type="int" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <dynamicField name="*_intdv_missinglast"     type="int" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <dynamicField name="*_doubledv"              type="double" indexed="false" stored="false" docValues="true"/>
    <dynamicField name="*_doubledv_missingfirst" type="double" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <dynamicField name="*_doubledv_missinglast"  type="double" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <dynamicField name="*_longdv"                type="long" indexed="false" stored="false" docValues="true"/>
    <dynamicField name="*_longdv_missingfirst"   type="long" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <dynamicField name="*_longdv_missinglast"    type="long" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <dynamicField name="*_datedv"                type="date" indexed="false" stored="false" docValues="true"/>
    <dynamicField name="*_datedv_missingfirst"   type="date" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <dynamicField name="*_datedv_missinglast"    type="date" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

    <dynamicField name="*_stringdv"              type="string" indexed="false" stored="false" docValues="true"/>
    <dynamicField name="*_stringdv_missingfirst" type="string" indexed="false" stored="false" docValues="true" sortMissingFirst="true"/>
    <dynamicField name="*_stringdv_missinglast"  type="string" indexed="false" stored="false" docValues="true" sortMissingLast="true"/>

  </fields>

  <uniqueKey>id</uniqueKey>

</schema>


text:
require 'spec_helper'

module Cyrax
  describe Decorator do
    let(:decorable) { double(foo:'bar') }
    subject { Cyrax::Decorator.new(decorable) }

    its(:resource) { should eq(decorable) }

    it 'should translate missing methods to decorable' do
      subject.foo.should eq('bar')
    end

    it 'should not translate missing methods' do
      expect {
        subject.bar
      }.to raise_error(NoMethodError)
    end
  end
end


text:
package edu.wustl.catissuecore.applet.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.JTable;

import edu.wustl.catissuecore.applet.AppletConstants;
import edu.wustl.catissuecore.applet.BaseCopyPasteValidator;
import edu.wustl.catissuecore.applet.CopyPasteOperationValidatorModel;
import edu.wustl.catissuecore.applet.SpecimenArrayCopyPasteValidator;
import edu.wustl.catissuecore.applet.model.SpecimenArrayTableModel;
import edu.wustl.catissuecore.applet.util.CommonAppletUtil;

/**
 *
This class handles common copy operation among objects which have.
 * copy/paste operation.

 * @author Ashwin Gupta
 * @version 1.1
 */
public abstract class AbstractCopyActionHandler implements ActionListener
{

	/**
	 * table component used in applet.
	 */
	protected JTable table;
	/**
	 * isValidateSuccess.
	 */
	protected boolean isValidateSuccess = true;
	/**
	 * populateValidatorModel.
	 */
	protected boolean populateValidatorModel = true;

	/**
	 * Default constructor.
	 */
	public AbstractCopyActionHandler()
	{
		//Empty AbstractCopyActionHandler.
	}

	/**
	 * constructor with table to persist table.
	 * @param table table used in applet
	 */
	public AbstractCopyActionHandler(JTable table)
	{
		this.table = table;
	}

	/**
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 * @param actionEvent : e
	 */
	public void actionPerformed(ActionEvent actionEvent)
	{
		this.preActionPerformed(actionEvent);
		this.doActionPerformed(actionEvent);
		this.postActionPerformed(actionEvent);
	}

	/**
	 * Pre action performed method for copy operation.
	 * @param actionEvent : actionEvent
	 */
	protected abstract void preActionPerformed(ActionEvent actionEvent);

	/**
	 * do action performed method for copy operation.
	 * Other copy listeners should override this method for specific operations.
	 * @param actionEvent : e
	 */
	protected void doActionPerformed(ActionEvent actionEvent)
	{
		this.populateValidatorModel();
	}

	/**
	 * Post action performed method for copy operation.
	 * @param actionEvent : e
	 */
	protected abstract void postActionPerformed(ActionEvent actionEvent);

	/**
	 * Protected method populateValidatorModel.
	 */
	protected void populateValidatorModel()
	{
		//Following code is added for checkbox
		this.populateValidatorModel = true;
		final CopyPasteOperationValidatorModel validatorModel = new CopyPasteOperationValidatorModel();

		if (this.populateValidatorModel)
		{

			final int[] selectedColumns = this.table.getSelectedColumns();
			final int[] selectedRows = this.table.getSelectedRows();

			// poulate validator model
			this.populateValidatorModel(validatorModel, selectedRows, selectedColumns);

		}
		BaseCopyPasteValidator validator = null;
		String validationMessage = null;

		validator = getValidator(validatorModel) ;
		if (validator != null)
		{
			validationMessage = validator.validate();
			if ("".equals(validationMessage))
			{
				this.isValidateSuccess = true;
				CommonAppletUtil.getBaseTableModel(this.table).setCopyPasteOperationValidatorModel(
						validatorModel);
			}
			else
			{
				this.isValidateSuccess = false;
				//System.out.println(" validationMessage:: " + validationMessage);
				final Object[] paramArray = {validationMessage};
				CommonAppletUtil.callJavaScriptFunction(this.table, this.getJSMethodName(),
						paramArray);
			}
		}
	}
	/**
	 * Returns the validator object.
	 * @param validatorModel CopyPasteOperationValidatorModel object.
	 * @return  validator object.
	 */
	private BaseCopyPasteValidator getValidator(CopyPasteOperationValidatorModel validatorModel)
	{
		BaseCopyPasteValidator validator = null ;
		if (( this.table != null) &&
				 (this.table.getModel() instanceof SpecimenArrayTableModel))
		{
			validator = new SpecimenArrayCopyPasteValidator(validatorModel);
			/*else if (table.getModel() instanceof MultipleSpecimenTableModel)
			 {
			 //TODO put same as above construstor
			 validator = new MultipleSpecimenCopyPasteValidator(table, validatorModel);
			 }*/
		}
		return validator ;
	}
	/**
	 * @param validatorModel model
	 * @param selectedRows rows
	 * @param selectedColumns columns
	 */
	private void populateValidatorModel(CopyPasteOperationValidatorModel validatorModel,
			int[] selectedRows, int[] selectedColumns)
	{
		validatorModel.setSelectedCopiedRows(CommonAppletUtil.createListFromArray(selectedRows));
		validatorModel.setSelectedCopiedCols(CommonAppletUtil.createListFromArray(selectedColumns));
		validatorModel.setOperation(AppletConstants.COPY_OPERATION);
		validatorModel.setCopiedData(this.getSelectedData(selectedRows, selectedColumns));
		validatorModel.setRowCount(this.table.getRowCount());
		validatorModel.setColumnCount(this.getColumnCount());
	}

	/**
	 * This method returns the map holding the selected data.
	 * The key is represented by the row@column format.
	 * @param selectedRows : selectedRows
	 * @param selectedColumns : selectedColumns
	 * @return HashMap : HashMap
	 */
	protected HashMap getSelectedData(int[] selectedRows, int[] selectedColumns)
	{
		final HashMap map = new HashMap();
		for (final int selectedRow : selectedRows)
		{
			for (final int selectedColumn : selectedColumns)
			{
				final String key = CommonAppletUtil.getDataKey(selectedRow, selectedColumn);
				final List valueList = this.getValueList(selectedRow, selectedColumn);
				map.put(key, valueList);
			}
		}

		/**
		 * Smita Kadam
		 * Reviewer: Sachin
		 * Bug ID: 4574
		 * Patch ID: 4574_1
		 * Description: Tooltip related processing done only for Multiple specimen table
		 */
		/*	if (table.getModel() instanceof MultipleSpecimenTableModel)
		 {
		 for (int columnIndex = 0; columnIndex < selectedColumns.length; columnIndex++)
		 {
		 String key = CommonAppletUtil.getDataKey(AppletConstants.SPECIMEN_EVENTS_ROW_NO,
		  selectedColumns[columnIndex]);
		 String value = getEventTooltip(selectedColumns[columnIndex]);
		 map.put(key, value);
		 }
		 }*/
		return map;
	}

	/**
	 * gets event tool tip for given column
	 * @param columnIndex for which tool tip to retrieve
	 * @return tooltip of event button for given column
	 */
	/*protected String getEventTooltip(int columnIndex)
	 {
	 TableColumnModel columnModel = table.getColumnModel();
	 TableColumn tm = columnModel.getColumn(columnIndex);
	 SpecimenColumnModel scm = (SpecimenColumnModel) tm.getCellEditor();
	 if (scm == null || scm.getToolTipToEventButton()==null)
	 return "";
	 else
	 return scm.getToolTipToEventButton();
	 }*/
	/** -- patch ends here -- */
	/**
	 * @param rowIndex : rowIndex
	 * @param columnIndex : columnIndex
	 * @return List
	 */
	protected List getValueList(int rowIndex, int columnIndex)
	{
		final List valueList = new ArrayList();
		Object value = this.table.getValueAt(rowIndex, columnIndex);
		if (value == null)
		{
			value = "";
		}
		valueList.add(value.toString());
		return valueList;
	}

	/**
	 * get total no. of columns
	 * @return total coumn count
	 */
	protected abstract int getColumnCount();

	/**
	 * @return JS method name for this button.
	 */
	protected String getJSMethodName()
	{
		return "showErrorMessage";
	}

}


text:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Data].[Organization]') AND type in (N'U'))
BEGIN
	CREATE TABLE [Data].[Organization](
		[OrganizationId] int IDENTITY(1,1) NOT NULL,
		[ContentInspectionId] int  NOT NULL,
		[OrganizationName] varchar(250)  NOT NULL,
		CONSTRAINT [PK_Organization] PRIMARY KEY CLUSTERED ([OrganizationId])
	)
	INSERT INTO [Data].[TableVersion]([TableName],[Version]) VALUES('[Data].[Organization]', 0)
END


text:
module Activerecord::Jdbcvertica::Adapter
  class Railtie < ::Rails::Railtie

    rake_tasks do
      if defined?(Rake)
        load "tasks/vertica_database_tasks.rake"
      end
    end

  end
end