text:
#include "include/core/SkString.h"
#include "include/core/SkTypes.h"
#include "tests/Test.h"

#include "tests/TestHarness.h"

#if SK_GPU_V1
#include "include/gpu/GrContextOptions.h"
#include "include/gpu/GrDirectContext.h"
#include "include/gpu/GrTypes.h"
#include "include/private/gpu/ganesh/GrTypesPriv.h"
#include "tools/gpu/TestContext.h"
#endif

class BazelReporter : public skiatest::Reporter {
public:
    void reportFailed(const skiatest::Failure& failure) override {
            SkDebugf("FAIL: %s\n", failure.toString().c_str());
            fFailed = true;
    }
    bool allowExtendedTest() const override { return false; }
    bool verbose() const override { return false; }
    bool ok() { return !fFailed; }
private:
    bool fFailed = false;
};

#if SK_GPU_V1
namespace skiatest {
bool IsGLContextType(sk_gpu_test::GrContextFactory::ContextType type) {
    return GrBackendApi::kOpenGL == sk_gpu_test::GrContextFactory::ContextTypeBackend(type);
}
bool IsVulkanContextType(sk_gpu_test::GrContextFactory::ContextType type) {
    return GrBackendApi::kVulkan == sk_gpu_test::GrContextFactory::ContextTypeBackend(type);
}
bool IsMetalContextType(sk_gpu_test::GrContextFactory::ContextType type) {
    return GrBackendApi::kMetal == sk_gpu_test::GrContextFactory::ContextTypeBackend(type);
}
bool IsDirect3DContextType(sk_gpu_test::GrContextFactory::ContextType type) {
    return GrBackendApi::kDirect3D == sk_gpu_test::GrContextFactory::ContextTypeBackend(type);
}
bool IsDawnContextType(sk_gpu_test::GrContextFactory::ContextType type) {
    return GrBackendApi::kDawn == sk_gpu_test::GrContextFactory::ContextTypeBackend(type);
}
bool IsRenderingGLContextType(sk_gpu_test::GrContextFactory::ContextType type) {
    return IsGLContextType(type) && sk_gpu_test::GrContextFactory::IsRenderingContext(type);
}
bool IsMockContextType(sk_gpu_test::GrContextFactory::ContextType type) {
    return type == sk_gpu_test::GrContextFactory::kMock_ContextType;
}

sk_gpu_test::GrContextFactory::ContextType compiledInContextTypes[] = {
#if defined(SK_GL)
    // Use "native" instead of explicitly trying both OpenGL and OpenGL ES. Do not use GLES on
    // desktop since tests do not account for not fixing http://skbug.com/2809
#if defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC)
    sk_gpu_test::GrContextFactory::kGL_ContextType,
#else
    sk_gpu_test::GrContextFactory::kGLES_ContextType,
#endif
#endif // defined(SK_GL)
#if defined(SK_VULKAN)
    sk_gpu_test::GrContextFactory::kVulkan_ContextType,
#endif
#if defined(SK_DAWN)
    sk_gpu_test::GrContextFactory::kDawn_ContextType,
#endif
// TODO(kjlubick) Other Ganesh backends
    sk_gpu_test::GrContextFactory::kMock_ContextType,
};

// The macros defined in Test.h eventually call into this function. For each GPU backend that is
// compiled in, we run the testFn with a freshly created
void RunWithGaneshTestContexts(GrContextTestFn* testFn, GrContextTypeFilterFn* filter,
                               Reporter* reporter, const GrContextOptions& options) {
    sk_gpu_test::GrContextFactory factory(options);

    for (sk_gpu_test::GrContextFactory::ContextType ctxType : compiledInContextTypes) {
        if (filter && !(*filter)(ctxType)) {
            continue;
        }

        sk_gpu_test::ContextInfo ctxInfo = factory.getContextInfo(ctxType);
        if (ctxInfo.directContext()) {
            (*testFn)(reporter, ctxInfo);
            // In case the test changed the current context make sure we move it back before
            // calling flush.
            ctxInfo.testContext()->makeCurrent();
            // Sync so any release/finished procs get called.
            ctxInfo.directContext()->flushAndSubmit(/*syncCPU=*/true);
        } else {
            SkDebugf("Unable to make direct context for Ganesh test.\n");
            SkASSERT(false);
            return;
        }
    }
}

} // namespace skiatest
#endif // #if SK_GPU_V1

TestHarness CurrentTestHarness() {
    return TestHarness::kBazelTestRunner;
}

int main() {
    BazelReporter reporter;
    for (skiatest::Test test : skiatest::TestRegistry::Range()) {
        if (test.fTestType == skiatest::TestType::kCPU) {
            SkDebugf("Running %s\n", test.fName);
            test.cpu(&reporter);
            SkDebugf("\tDone\n");
        }
    }

#if SK_GPU_V1
    GrContextOptions grCtxOptions;
    // TODO(kjlubick) DM has grContextOptions set via flags. Should this runner have that too?
    grCtxOptions.fExecutor = nullptr;
    grCtxOptions.fAllowPathMaskCaching = true;
    grCtxOptions.fFailFlushTimeCallbacks = false;
    grCtxOptions.fAllPathsVolatile = false;
    grCtxOptions.fGpuPathRenderers = GpuPathRenderers::kDefault;
    grCtxOptions.fDisableDriverCorrectnessWorkarounds = false;
    grCtxOptions.fResourceCacheLimitOverride = -1;
    grCtxOptions.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo;
    for (skiatest::Test test : skiatest::TestRegistry::Range()) {
        if (test.fTestType == skiatest::TestType::kGanesh) {
            SkDebugf("Running %s\n", test.fName);
            test.ganesh(&reporter, grCtxOptions);
            SkDebugf("\tDone\n");
        }
    }
#endif

    // TODO(kjlubick) Graphite support

    if (reporter.ok()) {
        SkDebugf("PASS\n");
        return 0;
    }
    SkDebugf("FAIL\n");
    return 1;
}


text:
#ifndef CONTROLLER_H
#define	CONTROLLER_H

#include "Organism.h"
#include <cstdlib>

class Controller
{
public:
    Controller(int popSize, Organism& target);
    virtual ~Controller();

    void printPopulation() const;
    void step(int n); //do n number of evolutionary generations.
    int fitness(Organism& org) const; //fintess function.
    void printFitGraph() const;

private:
    void error(std::string message) const;
    int populationSize; //the variable size of the population.
    Organism * population; //dynamic array of organisms to represent population.
    Organism goalOrganism;
    const static int chromosomeLen = 8 ; // VARIABLE this should reflect binaryNumber.numBits * Organism.noOfGenes
    int * gFitness; // graph of fitness where index represents the generation. ie. gen 0 is the starting highest fitness.
    int gSize; //gSize, the size of the gFitness graph - defined as the number of evolutionary steps.

};

#endif	/* CONTROLLER_H */

redpajama_set_name: RedPajamaGithub


text:
/**
* @file
* @author mentrox@gmail.com
* @version 1.0
* @date
*
* @section DESCRIPTION
*
* A Sprite is an object referring to a 2d image that can be translated, rotated,
* scaled, rendered and animated; this makes it ideal for displaying dynamic game
* objects such as players and enemies.
* Currently, Sprites load images with frame sizes that are a power of two - smallest 64x64.
*
*   See SpriteBatch for an implementation that allows more efficient sprite rendering
*   by using a texture atlas and vertex buffer object for large numbers of collected
*   sprites.
**/

// todos:
//flip method, resizing to exact size methods,
// get width/height, including scales/rotations etc
// methods for loading sprite that create timer for you automatically.
// subanimator selection

#if !defined(AAB_GAME_SPRITE_CLASS)
#define AAB_GAME_SPRITE_CLASS
#include"prototype/sprite.hh"
#include"transformation_node.hpp"
#include"../types/smart_ptr.hpp"
#include"../visen/texture_base.hpp"
#include"../visen/texture.hpp"
#include"../visen/animated_texture.hpp"
#include"../visen/Color.hpp"
//#include"../time/sub_animator.hpp"
//#include<exception>
//#include<vector>
namespace aab	{
namespace game	{

class Sprite : public TransformationNode
{
	public:

	typedef aab::visen::TextureBasePtr TextureBasePtr;
	typedef aab::visen::TexturePtr TexturePtr;
	typedef aab::visen::AnimatedTexturePtr AnimatedTexturePtr;
	typedef aab::visen::Colorub Colorub;
	//typedef aab::time::FrameTicker FrameTicker;

	private:

		TextureBasePtr texture;
		//std::vector<time::SubAnimator> subAnimators;
		//int currentSubAnimator;
		//int frames;
		bool updateFrameSize; //update size if frame size changes
		Colorub color;
		bool useColor;

	public:

		explicit Sprite (TextureBasePtr);
		explicit Sprite (TexturePtr,// FrameTicker::Ptr,
                   int frameWidth, int frameHeight);//std::invalid_argument
		virtual ~Sprite();// throw ();

		// draw includes transformation etc. Render is just a direct output.

		void draw ();
		void render ();

		virtual void before ();
		virtual void after ();

		TextureBasePtr getTextureBase ();
		//time::FrameTicker::Ptr getFrameTickerPtr ();

		//inline time::FrameTicker::Ptr getAnimator () { return getFrameTickerPtr(); }

		//void updateAnimation ();

		//int getCurrentSubAnimatorIndex () const;
		//void setSubAnimator(int index);// throw (std::exception&); // will only set if its not current
		//void addSubAnimator(const time::SubAnimator);// throw (std::exception&);
		//std::vector<time::SubAnimator> & accessSubAnimators ();

		visen::BlendMethod & accessBlendMethod () { return texture->accessBlendMethod(); }

		void setFrame(int frame);
		int getFrame()const;
		int getMaximumFrame()const;
		bool isAnimatable()const;

		Colorub getColor()const { return color; }
		void setColor(Colorub colorIn) { color = colorIn; useColor = true; }
		void removeColor() { useColor = false; }
		bool isUsingColor() const { return useColor; }

		void setAlpha(const char alpha) {   color.setAlpha(alpha); useColor = true; }
};

}		//	game
}		//	aab
#endif	//	AAB_GAME_SPRITE_CLASS


text:
<button id="btn1" type="button" onclick="loadXMLDoc()">请求数据</button>

		ttttt
		BBBBBBBB
		CCCCCCCC

	TTTTTTTTTT


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

namespace PrintHost.model.geom
{
    public class TopoTriangleStorage
    {
        public HashSet<TopoTriangle> triangles = new HashSet<TopoTriangle>();
        public TopoTriangleNode tree = null;
        public void Add(TopoTriangle triangle) {
            triangles.Add(triangle);
            if (tree != null)
                tree.AddTriangle(triangle);
        }
        public bool Remove(TopoTriangle triangle)
        {
            if (tree != null)
                tree.RemoveTriangle(triangle);
            return triangles.Remove(triangle);
        }
        public System.Collections.IEnumerator GetEnumerator()
        {
            foreach (TopoTriangle t in triangles)
               yield return t;
        }
        public void Clear()
        {
            tree = null;
            triangles.Clear();
        }
        public bool Contains(TopoTriangle test)
        {
            return triangles.Contains(test);
        }
        public int Count
        {
            get { return triangles.Count; }
        }
        public void PrepareFastSearch()
        {
            tree = new TopoTriangleNode(null);
            foreach (TopoTriangle triangle in triangles)
            {
                tree.AddTriangle(triangle);
            }
        }
        public HashSet<TopoTriangle> FindIntersectionCandidates(TopoTriangle triangle)
        {
            if (tree == null) PrepareFastSearch();
            HashSet<TopoTriangle> result = new HashSet<TopoTriangle>();
            tree.FindIntersectionCandidates(triangle, result);
            return result;
        }
    }
    public class TopoTriangleNode
    {
        int dimension = -1;
        double middlePosition;
        int nextTrySplit = 50;
        TopoTriangleNode parent = null;
        TopoTriangleNode left = null;
        TopoTriangleNode middle = null;
        TopoTriangleNode right = null;
        RHBoundingBox box = new RHBoundingBox();
        private HashSet<TopoTriangle> triangles = null;

        public TopoTriangleNode(TopoTriangleNode _parent)
        {
            parent = _parent;
        }
        public void AddTriangle(TopoTriangle triangle) {
            if(left == null && triangles == null) {
                triangles = new HashSet<TopoTriangle>();
            }
            if (triangles != null)
            {
                triangles.Add(triangle);
                box.Add(triangle.boundingBox);
                if (triangles.Count > nextTrySplit) TrySplit();
            }
            else
            {
                if (triangle.boundingBox.maxPoint[dimension] < middlePosition)
                    left.AddTriangle(triangle);
                else if (triangle.boundingBox.minPoint[dimension] > middlePosition)
                    right.AddTriangle(triangle);
                else
                    middle.AddTriangle(triangle);
            }
        }
        public bool RemoveTriangle(TopoTriangle triangle)
        {
            TopoTriangleNode node = FindNodeForTriangle(triangle);
            if (node != null)
                return node.triangles.Remove(triangle);
            return false;
        }
        public TopoTriangleNode FindNodeForTriangle(TopoTriangle triangle)
        {
            if (triangles != null) return this;
            if (triangle.boundingBox.maxPoint[dimension] < middlePosition)
                return left.FindNodeForTriangle(triangle);
            else if (triangle.boundingBox.minPoint[dimension] > middlePosition)
                return right.FindNodeForTriangle(triangle);
            else
                return middle.FindNodeForTriangle(triangle);
        }
        public void FindIntersectionCandidates(TopoTriangle triangle,HashSet<TopoTriangle> resultList)
        {
            if (triangles != null) // end leaf, test all boxes for intersection
            {
                foreach (TopoTriangle test in triangles)
                {
                    if(test!=triangle && test.boundingBox.IntersectsBox(triangle.boundingBox))
                        resultList.Add(test);
                }
                return;
            }
            if (left == null) return;
            if(triangle.boundingBox.minPoint[dimension]<middlePosition)
                left.FindIntersectionCandidates(triangle,resultList);
            if(triangle.boundingBox.maxPoint[dimension]>middlePosition)
                right.FindIntersectionCandidates(triangle,resultList);
            if(triangle.boundingBox.minPoint[dimension]<middlePosition && triangle.boundingBox.maxPoint[dimension]>middlePosition)
                middle.FindIntersectionCandidates(triangle,resultList);
        }
        private void TrySplit()
        {
            int newDim = 0;
            int parentDimension = -1;
            if (parent != null)
                parentDimension = parent.dimension;
            RHVector3 size = box.Size;
            if (parentDimension != 0) newDim = 0;
            if (parentDimension != 1 && size.x < size.y) newDim = 1;
            if (parentDimension != 2 && size.z > size[newDim]) newDim = 2;
            int loop = 0;
            int maxLoop = 4;
            double bestCenter = 0;
            double bestPercentage = 3000;
            int bestDim = 0;
            for (int dim = 0; dim < 3; dim++)
            {
                if (dim == parentDimension) continue;
                for (loop = 0; loop < maxLoop; loop++)
                {
                    int count = 0;
                    double testDist = box.minPoint[newDim] + size[newDim] * (1 + loop) / (maxLoop + 1);
                    foreach (TopoTriangle tri in triangles)
                    {
                        if (tri.boundingBox.maxPoint[newDim] < testDist)
                            count++;
                    }
                    double percent = 100.0 * (double)count / triangles.Count;
                    if (Math.Abs(50 - percent) < bestPercentage)
                    {
                        bestPercentage = percent;
                        bestCenter = testDist;
                        bestDim = dim;
                    }
                }
            }
            if (bestPercentage < 5)
            {
                nextTrySplit = (nextTrySplit * 3) / 2;
                return; // not effective enough
            }
            left = new TopoTriangleNode(this);
            right = new TopoTriangleNode(this);
            middle = new TopoTriangleNode(this);
            dimension = newDim;
            middlePosition = bestCenter;
            foreach (TopoTriangle tri in triangles)
            {
                if (tri.boundingBox.maxPoint[dimension] < middlePosition)
                    left.AddTriangle(tri);
                else if (tri.boundingBox.minPoint[dimension] > middlePosition)
                    right.AddTriangle(tri);
                else
                    middle.AddTriangle(tri);
            }
            triangles = null;
        }
    }
}


text:
'use strict';

const assert = require('assert');
const Client = require('../../../lib/client');
const types = require('../../../lib/types');
const utils = require('../../../lib/utils');
const policies = require('../../../lib/policies');
const ExecutionProfile = require('../../../lib/execution-profile').ExecutionProfile;
const GraphExecutor = require('../../../lib/datastax/graph/graph-executor');
const { GraphExecutionOptions, graphProtocol } = require('../../../lib/datastax/graph/options');
const helper = require('../../test-helper');

const proxyExecuteKey = 'ProxyExecute';

describe('GraphExecutor', function () {
  describe('#send()', () => {
    it('should encode the parameters and build GraphExecutionOptions', async () => {
      const setup = setupGraphExecutor();
      await setup.instance.send('QUERY1', { a: 1 }, null);

      assert.strictEqual(setup.executionArguments.query, 'QUERY1');
      assert.deepStrictEqual(setup.executionArguments.params, ['{"a":1}']);
      helper.assertInstanceOf(setup.executionArguments.options, GraphExecutionOptions);
      assert.ok(setup.executionArguments.options.getCustomPayload());
    });

    it('should not allow a namespace of type different than string', async () => {
      const setup = setupGraphExecutor();

      // Does not throw
      await setup.instance.send('Q1', {}, { graphName: 'abc' });

      await helper.assertThrowsAsync(setup.instance.send('Q1', {}, { graphName: 123 }), TypeError);
    });

    it('should not allow a array query parameters', async () => {
      const setup = setupGraphExecutor();

      await helper.assertThrowsAsync(setup.instance.send('Q1', [], { }), TypeError,
        'Parameters must be a Object instance as an associative array');
    });

    it('should set the same default options when not set', async () => {
      const setup = setupGraphExecutor();

      await setup.instance.send('Q5', { z: 3 }, null);
      const firstOptions = setup.executionArguments.options;
      assert.ok(firstOptions.getRawQueryOptions());

      setup.instance.send('Q6', { z: 4 }, null, helper.noop);
      assert.strictEqual(firstOptions.getRawQueryOptions(), setup.executionArguments.options.getRawQueryOptions());
      assert.ok(firstOptions.getCustomPayload());
    });

    it('should set the default payload for the executions', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        graphOptions: {
          name: 'name1',
          source: 'a1',
          readConsistency: types.consistencies.localOne
        }
      };

      const setup = setupGraphExecutor(clientOptions);
      const optionsParameter = { anotherOption: { k: 'v'}};

      await setup.instance.send('Q5', { c: 0}, optionsParameter);

      const actualOptions = setup.executionArguments.options;

      assert.strictEqual(optionsParameter.anotherOption, actualOptions.getRawQueryOptions().anotherOption);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'a1');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-name'], 'name1');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-read-consistency'], 'LOCAL_ONE');
      assert.strictEqual(actualOptions.getCustomPayload()['graph-write-consistency'], undefined);
    });

    it('should set the default readTimeout in the payload', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        graphOptions: {
          source: 'x',
          writeConsistency: types.consistencies.two
        }
      };

      const setup = setupGraphExecutor(clientOptions);
      let actualOptions;

      // with options defined
      await setup.instance.send('Q10', { c: 0}, { });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'x');
      assert.strictEqual(actualOptions.getCustomPayload()['graph-read-consistency'], undefined);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-write-consistency'], 'TWO');
      assert.strictEqual(typeof actualOptions.getCustomPayload()['request-timeout'], 'undefined');

      // with payload defined
      await setup.instance.send('Q10', { c: 0}, { customPayload: { 'z': utils.allocBufferFromString('zValue')} });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'x');
      helper.assertBufferString(actualOptions.getCustomPayload()['z'], 'zValue');
      assert.strictEqual(typeof actualOptions.getCustomPayload()['request-timeout'], 'undefined');

      // with timeout defined
      await setup.instance.send('Q10', { c: 0}, { readTimeout: 9999 });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'x');
      assert.strictEqual(actualOptions.getCustomPayload()['z'], undefined);
      assert.deepEqual(actualOptions.getCustomPayload()['request-timeout'],
        types.Long.toBuffer(types.Long.fromNumber(9999)));
      assert.strictEqual(actualOptions.getReadTimeout(), 9999);

      // without options defined
      await setup.instance.send('Q10', { c: 0});
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'x');
      assert.strictEqual(typeof actualOptions.getCustomPayload()['request-timeout'], 'undefined');
    });

    it('should set the read and write consistency levels', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        graphOptions: {
          name: 'name10'
        }
      };

      const setup = setupGraphExecutor(clientOptions);
      let actualOptions;

      await setup.instance.send('Q5', { c: 0});
      actualOptions = setup.executionArguments.options;
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'g');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-name'], 'name10');
      assert.strictEqual(actualOptions.getCustomPayload()['graph-read-consistency'], undefined);
      assert.strictEqual(actualOptions.getCustomPayload()['graph-write-consistency'], undefined);

      let optionsParameter = {
        graphReadConsistency: types.consistencies.localQuorum
      };
      await setup.instance.send('Q5', { c: 0}, optionsParameter);
      actualOptions = setup.executionArguments.options;
      assert.notStrictEqual(optionsParameter, actualOptions);
      assert.strictEqual(optionsParameter.anotherOption, actualOptions.getRawQueryOptions().anotherOption);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-read-consistency'], 'LOCAL_QUORUM');
      assert.strictEqual(actualOptions.getCustomPayload()['graph-write-consistency'], undefined);

      optionsParameter = {
        graphWriteConsistency: types.consistencies.quorum
      };
      await setup.instance.send('Q5', { c: 0}, optionsParameter);
      actualOptions = setup.executionArguments.options;
      assert.notStrictEqual(optionsParameter, actualOptions);
      assert.strictEqual(optionsParameter.anotherOption, actualOptions.anotherOption);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      assert.strictEqual(actualOptions.getCustomPayload()['graph-read-consistency'], undefined);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-write-consistency'], 'QUORUM');
    });

    it('should set graph results', async () => {
      const setup = setupGraphExecutor({ contactPoints: ['host1'] });

      await setup.instance.send('Q5', { c: 0});
      let actualOptions = setup.executionArguments.options;
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
      const optionsParameter = {
        graphResults: 'graphson-3.0'
      };
      await setup.instance.send('Q5', { c: 0}, optionsParameter);
      actualOptions = setup.executionArguments.options;
      assert.notStrictEqual(optionsParameter, actualOptions);
      //shallow copy the properties
      assert.strictEqual(optionsParameter.anotherOption, actualOptions.getRawQueryOptions().anotherOption);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], 'graphson-3.0');
    });

    it('should reuse the values from the default payload for the executions', async () => {
      const clientOptions = { contactPoints: ['host1'], graphOptions: { name: 'name1' }};
      const setup = setupGraphExecutor(clientOptions);
      const optionsParameter = { anotherOption: { k: 'v2'}};

      await setup.instance.send('Q5', { a: 1}, optionsParameter);
      const firstOptions = setup.executionArguments.options;
      await setup.instance.send('Q6', { b: 1}, optionsParameter);

      Object.keys(firstOptions.getCustomPayload())
        .filter(k => k !== 'graph-results')
        .forEach(k => {
          assert.strictEqual(
            firstOptions.getCustomPayload()[k], setup.executionArguments.options.getCustomPayload()[k]);
        });
    });

    it('should set the payload with the options provided', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        graphOptions: {
          language: 'groovy2',
          source: 'another-source',
          name: 'namespace2'
        }};

      const setup = setupGraphExecutor(clientOptions);
      const optionsParameter = { anotherOption: { k: 'v3'}};
      await setup.instance.send('Q5', { 'x': 1 }, optionsParameter);

      const actualOptions = setup.executionArguments.options;
      assert.strictEqual(optionsParameter.anotherOption, actualOptions.getRawQueryOptions().anotherOption);
      assert.ok(actualOptions.getCustomPayload());
      assert.deepStrictEqual(actualOptions.getCustomPayload()['graph-language'],
        utils.allocBufferFromString('groovy2'));
      assert.deepStrictEqual(actualOptions.getCustomPayload()['graph-source'],
        utils.allocBufferFromString('another-source'));
      assert.deepStrictEqual(actualOptions.getCustomPayload()['graph-name'], utils.allocBufferFromString('namespace2'));
    });

    it('should set the payload with the user/role provided', async () => {
      const clientOptions = { contactPoints: ['host1'], graphOptions: { name: 'name2' }};
      const setup = setupGraphExecutor(clientOptions);
      let actualOptions;

      await setup.instance.send('Q5', { 'x': 1 }, null);
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-name'], 'name2');
      assert.strictEqual(actualOptions.getCustomPayload()[proxyExecuteKey], undefined);
      const previousPayload = actualOptions.getCustomPayload();

      await setup.instance.send('Q5', { 'x': 1 }, { executeAs: 'alice' });
      actualOptions = setup.executionArguments.options;
      assert.notStrictEqual(previousPayload, actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-name'], 'name2');
      helper.assertBufferString(actualOptions.getCustomPayload()[proxyExecuteKey], 'alice');
    });

    it('should set the options according to default profile', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        graphOptions: {
          language: 'groovy1',
          source: 'source1',
          name: 'name1'
        },
        profiles: [
          new ExecutionProfile('default', {
            graphOptions: {
              name: 'nameZ',
              readConsistency: types.consistencies.two
            }
          })
        ]
      };

      const setup = setupGraphExecutor(clientOptions);

      await setup.instance.send('Q', { 'x': 1 }, null);
      const actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'groovy1');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson2);
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'source1');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-name'], 'nameZ');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-read-consistency'], 'TWO');
      helper.assertInstanceOf(actualOptions.getRetryPolicy(), policies.retry.FallthroughRetryPolicy);
    });

    it('should set the options according to specified profile', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        graphOptions: {
          source: 'source1',
          name: 'name1'
        },
        profiles: [
          new ExecutionProfile('default', {
            graphOptions: {
              name: 'nameZ',
              readConsistency: types.consistencies.two
            }
          }),
          new ExecutionProfile('graph-olap', {
            graphOptions: {
              source: 'aaa',
              readConsistency: types.consistencies.three,
              writeConsistency: types.consistencies.quorum
            },
            readTimeout: 99000
          })
        ]
      };

      const setup = setupGraphExecutor(clientOptions);
      const optionsParameter = { executionProfile: 'graph-olap' };
      let actualOptions;
      await setup.instance.send('Q', { 'x': 1 }, optionsParameter);
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.ok(actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-source'], 'aaa');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-name'], 'nameZ');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-read-consistency'], 'THREE');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-write-consistency'], 'QUORUM');
      assert.deepEqual(actualOptions.getCustomPayload()['request-timeout'],
        types.Long.toBuffer(types.Long.fromNumber(99000)));
      const lastOptions = actualOptions;

      await setup.instance.send('Q2', { 'x': 2 }, optionsParameter);
      actualOptions = setup.executionArguments.options;
      assert.notStrictEqual(actualOptions, lastOptions);
      helper.assertInstanceOf(actualOptions.getRetryPolicy(), policies.retry.FallthroughRetryPolicy);
      optionsParameter.retry = new policies.retry.RetryPolicy();

      await setup.instance.send('Q2', { 'x': 3 }, optionsParameter);
      actualOptions = setup.executionArguments.options;
      assert.strictEqual(actualOptions.getRetryPolicy(), optionsParameter.retry);
    });

    it('should use the retry policy from the default profile when specified', async () => {
      const retryPolicy1 = new policies.retry.RetryPolicy();
      const retryPolicy2 = new policies.retry.FallthroughRetryPolicy();
      const retryPolicy3 = new policies.retry.FallthroughRetryPolicy();
      const clientOptions = {
        contactPoints: ['host1'],
        profiles: [
          new ExecutionProfile('default', {
            retry: retryPolicy1
          }),
          new ExecutionProfile('graph-olap', {
            retry: retryPolicy2
          })
        ]
      };

      const setup = setupGraphExecutor(clientOptions);
      let actualOptions;
      await setup.instance.send('Q', null, null);
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy1);

      await setup.instance.send('Q', null, { executionProfile: 'graph-olap' });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy2);

      await setup.instance.send('Q', null, { executionProfile: 'graph-olap', retry: retryPolicy3 });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy3);

      await setup.instance.send('Q', null, { retry: retryPolicy3 });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy3);
    });

    it('should use specific retry policy when not specified in the default profile',async () => {
      const retryPolicy1 = new policies.retry.RetryPolicy();
      const retryPolicy2 = new policies.retry.RetryPolicy();
      const clientOptions = {
        contactPoints: ['host1'],
        profiles: [
          new ExecutionProfile('default'),
          new ExecutionProfile('graph-olap', {
            retry: retryPolicy1
          })
        ]
      };
      const setup = setupGraphExecutor(clientOptions);
      let actualOptions;

      await setup.instance.send('Q', null, null);
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      helper.assertInstanceOf(actualOptions.getRetryPolicy(), policies.retry.FallthroughRetryPolicy);

      await setup.instance.send('Q', null, { executionProfile: 'default'});
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      helper.assertInstanceOf(actualOptions.getRetryPolicy(), policies.retry.FallthroughRetryPolicy);

      await setup.instance.send('Q', null, { executionProfile: 'graph-olap' });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy1);

      await setup.instance.send('Q', null, { executionProfile: 'graph-olap', retry: retryPolicy2 });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy2);

      await setup.instance.send('Q', null, { retry: retryPolicy2 });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy2);
    });

    it('should use specific retry policy when no default profile specified', async () => {
      const retryPolicy1 = new policies.retry.RetryPolicy();
      const retryPolicy2 = new policies.retry.RetryPolicy();
      const clientOptions = {
        contactPoints: ['host1'],
        profiles: [
          new ExecutionProfile('graph-olap', {
            retry: retryPolicy1
          })
        ]
      };

      const setup = setupGraphExecutor(clientOptions);
      let actualOptions;

      await setup.instance.send('Q', null, null);
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      helper.assertInstanceOf(actualOptions.getRetryPolicy(), policies.retry.FallthroughRetryPolicy);

      await setup.instance.send('Q', null, { executionProfile: 'default'});
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      helper.assertInstanceOf(actualOptions.getRetryPolicy(), policies.retry.FallthroughRetryPolicy);

      await setup.instance.send('Q', null, { executionProfile: 'graph-olap' });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy1);

      await setup.instance.send('Q', null, { executionProfile: 'graph-olap', retry: retryPolicy2 });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy2);

      await setup.instance.send('Q', null, { retry: retryPolicy2 });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions);
      assert.strictEqual(actualOptions.getRetryPolicy(), retryPolicy2);
    });

    it('should use the graph language provided in the profile', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        profiles: [
          new ExecutionProfile('graph-olap', {
            graphOptions: { language: 'lolcode' }
          })
        ]
      };
      const setup = setupGraphExecutor(clientOptions);

      let actualOptions;
      await setup.instance.send('Q', null, { executionProfile: 'graph-olap' });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions && actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'lolcode');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson2);

      await setup.instance.send('Q');
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions && actualOptions.getCustomPayload());
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-language'], 'gremlin-groovy');
      helper.assertBufferString(actualOptions.getCustomPayload()['graph-results'], graphProtocol.graphson1);
    });

    it('should use the graph results provided in the profile', async () => {
      const clientOptions = {
        contactPoints: ['host1'],
        profiles: [
          new ExecutionProfile('graph-olap', {
            graphOptions: { results: graphProtocol.graphson2 }
          })
        ]
      };
      const setup = setupGraphExecutor(clientOptions);

      let actualOptions;
      await setup.instance.send('Q', null, { executionProfile: 'graph-olap' });
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions && actualOptions.getCustomPayload());
      assert.strictEqual(actualOptions.getCustomPayload()['graph-results'].toString(), graphProtocol.graphson2);
      await setup.instance.send('Q', null, null);
      actualOptions = setup.executionArguments.options;
      assert.ok(actualOptions && actualOptions.getCustomPayload());
      // Default for gremlin groovy
      assert.strictEqual(actualOptions.getCustomPayload()['graph-results'].toString(), graphProtocol.graphson1);
    });

    context('with analytics queries', function () {
      it('should query for analytics master', async () => {
        const clientOptions = {
          contactPoints: ['host1'],
          graphOptions: {
            source: 'a',
            name: 'name1'
          }};

        const setup = setupGraphExecutor(clientOptions);

        await setup.instance.send('g.V()', null, {});
        const actualOptions = setup.executionArguments.options;
        assert.ok(actualOptions);
        assert.ok(actualOptions.getPreferredHost());
        assert.ok(actualOptions.getPreferredHost().address, '10.10.10.10:9042');
      });

      it('should query for analytics master when using execution profile', async () => {
        const clientOptions = {
          contactPoints: ['host1'],
          profiles: [
            new ExecutionProfile('analytics', {
              graphOptions: {
                source: 'a'
              }
            })
          ]
        };

        const setup = setupGraphExecutor(clientOptions);

        await setup.instance.send('g.V()', null, { executionProfile: 'analytics' });
        const actualOptions = setup.executionArguments.options;
        assert.ok(actualOptions);
        assert.ok(actualOptions.getPreferredHost());
        assert.ok(actualOptions.getPreferredHost().address, '10.10.10.10:9042');
      });

      it('should call address translator', async () => {
        let translatorCalled = 0;
        const translator = new policies.addressResolution.AddressTranslator();
        translator.translate = function (ip, port, cb) {
          translatorCalled++;
          cb(ip + ':' + port);
        };

        const clientOptions = {
          contactPoints: ['host1'],
          graphOptions: {
            source: 'a',
            name: 'name1'
          },
          policies: {
            addressResolution: translator
          }
        };

        const setup = setupGraphExecutor(clientOptions);

        await setup.instance.send('g.V()', null, null);
        const actualOptions = setup.executionArguments.options;
        assert.ok(actualOptions);
        assert.ok(actualOptions.getPreferredHost());
        assert.strictEqual(actualOptions.getPreferredHost().address, '10.10.10.10:9042');
        assert.strictEqual(translatorCalled, 1);
      });

      it('should set preferredHost to null when RPC errors', async () => {
        const clientOptions = {
          contactPoints: ['host1'],
          graphOptions: {
            source: 'a',
            name: 'name1'
          }};

        const clientProperties = {
          execute: function (q) {
            if (q === 'CALL DseClientTool.getAnalyticsGraphServer()') {
              return Promise.reject(new Error('Test error'));
            }

            return Promise.resolve({ rows: []});
          }
        };

        const setup = setupGraphExecutor(clientOptions, clientProperties);

        await setup.instance.send('g.V()');
        const actualOptions = setup.executionArguments.options;
        assert.ok(actualOptions);
        assert.strictEqual(actualOptions.getPreferredHost(), null);
      });
    });
  });
});

function setupGraphExecutor(clientOptions, clientProperties) {
  clientOptions = clientOptions || { contactPoints: [ 'h1' ] };
  const client = new Client(clientOptions);

  const result = {
    executionArguments: null,
    instance: null
  };

  result.instance = new GraphExecutor(client, clientOptions, (query, params, options) => {
    result.executionArguments = { query, params, options };
    return Promise.resolve({ rows: [] });
  });

  client.hosts = { get: address => ({ type: 'host', address: address }) };
  client.execute = q => {
    if (q === 'CALL DseClientTool.getAnalyticsGraphServer()') {
      return Promise.resolve({ rows: [ { result: { location: '10.10.10.10:1234' }} ]});
    }

    return Promise.resolve({ rows: []});
  };

  if (clientProperties) {
    Object.keys(clientProperties).forEach(propName => client[propName] = clientProperties[propName]);
  }

  return result;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Venenarius subcitriniceps Murrill

### Remarks
null


text:
namespace Martin {
    public enum HttpVerbs { GET, POST, PUT, DELETE }
}


text:
package org.metasyntactic.recreation.life;

import org.apache.commons.collections.map.MultiValueMap;

import java.io.*;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class Universe {
    private final static Map<AbstractNode, AbstractNode> internMap =
            new HashMap<AbstractNode, AbstractNode>();
    private final static Map<Integer, AbstractNode> emptyNodes = new HashMap<Integer, AbstractNode>();

    public static AbstractNode lookupNode(AbstractNode node) {
        AbstractNode result = internMap.get(node);
        if (result == null) {
            result = node;
            internMap.put(result, result);
        }

        return result;
    }

    public static AbstractNode emptyNode(int depth) {
        AbstractNode node = emptyNodes.get(depth);
        if (node == null) {
            if (depth == 2) {
                node = Leaf.emptyLeaf();
            } else {
                AbstractNode subNode = emptyNode(depth - 1);
                node = new Node(subNode, subNode, subNode, subNode);
                internMap.put(node, node);
            }

            emptyNodes.put(depth, node);
        }

        return node;
    }

    private static int universeAge;

    private final Node root;
    private final static BigInteger TWO = new BigInteger("2");

    private final static Node defaultEmptyNode =
            Node.newNode(
                    Leaf.emptyLeaf(),
                    Leaf.emptyLeaf(),
                    Leaf.emptyLeaf(),
                    Leaf.emptyLeaf());

    public Universe() {
        this(Node.newNode(defaultEmptyNode, defaultEmptyNode, defaultEmptyNode, defaultEmptyNode));
    }

    public Universe(AbstractNode node) {
        this(node instanceof Leaf ? node.push() : (Node) node);
    }

    private Universe(Node root) {
        universeAge++;
        if (universeAge % 5000 == 0) {
            flushUniverse();
            this.root = (Node) root.canonicalize();
        } else {
            this.root = root;
        }
    }

    public Node getRoot() {
        return root;
    }

    private void flushUniverse() {
        internMap.clear();
        for (AbstractNode node : emptyNodes.values()) {
            internMap.put(node, node);
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        MultiValueMap liveLocations = root.getLiveLocations();
        int minX = Integer.MAX_VALUE;
        int maxX = 0;
        int minY = Integer.MAX_VALUE;
        int maxY = 0;

        for (int x : (Set<Integer>) liveLocations.keySet()) {
            minX = Math.min(x, minX);
            maxX = Math.max(x, maxX);

            TreeSet<Integer> ys = (TreeSet<Integer>) liveLocations.getCollection(x);
            minY = Math.min(ys.first(), minY);
            maxY = Math.max(ys.last(), maxY);
        }

        int width = maxX - minX;
        int height = maxY - minY;
        printDashes(builder, width);
        builder.append('\n');

        for (int y = 0; y < height; y++) {
            builder.append('|');

            for (int x = 0; x < width; x++) {
                boolean b = liveLocations.containsValue(minX + x, minY + y);

                builder.append(b ? '*' : ' ');
            }

            builder.append('|');
            builder.append('\n');
        }

        printDashes(builder, width);

        return builder.toString();
    }

    private void printDashes(StringBuilder builder, int widthHeight) {
        for (int y = 0; y < widthHeight + 2; y++) {
            builder.append('-');
        }
    }

    public Universe setValue(int x, int y, boolean value) {
        return setValue(new BigInteger(String.valueOf(x)),
                new BigInteger(String.valueOf(y)), value);
    }

    public Universe setValue(BigInteger x, BigInteger y, boolean value) {
        return new Universe(root.setValue(x, y, value));
    }

    public Universe step() {
        Node node = root.push();

        AbstractNode nextGeneration = node.nextGeneration();
        if (nextGeneration instanceof Leaf || ((Node) nextGeneration).expandsBeyondCenter()) {
            nextGeneration = nextGeneration.push();
        }

        return new Universe(nextGeneration);
    }

    public static AbstractNode read(File file) throws IOException, ClassNotFoundException {
        if (file.getName().toLowerCase().endsWith(".lifematrix")) {
            return readLifeMatrix(file);
        } else if (file.getName().toLowerCase().endsWith(".lifetree")) {
            return readLifeTree(file);
        } else {
            throw new IllegalArgumentException();
        }
    }

    private static AbstractNode readLifeTree(File file) throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));

        AbstractNode node = (AbstractNode) in.readObject();

        return node;
    }

    private static AbstractNode readLifeMatrix(File file) throws IOException {
        LineNumberReader in = new LineNumberReader(new FileReader(file));
        String line;

        int maxY = 0;
        int maxX = 0;

        for (int y = 0; (line = in.readLine()) != null; y++) {
            if (line.trim().equals("#")) {
                break;
            }

            if (y > maxY) {
                maxY = y;
            }

            maxX = Math.max(maxX, line.length());
        }

        AbstractNode node = Leaf.emptyLeaf();
        while (node.depth() < Math.log(Math.max(maxX, maxY)) + 1) {
            node = node.push();
        }

        in.close();
        in = new LineNumberReader(new FileReader(file));
        for (int y = 0; (line = in.readLine()) != null; y++) {
            if (line.trim().equals("#")) {
                break;
            }

            BigInteger bigY = new BigInteger(String.valueOf(y));

            for (int x = 0; x < line.length(); x++) {
                if (line.charAt(x) != ' ') {
                    node = node.setValue(new BigInteger(String.valueOf(x)), bigY, true);
                }
            }
        }

        return node;
    }
}


text:
package uk.sky.cqlmigrate;

import com.datastax.oss.driver.api.core.ConsistencyLevel;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.DriverException;
import com.datastax.oss.protocol.internal.request.Prepare;
import com.datastax.oss.simulacron.common.cluster.ClusterSpec;
import com.datastax.oss.simulacron.common.cluster.DataCenterSpec;
import com.datastax.oss.simulacron.common.cluster.QueryLog;
import com.datastax.oss.simulacron.common.codec.WriteType;
import com.datastax.oss.simulacron.server.BoundCluster;
import com.datastax.oss.simulacron.server.Server;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.assertj.core.api.AbstractThrowableAssert;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import uk.sky.cqlmigrate.exception.CannotAcquireLockException;
import uk.sky.cqlmigrate.exception.CannotReleaseLockException;
import uk.sky.cqlmigrate.util.PortScavenger;

import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.datastax.oss.simulacron.common.stubbing.PrimeDsl.*;
import static java.lang.String.valueOf;
import static org.assertj.core.api.Assertions.*;

public class CassandraLockingMechanismTest {

    private static final String LOCK_KEYSPACE = "lock-keyspace";
    private static final String CLIENT_ID = UUID.randomUUID().toString();
    private static final String PREPARE_INSERT_QUERY = "INSERT INTO cqlmigrate.locks (name, client) VALUES (?, ?) IF NOT EXISTS";
    private static final String PREPARE_DELETE_QUERY = "DELETE FROM cqlmigrate.locks WHERE name = ? IF client = ?";

    private static final int defaultStartingPort = PortScavenger.getFreePort();
    private static final Server server = Server.builder().build();
    private static final ClusterSpec clusterSpec = ClusterSpec.builder().build();

    private static BoundCluster cluster;
    private static DataCenterSpec dc;

    private CqlSession session;
    private CassandraLockingMechanism lockingMechanism;

    Predicate<QueryLog> prepareQueryPredicate = i -> i.getFrame().message instanceof Prepare;

    @BeforeClass
    public static void classSetup() throws UnknownHostException {
        dc = clusterSpec.addDataCenter().withName("DC1").withCassandraVersion("3.11").build();
        dc.addNode()
                .withAddress(new InetSocketAddress(Inet4Address.getByAddress(new byte[]{127, 0, 0, 1}), defaultStartingPort))
                .withPeerInfo("host_id", UUID.randomUUID())
                .build();
        cluster = server.register(clusterSpec);

        cluster.prime(when("select cluster_name from system.local where key = 'local'")
                .then(rows().row("cluster_name", "0").build()));
    }

    @Before
    public void baseSetup() throws Exception {
        cluster.acceptConnections();
        cluster.clearLogs();
        cluster.clearPrimes(true);

        session = newSession();
        lockingMechanism = new CassandraLockingMechanism(session, LOCK_KEYSPACE, ConsistencyLevel.ALL, "cqlmigrate");
    }

    @After
    public void baseTearDown() {
        session.close();
    }

    @Test
    public void shouldPrepareInsertLocksQueryWhenInit() {
        //when
        lockingMechanism.init();
        //then
        List<QueryLog> queryLogs = cluster.getLogs().getQueryLogs().stream()
                .filter(prepareQueryPredicate)
                .filter(queryLog -> ((Prepare) queryLog.getFrame().message).cqlQuery.equals(PREPARE_INSERT_QUERY))
                .collect(Collectors.toList());

        assertThat(queryLogs.size()).isEqualTo(1);
    }

    @Test
    public void shouldPrepareDeleteLocksQueryWhenInit() {
        //when
        lockingMechanism.init();

        //then
        List<QueryLog> queryLogs = cluster.getLogs().getQueryLogs().stream()
                .filter(queryLog -> queryLog.getFrame().message.toString().contains(PREPARE_DELETE_QUERY))
                .filter(prepareQueryPredicate).collect(Collectors.toList());
        assertThat(queryLogs.size()).isEqualTo(1);
    }

    @Test
    public void shouldSuccessfullyAcquireLockWhenInsertIsApplied() {
        //given
        cluster.prime(primeInsertQuery(LOCK_KEYSPACE, CLIENT_ID, true));
        //when
        lockingMechanism.init();
        boolean acquiredLock = lockingMechanism.acquire(CLIENT_ID);
        //then
        assertThat(acquiredLock)
                .describedAs("lock was acquired")
                .isTrue();
    }

    @Test
    public void shouldSuccessfullyAcquireLockWhenLockIsAlreadyAcquired() {
        //given
        cluster.prime(primeInsertQuery(LOCK_KEYSPACE, CLIENT_ID, false));
        //when
        lockingMechanism.init();
        boolean acquiredLock = lockingMechanism.acquire(CLIENT_ID);
        //then
        assertThat(acquiredLock)
                .describedAs("lock was acquired")
                .isTrue();
    }

    @Test
    public void shouldNotAcquireLockWhenLockIsAlreadyAcquiredByDifferentClient() {
        //given
        cluster.prime(primeInsertQueryAcquiredByDifferentClient(LOCK_KEYSPACE, CLIENT_ID));
        //when
        lockingMechanism.init();
        boolean acquiredLock = lockingMechanism.acquire(CLIENT_ID);
        //then
        assertThat(acquiredLock)
                .describedAs("lock not acquired")
                .isFalse();
    }

    @Test
    public void shouldUnsuccessfullyAcquireLockWhenInsertIsNotApplied() {
        //given
        cluster.prime(primeInsertQuery(LOCK_KEYSPACE, CLIENT_ID, true).
                then(writeTimeout(com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL, 1, 1, WriteType.SIMPLE)));

        //when
        lockingMechanism.init();
        boolean acquiredLock = lockingMechanism.acquire(CLIENT_ID);

        //then
        assertThat(acquiredLock)
                .describedAs("lock was not acquired")
                .isFalse();
    }

    @Test
    public void shouldThrowExceptionIfQueryFailsToExecuteWhenAcquiringLock() {
        cluster.prime(primeInsertQuery(LOCK_KEYSPACE, CLIENT_ID, true).
                then(unavailable(com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL, 1, 1)));
        lockingMechanism.init();
        //when
        Throwable throwable = catchThrowable(() -> lockingMechanism.acquire(CLIENT_ID));
        //then
        assertThat(throwable)
                .isNotNull()
                .isInstanceOf(CannotAcquireLockException.class)
                .hasCauseInstanceOf(DriverException.class)
                .hasMessage(String.format("Query to acquire lock %s.schema_migration for client %s failed to execute", LOCK_KEYSPACE, CLIENT_ID));
    }

    @Test
    public void shouldDeleteLockWhenReleasingLock() {
        //given
        cluster.prime(primeDeleteQuery(LOCK_KEYSPACE, CLIENT_ID, true));
        //when
        lockingMechanism.init();
        boolean isLockReleased = lockingMechanism.release(CLIENT_ID);

        //then
        assertThat(isLockReleased).isTrue();
        List<QueryLog> queryLogs = cluster.getLogs().getQueryLogs().stream()
                .filter(queryLog -> queryLog.getFrame().message.toString().contains(PREPARE_DELETE_QUERY))
                .collect(Collectors.toList());

        assertThat(queryLogs.size()).isEqualTo(1);
    }

    @Test
    public void shouldSuccessfullyReleaseLockWhenNoLockFound() {
        cluster.prime(primeDeleteQuery(LOCK_KEYSPACE, CLIENT_ID, false));
        lockingMechanism.init();
        //when
        AbstractThrowableAssert<?, ? extends Throwable> execution = assertThatCode(
                () -> lockingMechanism.release(CLIENT_ID)
        );
        // then
        execution.doesNotThrowAnyException();
    }

    @Test
    public void shouldThrowExceptionIfQueryFailsToExecuteWhenReleasingLock() {
        //given
        cluster.prime(primeDeleteQuery(LOCK_KEYSPACE, CLIENT_ID, true).
                then(unavailable(com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL, 1, 1)));
        lockingMechanism.init();

        //when
        Throwable throwable = catchThrowable(() -> lockingMechanism.release(CLIENT_ID));

        //then
        assertThat(throwable)
                .isNotNull()
                .isInstanceOf(CannotReleaseLockException.class)
                .hasCauseInstanceOf(DriverException.class)
                .hasMessage("Query failed to execute");
    }

    @Test
    public void shouldSuccessfullyReleaseLockWhenRetryingAfterWriteTimeOutButDoesNotHoldLockNow() {
        //given
        cluster.prime(primeDeleteQuery(LOCK_KEYSPACE, CLIENT_ID, false).
                then(writeTimeout(com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL, 1, 1, WriteType.SIMPLE)));

        //when
        lockingMechanism.init();
        lockingMechanism.release(CLIENT_ID);

        //then prime a success
        cluster.clearPrimes(true);
        cluster.prime(primeDeleteQuery(LOCK_KEYSPACE, CLIENT_ID, true));

        //when
        boolean result = lockingMechanism.release(CLIENT_ID);

        //then
        assertThat(result)
                .describedAs("lock was released")
                .isTrue();
    }

    @Test
    public void shouldThrowCannotReleaseLockExceptionWhenLockNotHeldByUs() {
        //when
        String newLockHolder = "new lock holder";
        cluster.prime(primeDeleteQueryFailsWithLockForOtherClient(LOCK_KEYSPACE, CLIENT_ID, newLockHolder));
        //and
//        primeDeleteQuery(LOCK_KEYSPACE, CLIENT_ID, false);
//        cluster.prime(primeBuilder.then(noRows()));
        lockingMechanism.init();

        Throwable throwable = catchThrowable(() -> lockingMechanism.release(CLIENT_ID));

        assertThat(throwable)
                .isNotNull()
                .isInstanceOf(CannotReleaseLockException.class)
                .hasMessage(String.format("Lock %s.schema_migration attempted to be released by a non lock holder (%s). Current lock holder: %s", LOCK_KEYSPACE, CLIENT_ID, newLockHolder));
    }

    @Test // Not sure if this is a realistic possibility?
    public void shouldReturnFalseIfDeleteNotAppliedButClientIsUs() {
        //given
        cluster.prime(primeDeleteQueryFailsWithLockForOtherClient(LOCK_KEYSPACE, CLIENT_ID, CLIENT_ID));
        lockingMechanism.init();
        //when
        boolean released = lockingMechanism.release(CLIENT_ID);

        //then
        assertThat(released)
                .describedAs("lock was not released")
                .isFalse();
    }

    private CqlSession newSession() throws UnknownHostException {
        return CqlSession.builder().addContactPoint(new InetSocketAddress(Inet4Address.getByAddress(new byte[]{127, 0, 0, 1}), defaultStartingPort)).withLocalDatacenter(dc.getName()).build();
    }

    private static PrimeBuilder primeInsertQuery(String lockName, String clientId, Boolean lockApplied) {
        String prepareInsertQuery = "INSERT INTO cqlmigrate.locks (name, client) VALUES (?, ?) IF NOT EXISTS";

        return when(query(
                prepareInsertQuery,
                Lists.newArrayList(
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ONE,
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL),
                new LinkedHashMap<>(ImmutableMap.of("name", lockName + ".schema_migration", "client", clientId)),
                new LinkedHashMap<>(ImmutableMap.of("name", "varchar", "client", "varchar"))))
                .then(rows().row(
                        "[applied]", valueOf(lockApplied), "client", CLIENT_ID).columnTypes("[applied]", "boolean", "clientid", "varchar")
                );
    }

    private static PrimeBuilder primeInsertQueryAcquiredByDifferentClient(String lockName, String clientId) {
        String prepareInsertQuery = "INSERT INTO cqlmigrate.locks (name, client) VALUES (?, ?) IF NOT EXISTS";
        String differentClient = UUID.randomUUID().toString();

        return when(query(
                prepareInsertQuery,
                Lists.newArrayList(
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ONE,
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL),
                new LinkedHashMap<>(ImmutableMap.of("name", lockName + ".schema_migration", "client", clientId)),
                new LinkedHashMap<>(ImmutableMap.of("name", "varchar", "client", "varchar"))))
                .then(rows().row(
                        "[applied]", valueOf(false), "client", differentClient).columnTypes("[applied]", "boolean", "clientid", "varchar")
                );
    }

    private static PrimeBuilder primeDeleteQuery(String lockName, String queriedClientId, boolean lockDeleted) {
        String deleteQuery = "DELETE FROM cqlmigrate.locks WHERE name = ? IF client = ?";

        return when(query(
                deleteQuery,
                Lists.newArrayList(
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ONE,
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL),
                new LinkedHashMap<>(ImmutableMap.of("name", lockName + ".schema_migration", "client", queriedClientId)),
                new LinkedHashMap<>(ImmutableMap.of("name", "varchar", "client", "varchar"))))
                .then(rows()
                        .row("[applied]", valueOf(lockDeleted)).columnTypes("[applied]", "boolean"));
    }

    private static PrimeBuilder primeDeleteQueryFailsWithLockForOtherClient(String lockName, String queriedClientId, String lockHeldClientId) {
        String deleteQuery = "DELETE FROM cqlmigrate.locks WHERE name = ? IF client = ?";

        return when(query(
                deleteQuery,
                Lists.newArrayList(
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ONE,
                        com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL),
                new LinkedHashMap<>(ImmutableMap.of("name", lockName + ".schema_migration", "client", queriedClientId)),
                new LinkedHashMap<>(ImmutableMap.of("name", "varchar", "client", "varchar"))))
                .then(rows()
                        .row("[applied]", false, "client", lockHeldClientId).columnTypes("[applied]", "boolean", "clientid", "varchar"));
    }

}


text:
namespace crashpad {

ScopedPtraceAttach::ScopedPtraceAttach()
    : pid_(-1) {}

ScopedPtraceAttach::~ScopedPtraceAttach() {
  Reset();
}

bool ScopedPtraceAttach::Reset() {
  if (pid_ >= 0 && ptrace(PTRACE_DETACH, pid_, nullptr, nullptr) != 0) {
    PLOG(ERROR) << "ptrace";
    return false;
  }
  pid_ = -1;
  return true;
}

bool ScopedPtraceAttach::ResetAttach(pid_t pid) {
  Reset();

  if (ptrace(PTRACE_ATTACH, pid, nullptr, nullptr) != 0) {
    PLOG(ERROR) << "ptrace";
    return false;
  }
  pid_ = pid;

  int status;
  if (HANDLE_EINTR(waitpid(pid_, &status, __WALL)) < 0) {
    PLOG(ERROR) << "waitpid";
    return false;
  }
  if (!WIFSTOPPED(status)) {
    LOG(ERROR) << "process not stopped";
    return false;
  }
  return true;
}

}  // namespace crashpad


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

namespace Cats.Web.Adminstration.Models.ViewModels
{
    public class HubOwnerViewModel
    {
        public int HubOwnerID { get; set; }
        public string Name { get; set; }
        public string LongName { get; set; }
        public string Hub { get; set; }
        public int HubId { get; set; }

    }
}


text:
// <copyright file="OptionsConcernClassAttribute.cs" company="Cui Ziqiang">
// Copyright (c) 2017 Cui Ziqiang
// </copyright>

namespace CrossCutterN.Test.OptionsTest
{
    using CrossCutterN.Base.Concern;

    /// <summary>
    /// Class concern attribute for options test.
    /// </summary>
    internal sealed class OptionsConcernClassAttribute : ConcernClassAttribute
    {
    }
}


text:
package io.seata.server.console.service;

import io.seata.server.console.param.GlobalSessionParam;
import io.seata.server.console.vo.GlobalSessionVO;
import io.seata.console.result.PageResult;

/**
 * Global session service
 * @author wangzhongxiang
 */
public interface GlobalSessionService {

    /**
     * Query global session
     * @param param the param
     * @return the GlobalSessionVO list
     */
    PageResult<GlobalSessionVO> query(GlobalSessionParam param);

}


text:
package edu.jhu.pacaya.gm.model;

import java.io.IOException;
import java.io.Writer;

import edu.jhu.prim.util.Lambda.LambdaBinOpDouble;

/**
 * Model for a single template in a CRF/MRF.
 * @author mgormley
 */
// TODO: Use this interface.
public interface TemplateModel {

    void add(int config, int feat, double addend);

    double[] getParams(int config);

    void printModel(Writer writer) throws IOException;

    int getNumParams();

    int getNumConfigs();

    int getNumFeats(int c);

    void apply(LambdaBinOpDouble lambda);
}


text:
import os

os.system("python FeatureExtract.py")
os.system("python Labelling.py")
os.system("python MatchLabels.py")
os.system("python Feature_Selection.py")
os.system("python GaussianNB.py")
os.system("python LogisticRegression.py")
os.system("python DecisionTree.py")
os.system("python SVM.py")
os.system("python NeuralNets.py")
os.system("python Combine.py")

exit()


text:
Configuration File
==================

Ketrew applications (ie. server or client), use a JSON format
for configuration (it is possible to generate that file from OCaml or
even to avoid all configuration files by creating your own
[ad-hoc command-line application](./Alternative_CLI_Application.md)).

The configuration file can contain one or more named "profiles".

Location
--------

Ketrew finds it's configuration file by successively checking:

1. the command line option `--configuration-file` (alias: `-C`)
2. the environment variables `KETREW_CONFIGURATION` and `KETREW_CONFIG`,
3. given a "root" directory (either by the variable `KETREW_ROOT` or the default
`$HOME/.ketrew/`), Ketrew will try to access the files:
    - `configuration.json`,
    - `configuration.ml`, and
    - `configuration.sh`

Given the extension of the filename Ketrew will read the configuration
differently:

- `.json` → will read and parse the file;
- `.ml` → will execute `ocaml <file>`, collect `stdout`, and parse it (as JSON);
- `.sh` → will execute `./<file>`, collect `stdout`, and parse it (as JSON).

Other file extension are considered undefined behavior for future use.

After parsing the configuration file, Ketrew will select a profile by name:

1. using the command line option `-P`/`--configuration-profile`,
2. checking the environment variable `KETREW_PROFILE`,
3. using `"default"`.

Generating From Command Line
----------------------------

The command `ketrew initialize` can generate a configuration file (among other
things); see `ketrew init --help`.

Example
-------

A configuration file `configuration.ml` (that Ketrew will execute through
`OCaml`) would look like:

```ocaml
#use "topfind"
#thread
#require "ketrew"

open Ketrew.Configuration

let debug_level = 2
(* `debug-level`: integer specifying the amount of verbose messages:
    `0`: none,
    `1`: verbose,
    `2`: very verbose.
*)

(* Plugins to load: *)
let plugins = [
  `OCamlfind "lwt.react";
  `Compiled "/path/to/some/ketrew_plugin.cmxs";
]

(* User-Interface preferences: *)
let explorer =
  explorer
    ~request_targets_ids:(`Younger_than (`Days 1.5))
    ~targets_per_page:5
    ~targets_to_prefetch:10 ()
let ui = ui ~with_color:true ~explorer ~with_cbreak:true ()

(* A function that given a boolean value creates a "server
  configuration" that detaches or not from the shell. *)
let my_servers daemon =
  server ~ui
    ~engine:(engine ~database_parameters:"/path/to/sqlite-database-client-server" ())
    ~authorized_tokens:[
       authorized_tokens_path "/path/to/authorized-tokens";
       authorized_token ~name:"The-inline-one" "inlinetoken";
     ]
    ~return_error_messages:true
    ~log_path:"/path/to/logs-of-server.txt"
    ~daemon
    ~command_pipe:"/path/to/command.pipe"
    (`Tls ("/path/to/cert.pem", "/path/to/key.pem", 8443))

(* We put together 4 profiles in this configuration and "output" them
   (literally, as Json, to `stdout`).

   `debug_level`, `plugins`, and `ui` are shared between configurations.
*)
let () =
  output [
    profile "standalone"
      (create ~debug_level ~plugins
         (standalone ~ui ()
            ~engine:(engine ~database_parameters:"/path/to/sqlite-database-standalone" ())));
    profile "daemon"
      (create ~debug_level ~plugins (my_servers true));
    profile "server"
      (create ~debug_level ~plugins (my_servers false));
    profile "client"
      (create ~debug_level ~plugins (
          client ~ui ~token:"nekot" "https://127.0.0.1:8443"
          ));
  ]
```

You may run `ocaml configuration.ml` to see the equivalent Json.

Creating a test environment (`make test-env`, cf. developer
[docs](./Developer_Documentation.md)) generates a pretty complex configuration
file.

Option Details
--------------

To build configurations refer to the [API](src/lib/configuration.mli) of
the `Ketrew.Configuration` module.

As shown above, the idea is to call the function `Ketrew.Configuration.output`
with results of the function `Ketrew.Configuration.profile`, themselves created
thanks to the function `Ketrew.Configuration.create`, etc.

Print The Configuration
-----------------------

One can always test their configuration with:

    ketrew print-configuration


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Microsphaera schizandrae Sawada

### Remarks
null


text:
package org.omg.spec.bpmn._20100524.model;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;

/**
 *
Java class for tCatchEvent complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="tCatchEvent">
 *   <complexContent>
 *     <extension base="{http://www.omg.org/spec/BPMN/20100524/MODEL}tEvent">
 *       <sequence>
 *         <element ref="{http://www.omg.org/spec/BPMN/20100524/MODEL}dataOutput" maxOccurs="unbounded" minOccurs="0"/>
 *         <element ref="{http://www.omg.org/spec/BPMN/20100524/MODEL}dataOutputAssociation" maxOccurs="unbounded" minOccurs="0"/>
 *         <element ref="{http://www.omg.org/spec/BPMN/20100524/MODEL}outputSet" minOccurs="0"/>
 *         <element ref="{http://www.omg.org/spec/BPMN/20100524/MODEL}eventDefinition" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="eventDefinitionRef" type="{http://www.w3.org/2001/XMLSchema}QName" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="parallelMultiple" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tCatchEvent", propOrder = {
    "dataOutputs",
    "dataOutputAssociations",
    "outputSet",
    "eventDefinitions",
    "eventDefinitionReves"
})
@XmlSeeAlso({
    TStartEvent.class,
    TIntermediateCatchEvent.class,
    TBoundaryEvent.class
})
public abstract class TCatchEvent
    extends TEvent
{

    @XmlElement(name = "dataOutput")
    protected List<DataOutput> dataOutputs;
    @XmlElement(name = "dataOutputAssociation")
    protected List<DataOutputAssociation> dataOutputAssociations;
    protected OutputSet outputSet;
    @XmlElementRef(name = "eventDefinition", namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", type = JAXBElement.class, required = false)
    protected List<JAXBElement<? extends TEventDefinition>> eventDefinitions;
    @XmlElement(name = "eventDefinitionRef")
    protected List<QName> eventDefinitionReves;
    @XmlAttribute(name = "parallelMultiple")
    protected Boolean parallelMultiple;

    /**
     * Gets the value of the dataOutputs property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the dataOutputs property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDataOutputs().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link DataOutput }
     *
     *
     */
    public List<DataOutput> getDataOutputs() {
        if (dataOutputs == null) {
            dataOutputs = new ArrayList<DataOutput>();
        }
        return this.dataOutputs;
    }

    /**
     * Gets the value of the dataOutputAssociations property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the dataOutputAssociations property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDataOutputAssociations().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link DataOutputAssociation }
     *
     *
     */
    public List<DataOutputAssociation> getDataOutputAssociations() {
        if (dataOutputAssociations == null) {
            dataOutputAssociations = new ArrayList<DataOutputAssociation>();
        }
        return this.dataOutputAssociations;
    }

    /**
     * Gets the value of the outputSet property.
     *
     * @return
     *     possible object is
     *     {@link OutputSet }
     *
     */
    public OutputSet getOutputSet() {
        return outputSet;
    }

    /**
     * Sets the value of the outputSet property.
     *
     * @param value
     *     allowed object is
     *     {@link OutputSet }
     *
     */
    public void setOutputSet(OutputSet value) {
        this.outputSet = value;
    }

    /**
     * Gets the value of the eventDefinitions property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the eventDefinitions property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getEventDefinitions().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link JAXBElement }{@code <}{@link TEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TEscalationEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TTimerEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TCancelEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TSignalEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TLinkEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TConditionalEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TTerminateEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TMessageEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TErrorEventDefinition }{@code >}
     * {@link JAXBElement }{@code <}{@link TCompensateEventDefinition }{@code >}
     *
     *
     */
    public List<JAXBElement<? extends TEventDefinition>> getEventDefinitions() {
        if (eventDefinitions == null) {
            eventDefinitions = new ArrayList<JAXBElement<? extends TEventDefinition>>();
        }
        return this.eventDefinitions;
    }

    /**
     * Gets the value of the eventDefinitionReves property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the eventDefinitionReves property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getEventDefinitionReves().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link QName }
     *
     *
     */
    public List<QName> getEventDefinitionReves() {
        if (eventDefinitionReves == null) {
            eventDefinitionReves = new ArrayList<QName>();
        }
        return this.eventDefinitionReves;
    }

    /**
     * Gets the value of the parallelMultiple property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean getParallelMultiple() {
        if (parallelMultiple == null) {
            return false;
        } else {
            return parallelMultiple;
        }
    }

    /**
     * Sets the value of the parallelMultiple property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setParallelMultiple(Boolean value) {
        this.parallelMultiple = value;
    }

}


text:
// Copyright (c) Microsoft. All rights reserved.

#include "pch.h"
#include "Scenario1_CreateAFileInThePicturesLibrary.xaml.h"

using namespace SDKSample::FileAccess;

using namespace concurrency;
using namespace Windows::Storage;
using namespace Windows::UI::Xaml;

Scenario1::Scenario1() : rootPage(MainPage::Current)
{
    InitializeComponent();
    rootPage->Initialize();
    CreateFileButton->Click += ref new RoutedEventHandler(this, &Scenario1::CreateFileButton_Click);
}

void Scenario1::CreateFileButton_Click(Object^ sender, RoutedEventArgs^ e)
{
    create_task(KnownFolders::PicturesLibrary->CreateFileAsync(rootPage->Filename, CreationCollisionOption::ReplaceExisting)).then([this](StorageFile^ file)
    {
        rootPage->SampleFile = file;
        rootPage->NotifyUser("The file '" + file->Name + "' was created.", NotifyType::StatusMessage);
    });
}


text:
PHP Timezone Select
===================

An HTML select list and JSON file of PHP timezones. I've cleaned up a few things and added a few niceties as well.

Based on the timezone selection we did for [Snappy](http://www.besnappy.com).

MIT License

You're welcome!

## JSON Format
```json
{
   "AF":{
      "name":"Afghanistan",
      "timezones":{
         "Asia\/Kabul":{
            "abbr":"AFT",
            "offset":16200,
            "name":"Kabul"
         }
      }
   },
}
```

## Example Usage
You can use the HTML version as is (perhaps some javascript to set the default if needed) but if you need to do something custom you can use the json to have full control.

```php
/*
//This example uses Laravel Blade syntax
//In the controlloer do something like:

$timezones = json_decode(file_get_contents(path('storage').'data/timezones.json'));
return View::make('home.index')->with('timezones', $timezones);
*/

<select name="timezone" id="timezone">
	@foreach($timezones AS $countr_abbr=>$country)
		<optgroup label="{{ $country->name }}">
			@foreach($country->timezones AS $php_abbr=>$info)
				<option value="{{ $php_abbr }}">{{ $info->name }}   ({{ $info->abbr }})</option>
			@endforeach
		 </optgroup>
	 @endforeach
</select>
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<display-name>Archetype Created Web Application</display-name>

	<!-- Spring 容器启动监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 配置缓存清除监听器 处理由 JavaBean Introspector功能而引起的缓存泄露 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<!-- log4j Listener -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<!-- Spring 全局配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:appCtx-action.xml</param-value>
	</context-param>

</web-app>


text:
@interface LIALinkedInHttpClient ()
@property(nonatomic, strong) LIALinkedInApplication *application;
@property(nonatomic, weak) UIViewController *presentingViewController;
@end

@implementation LIALinkedInHttpClient

+ (LIALinkedInHttpClient *)clientForApplication:(LIALinkedInApplication *)application {
  return [self clientForApplication:application presentingViewController:nil];
}

+ (LIALinkedInHttpClient *)clientForApplication:(LIALinkedInApplication *)application presentingViewController:viewController {
  LIALinkedInHttpClient *client = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.linkedin.com"]];
  client.application = application;
  client.presentingViewController = viewController;
  return client;
}

- (id)initWithBaseURL:(NSURL *)url {
  self = [super initWithBaseURL:url];
  if (self) {
    [self setResponseSerializer:[AFJSONResponseSerializer serializer]];
  }
  return self;
}

- (BOOL)validToken {
  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

  if ([[NSDate date] timeIntervalSince1970] >= ([userDefaults doubleForKey:LINKEDIN_CREATION_KEY] + [userDefaults doubleForKey:LINKEDIN_EXPIRATION_KEY])) {
    return NO;
  }
  else {
    return YES;
  }
}

- (NSString *)accessToken {
  return [[NSUserDefaults standardUserDefaults] objectForKey:LINKEDIN_TOKEN_KEY];
}

- (void)getAccessToken:(NSString *)authorizationCode success:(void (^)(NSDictionary *))success failure:(void (^)(NSError *))failure {
  NSString *accessTokenUrl = @"/uas/oauth2/accessToken?grant_type=authorization_code&code=%@&redirect_uri=%@&client_id=%@&client_secret=%@";
  NSString *url = [NSString stringWithFormat:accessTokenUrl, authorizationCode, [self.application.redirectURL LIAEncode], self.application.clientId, self.application.clientSecret];

  [self POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *accessToken = [responseObject objectForKey:@"access_token"];
    NSTimeInterval expiration = [[responseObject objectForKey:@"expires_in"] doubleValue];

    // store credentials
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    [userDefaults setObject:accessToken forKey:LINKEDIN_TOKEN_KEY];
    [userDefaults setDouble:expiration forKey:LINKEDIN_EXPIRATION_KEY];
    [userDefaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:LINKEDIN_CREATION_KEY];
    [userDefaults synchronize];

    success(responseObject);
  }  failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    failure(error);
  }];

}

- (void)getAuthorizationCode:(void (^)(NSString *))success cancel:(void (^)(void))cancel failure:(void (^)(NSError *))failure {
  LIALinkedInAuthorizationViewController *authorizationViewController = [[LIALinkedInAuthorizationViewController alloc]
      initWithApplication:
          self.application
                  success:^(NSString *code) {
                    [self hideAuthenticateView];
                    if (success) {
                      success(code);
                    }
                  }
                   cancel:^{
                     [self hideAuthenticateView];
                     if (cancel) {
                       cancel();
                     }
                   } failure:^(NSError *error) {
        [self hideAuthenticateView];
        if (failure) {
          failure(error);
        }
      }];
  [self showAuthorizationView:authorizationViewController];
}

- (void)showAuthorizationView:(LIALinkedInAuthorizationViewController *)authorizationViewController {
  if (self.presentingViewController == nil)
    self.presentingViewController = [[UIApplication sharedApplication] keyWindow].rootViewController;

  UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:authorizationViewController];

  if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
    nc.modalPresentationStyle = UIModalPresentationFormSheet;
  }

  [self.presentingViewController presentViewController:nc animated:NO completion:nil];
}

- (void)hideAuthenticateView {
  [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
package com.spotify.sparkey;

import com.google.common.base.Charsets;

import java.io.*;

final class LogWriter {
  private final LogHeader header;
  private final File file;
  private final BlockOutput logStream;

  private LogWriter(File file, CompressionType compressionType, int compressionBlockSize) throws IOException {
    this.file = file;
    header = new LogHeader(compressionType, compressionBlockSize);
    header.write(file, false);
    logStream = setup(header, file);
  }

  private LogWriter(File file) throws IOException {
    this.file = file;
    if (!file.exists()) {
      throw new FileNotFoundException(file.getCanonicalPath());
    }
    header = LogHeader.read(file);
    logStream = setup(header, file);
  }

  File getFile() {
    return file;
  }

  private static BlockOutput setup(LogHeader header, File file) throws IOException {
    truncate(file, header.getDataEnd());
    FileOutputStream fileOutputStream = new FileOutputStream(file, true);
    FileDescriptor fd = fileOutputStream.getFD();
    OutputStream stream = new BufferedOutputStream(fileOutputStream, 1024 * 1024);
    return header.getCompressionType().createBlockOutput(fd, stream, header.getCompressionBlockSize(),
            header.getMaxEntriesPerBlock());
  }

  private static void truncate(File file, long size) throws IOException {
    RandomAccessFile rw = new RandomAccessFile(file, "rw");
    try {
      rw.setLength(size);
    } finally {
      rw.close();
    }
  }

  static LogWriter createNew(File file, CompressionType compressionType, int compressionBlockSize) throws IOException {
    return new LogWriter(file, compressionType, compressionBlockSize);
  }

  static LogWriter openExisting(File file) throws IOException {
    return new LogWriter(file);
  }

  void flush(boolean fsync) throws IOException {
    logStream.flush(fsync);
    writeHeader(fsync);
  }

  private void writeHeader(boolean fsync) throws IOException {
    header.setMaxEntriesPerBlock(logStream.getMaxEntriesPerBlock());
    header.setDataEnd(file.length());
    header.write(file, fsync);
  }

  void close(boolean fsync) throws IOException {
    logStream.close(fsync);
    writeHeader(fsync);
  }

  void put(String key, String value) throws IOException {
    put(key.getBytes(Charsets.UTF_8), value.getBytes(Charsets.UTF_8));
  }

  void put(byte[] key, byte[] value) throws IOException {
    logStream.put(key, key.length, value, value.length);
    header.put(key.length, value.length);
  }

  void put(byte[] key, InputStream value, long valueLen) throws IOException {
    logStream.put(key, key.length, value, valueLen);
    header.put(key.length, valueLen);
  }

  void delete(String key) throws IOException {
    delete(key.getBytes(Charsets.UTF_8));
  }

  void delete(byte[] key) throws IOException {
    if (key.length <= header.getMaxKeyLen()) {
      logStream.delete(key, key.length);
      header.delete(key.length);
    }
  }

}


text:
using System;
using ToKO.Generators;

namespace ToKO
{
    public class KOUtils
    {
        public static string WrapObservableArray(string arrayValue, bool observable)
        {
            if (observable)
            {
                return "ko.observableArray([" + arrayValue + "])";
            }
            return arrayValue;
        }

        public static string WrapObservable(string value, bool observable)
        {
            if (observable)
            {
                return "ko.observable(" + value + ")";
            }
            return value;
        }

        public static string ToJavascriptValue(dynamic value)
        {
            int dummyInt;
            double dummyDouble;
            if (value == null)
            {
                return "undefined";
            }

            if (value is KOModel)
            {
                return (value as KOModel).ToJavascript();
            }

            if (value is DateTime)
            {
                return String.Format("new Date({0}, {1}, {2}, {3}, {4}, {5}, {6})", value.Year, value.Month,
                    value.Day, value.Hour, value.Minute, value.Second, value.Millisecond);
            }

            if (int.TryParse(value.ToString(), out dummyInt) || double.TryParse(value.ToString(), out dummyDouble))
            {
                return value.ToString();
            }

            return "'" + value.ToString() + "'";
        }
    }
}


text:
package org.teavm.classlib.impl.unicode;

import java.util.Map;
import org.teavm.model.MethodReference;
import org.teavm.platform.metadata.*;

public class LikelySubtagsMetadataGenerator implements MetadataGenerator {
    @Override
    public Resource generateMetadata(MetadataGeneratorContext context, MethodReference method) {
        CLDRReader reader = context.getService(CLDRReader.class);
        ResourceMap<StringResource> map = context.createResourceMap();
        for (Map.Entry<String, String> entry : reader.getLikelySubtags().entrySet()) {
            StringResource subtagRes = context.createResource(StringResource.class);
            subtagRes.setValue(entry.getValue());
            map.put(entry.getKey(), subtagRes);
        }
        return map;
    }
}


text:
function isEncrypted(file) {
	/***************************************************************************
	Version 1.0
	edited by Justin San Agustin: 12/24/2016, 2:29:46 AM
	//
	Checks if passFile contents are encrypted.
		If it is encrypted, the contents should end with "="
	Returns true/false
	//
	Dependencies:
		None
	***************************************************************************/
	var fso      = new ActiveXObject("Scripting.FileSystemObject");
	var passFile = fso.OpenTextFile(file);
	var pass     = passFile.ReadAll();
	passFile.Close();
	var charCount      = pass.length; //Gets # of char in the file
	var markerPosition = pass.indexOf("=") + 1; //Finds where "=", but count starts at 0
	if (markerPosition == charCount) { return true; }
	else { return false; }
}


text:
#pragma once

/**
 *  Set up namespace
 */
namespace AMQP {

/**
 *  Class definition
 */
class Message : public Envelope
{
protected:
    /**
     *  The exchange to which it was originally published
     *  @var    string
     */
    std::string _exchange;

    /**
     *  The routing key that was originally used
     *  @var    string
     */
    std::string _routingKey;

protected:
    /**
     *  The constructor is protected to ensure that endusers can not
     *  instantiate a message
     *  @param  exchange
     *  @param  routingKey
     */
    Message(const std::string &exchange, const std::string &routingKey) :
        Envelope(nullptr, 0), _exchange(exchange), _routingKey(routingKey)
    {}

public:

    /**
     *  Copy constructor
     *
     *  @param  message the message to copy
     */
    Message(const Message &message) :
        Envelope(message),
        _exchange(message._exchange),
        _routingKey(message._routingKey)
    {}

    /**
     *  Move constructor
     *
     *  @param  message the message to move
     */
    Message(Message &&message) :
        Envelope(std::move(message)),
        _exchange(std::move(message._exchange)),
        _routingKey(std::move(message._routingKey))
    {}

    /**
     *  Destructor
     */
    virtual ~Message() {}

    /**
     *  Assignment operator
     *
     *  @param  message the message to copy
     *  @return same object for chaining
     */
    Message &operator=(const Message &message)
    {
        // call the base assignment
        Envelope::operator=(message);

        // move the exchange and routing key
        _exchange   = message._exchange;
        _routingKey = message._routingKey;

        // allow chaining
        return *this;
    }

    /**
     *  Move assignment operator
     *
     *  @param  message the message to move
     *  @return same object for chaining
     */
    Message &operator=(Message &&message)
    {
        // call the base assignment
        Envelope::operator=(std::move(message));

        // move the exchange and routing key
        _exchange   = std::move(message._exchange);
        _routingKey = std::move(message._routingKey);

        // allow chaining
        return *this;
    }

    /**
     *  The exchange to which it was originally published
     *  @var    string
     */
    const std::string &exchange() const
    {
        return _exchange;
    }

    /**
     *  The routing key that was originally used
     *  @var    string
     */
    const std::string &routingKey() const
    {
        return _routingKey;
    }
};

/**
 *  End of namespace
 */
}


text:
package pattern.proxy;

interface IStudent {

  int getGrade();
  void setGrade(int grade);

  String getProfile();

}


text:
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Boost.MultiArray Library
//  Authors: Ronald Garcia
//           Jeremy Siek
//           Andrew Lumsdaine
//  See http://www.boost.org/libs/multi_array for documentation.

#ifndef COLLECTION_CONCEPT_RG103101_HPP
#define COLLECTION_CONCEPT_RG103101_HPP

#include "boost/concept_check.hpp"

namespace boost {
namespace detail {
namespace multi_array {

  //===========================================================================
  // Collection Concept

  template <class Collection>
  struct CollectionConcept
  {
    typedef typename Collection::value_type value_type;
    typedef typename Collection::iterator iterator;
    typedef typename Collection::const_iterator const_iterator;
    typedef typename Collection::reference reference;
    typedef typename Collection::const_reference const_reference;
    // typedef typename Collection::pointer pointer;
    typedef typename Collection::difference_type difference_type;
    typedef typename Collection::size_type size_type;

    void constraints() {
      boost::function_requires<boost::InputIteratorConcept<iterator> >();
      boost::function_requires<boost::InputIteratorConcept<const_iterator> >();
      boost::function_requires<boost::CopyConstructibleConcept<value_type> >();
      const_constraints(c);
      i = c.begin();
      i = c.end();
      c.swap(c);
    }
    void const_constraints(const Collection& c) {
      ci = c.begin();
      ci = c.end();
      n = c.size();
      b = c.empty();
    }
    Collection c;
    bool b;
    iterator i;
    const_iterator ci;
    size_type n;
  };

}
}
}
#endif // COLLECTION_CONCEPT_RG103101_HPP