text:
'use strict';
/* jshint node: true */
/* jshint esnext: true */
/* global describe, beforeEach, beforeAll, afterAll, spyOn, it, expect, fail */

describe('registration', () => {

  const registration = require('../../service/registration');
  const participants = require('../../service/participants');
  const tshirts = require('../../service/tshirts');
  const participant = require('../../domain/participant');
  const couponcode = require('../../service/couponcodes');

  const mails = require('../../service/util/mails');
  const helper = require('../journeyHelper');

  let originalRegistrationStatus;
  let startNr = 30;

  const aParticipant = participant.from({
    firstname: 'Hertha',
    lastname: 'Mustermann',
    email: 'h.mustermann@example.com',
    category: 'Unicorn',
    birthyear: 1980,
    visibility: 'yes',
    discount: 'no',
    team: 'Crazy runners'
  }).withSecureId('some_secure_id');

  beforeAll((done) => {
      helper.setupDbConnection().then(() => {
        registration.isClosed().then(isClosed => {
            originalRegistrationStatus = isClosed;
            if (isClosed) {
                registration.reopen().then(() => {
                    done();
                });
            } else {
                done();
            }
        });
    });
  });

  afterAll((done) => {
    if (!originalRegistrationStatus) {
      registration.reopen().then(() => {
        helper.closeDbConnection(done);
      }).catch(() => {
          helper.closeDbConnection(done);
      });
    } else {
      helper.closeDbConnection(done);
    }
  });

  describe('start()', () => {
    it('should save the participant and send confirmation email', (done) => {
      spyOn(participants, 'save').and.callThrough();
      spyOn(participants, 'markPayed').and.callThrough();
      spyOn(participants, 'choseStartBlock').and.callThrough();
      spyOn(mails, 'sendEmail');
      spyOn(tshirts, 'addFor');

      const p = participant.from({
        firstname: 'Hertha',
        lastname: 'Mustermann',
        email: 'h.mustermann@example.com',
        category: 'Unicorn',
        birthyear: 1980,
        visibility: 'yes',
        discount: 'no',
        team: 'Crazy runners'
      });

      registration.start(p)
        .then((result) => {
          expect(participants.save).toHaveBeenCalled();

          let participant = participants.save.calls.mostRecent().args[0];
          expect(participant.firstname).toBe(p.firstname);
          expect(participant.paymentToken).toBe(result.token);
          expect(participant.secureID).toBe(result.secureid);
          expect(participant.start_number).toBe(result.startnr);
          expect(participant.start_block).toBeDefined();

          expect(participants.markPayed).not.toHaveBeenCalled();

          expect(mails.sendEmail).toHaveBeenCalled();

          let participantsEmail = mails.sendEmail.calls.mostRecent().args[0];
          expect(participantsEmail).toBe(p.email);

          let subject = mails.sendEmail.calls.mostRecent().args[1];
          expect(subject).toBe('Lauf Gegen Rechts: Registrierung erfolgreich');

          let content = mails.sendEmail.calls.mostRecent().args[2];
          expect(content).toMatch(/Danke/);
          expect(content).toMatch(/Bitte überweise den Betrag/);

          expect(tshirts.addFor).not.toHaveBeenCalled();
          done();
        })
        .catch(done.fail);
    });

    it('should mark the participant as payed if their amount is 0 and send the matching email', (done) => {
      spyOn(participants, 'save').and.callThrough();
      spyOn(couponcode, 'validateCode').and.callThrough();
      spyOn(participants, 'markPayed').and.callThrough();
      spyOn(couponcode, 'randomString').and.returnValue('UNIQUECODE2');
      spyOn(mails, 'sendEmail');
      spyOn(tshirts, 'addFor');

      const p = participant.from({
        firstname: 'Hertha',
        lastname: 'Mustermann',
        email: 'h.mustermann@example.com',
        category: 'Unicorn',
        birthyear: 1980,
        visibility: 'yes',
        discount: 'free',
        couponcode: 'UNIQUECODE2',
        team: 'Crazy runners'
      });

      couponcode.create().then(() => {
        registration.start(p)
          .then((result) => {
            expect(participants.save).toHaveBeenCalled();

            let participant = participants.save.calls.mostRecent().args[0];
            expect(participant.firstname).toBe(p.firstname);
            expect(participant.paymentToken).toBe(result.token);
            expect(participant.secureID).toBe(result.secureid);
            expect(participant.start_number).toBe(result.startnr);

            expect(participants.markPayed).toHaveBeenCalled();

            expect(mails.sendEmail).toHaveBeenCalled();

            let participantsEmail = mails.sendEmail.calls.mostRecent().args[0];
            expect(participantsEmail).toBe(p.email);

            let subject = mails.sendEmail.calls.mostRecent().args[1];
            expect(subject).toBe('Lauf Gegen Rechts: Registrierung erfolgreich');

            let content = mails.sendEmail.calls.mostRecent().args[2];
            expect(content).toMatch(/Danke/);
            expect(content).not.toMatch(/Bitte überweise den Betrag/);

            expect(tshirts.addFor).not.toHaveBeenCalled();
            done();
          })
          .catch(done.fail);
      }).catch(done.fail);
    });

    it('should call addFor if one ordered', (done) => {
      spyOn(tshirts, 'addFor');

      const pWithShirt = participant.from({
        firstname: 'Hertha',
        lastname: 'Mustermann',
        email: 'h.mustermann@example.com',
        birthyear: 1980,
        category: 'Horse',
        visibility: 'yes',
        discount: 'no',
        shirt: 'yes',
        size: 'XS',
        model: 'Crazy cool fit'
      });

      registration.start(pWithShirt)
        .then(() => {
          expect(tshirts.addFor).toHaveBeenCalled();
          done();
        })
        .catch(done.fail);
    });

    it('should not mark as payed if coupon user ordered a shirt', (done) => {
      spyOn(tshirts, 'addFor');
      spyOn(participants, 'markPayed');
      spyOn(couponcode, 'randomString').and.returnValue('UNIQUECODE1');

      const pWithShirt = participant.from({
        firstname: 'Hertha',
        lastname: 'Mustermann',
        email: 'h.mustermann@example.com',
        birthyear: 1980,
        category: 'Horse',
        visibility: 'yes',
        discount: 'free',
        couponcode: 'UNIQUECODE1',
        shirt: 'yes',
        size: 'XS',
        model: 'Crazy cool fit'
      });

      couponcode.create().then(() => {
        registration.start(pWithShirt)
          .then(() => {
            expect(participants.markPayed).not.toHaveBeenCalled();
            expect(tshirts.addFor).toHaveBeenCalled();
            done();
          }).catch(done.fail);
      }).catch(done.fail);
    });
  });

  describe('confirm()', () => {
    it('should mark the participant as payed and send a confirmation mail which includes the edit link', (done) => {
      spyOn(participants, 'markPayed').and.callThrough();
      spyOn(mails, 'sendEmail');

      participants.save(aParticipant.withToken('token x').withStartNr(startNr++))
        .then(function (participantId) {
          registration.confirm(participantId)
            .then(() => {
              expect(participants.markPayed).toHaveBeenCalledWith(participantId);

              expect(mails.sendEmail).toHaveBeenCalled();
              let partcipantsEmail = mails.sendEmail.calls.mostRecent().args[0];
              expect(partcipantsEmail).toBe(aParticipant.email);
              let subject = mails.sendEmail.calls.mostRecent().args[1];
              expect(subject).toBe('Lauf gegen Rechts: Zahlung erhalten');
              let content = mails.sendEmail.calls.mostRecent().args[2];
              expect(content).toMatch(aParticipant.firstname);
              expect(content).toMatch(/eingegangen/);
              expect(content).toMatch('some_secure_id');

              done();
            })
            .catch(done.fail);
        }).catch(done.fail);
    });

    it('should give error if ID is invalid', (done) => {
      let wrongId = '999';

      participants.save(aParticipant.withToken('token y').withStartNr(startNr++))
        .then(() => {
          registration.confirm(wrongId)
            .catch(() => {
              done();
            });
        }).catch(done.fail);
    });
  });

  it('should close the registration', (done) => {
    registration.close()
      .then(() => {
        registration.isClosed()
          .then((isClosed) => {
            expect(isClosed).toEqual(true);
            done();
          })
          .catch(done.fail);
      })
      .catch(done.fail);
  });
});


text:
using MatterHackers.Agg;
using MatterHackers.VectorMath;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace MatterHackers.GCodeVisualizer
{
    public abstract class GCodeFile
	{
		private static readonly Vector4 MaxAccelerationMmPerS2 = new Vector4(1000, 1000, 100, 5000);
		private static readonly Vector4 MaxVelocityMmPerS = new Vector4(500, 500, 5, 25);
		private static readonly Vector4 VelocitySameAsStopMmPerS = new Vector4(8, 8, .4, 5);

#if __ANDROID__
		protected const int Max32BitFileSize = 10000000; // 10 megs
#else
		protected const int Max32BitFileSize = 100000000; // 100 megs
#endif

		public static void AssertDebugNotDefined()
		{
#if DEBUG
			throw new Exception("DEBUG is defined and should not be!");
#endif
		}

		#region Abstract Functions
		// the number of lines in the file
		public abstract int LineCount { get; }

		public abstract int NumChangesInZ { get; }
		public abstract double TotalSecondsInPrint { get; }

		public abstract void Clear();

		public abstract RectangleDouble GetBounds();

		public abstract double GetFilamentCubicMm(double filamentDiameter);

		public abstract double GetFilamentDiameter();

		public abstract double GetFilamentUsedMm(double filamentDiameter);

		public abstract double GetFilamentWeightGrams(double filamentDiameterMm, double density);

		public abstract double GetFirstLayerHeight();

		public abstract int GetInstructionIndexAtLayer(int layerIndex);

		public abstract double GetLayerHeight();

		public abstract int GetLayerIndex(int instructionIndex);

		public abstract Vector2 GetWeightedCenter();

		public abstract PrinterMachineInstruction Instruction(int i);

		public abstract bool IsExtruding(int instructionIndexToCheck);
		public abstract double PercentComplete(int instructionIndex);

		public abstract double Ratio0to1IntoContainedLayer(int instructionIndex);
		#endregion Abstract Functions

		#region Static Functions

		public static int CalculateChecksum(string commandToGetChecksumFor)
		{
			int checksum = 0;
			if (commandToGetChecksumFor.Length > 0)
			{
				checksum = commandToGetChecksumFor[0];
				for (int i = 1; i < commandToGetChecksumFor.Length; i++)
				{
					checksum ^= commandToGetChecksumFor[i];
				}
			}
			return checksum;
		}

		public static bool FileTooBigToLoad(string fileName)
		{
			if (File.Exists(fileName)
				&& RunningIn32Bit())
			{
				FileInfo info = new FileInfo(fileName);
				// Let's make sure we can load a file this big
				if (info.Length > Max32BitFileSize)
				{
					// It is too big to load
					return true;
				}
			}

			return false;
		}

		public static bool GetFirstNumberAfter(string stringToCheckAfter, string stringWithNumber, ref double readValue, int startIndex = 0)
		{
			int stringPos = stringWithNumber.IndexOf(stringToCheckAfter, startIndex);
			if (stringPos != -1)
			{
				stringPos += stringToCheckAfter.Length;
				readValue = agg_basics.ParseDouble(stringWithNumber, ref stringPos, true);

				return true;
			}

			return false;
		}

		public static bool GetFirstStringAfter(string stringToCheckAfter, string fullStringToLookIn, string separatorString, ref string nextString, int startIndex = 0)
		{
			int stringPos = fullStringToLookIn.IndexOf(stringToCheckAfter, startIndex);
			if (stringPos != -1)
			{
				int separatorPos = fullStringToLookIn.IndexOf(separatorString, stringPos);
				if (separatorPos != -1)
				{
					nextString = fullStringToLookIn.Substring(stringPos + stringToCheckAfter.Length, separatorPos - (stringPos + stringToCheckAfter.Length));
					return true;
				}
			}

			return false;
		}

		public static GCodeFile Load(string fileName)
		{
			if (FileTooBigToLoad(fileName))
			{
				return new GCodeFileStreamed(fileName);
			}
			else
			{
				return new GCodeFileLoaded(fileName);
			}
		}

		public static string ReplaceNumberAfter(char charToReplaceAfter, string stringWithNumber, double numberToPutIn)
		{
			int charPos = stringWithNumber.IndexOf(charToReplaceAfter);
			if (charPos != -1)
			{
				int spacePos = stringWithNumber.IndexOf(" ", charPos);
				if (spacePos == -1)
				{
					string newString = string.Format("{0}{1:0.#####}", stringWithNumber.Substring(0, charPos + 1), numberToPutIn);
					return newString;
				}
				else
				{
					string newString = string.Format("{0}{1:0.#####}{2}", stringWithNumber.Substring(0, charPos + 1), numberToPutIn, stringWithNumber.Substring(spacePos));
					return newString;
				}
			}

			return stringWithNumber;
		}

		protected static double GetSecondsThisLine(Vector3 deltaPositionThisLine, double deltaEPositionThisLine, double feedRateMmPerMin)
		{
			double startingVelocityMmPerS = VelocitySameAsStopMmPerS.x;
			double endingVelocityMmPerS = VelocitySameAsStopMmPerS.x;
			double maxVelocityMmPerS = Math.Min(feedRateMmPerMin / 60, MaxVelocityMmPerS.x);
			double acceleration = MaxAccelerationMmPerS2.x;
			double lengthOfThisMoveMm = Math.Max(deltaPositionThisLine.Length, deltaEPositionThisLine);

			double distanceToMaxVelocity = GetDistanceToReachEndingVelocity(startingVelocityMmPerS, maxVelocityMmPerS, acceleration);
			if (distanceToMaxVelocity <= lengthOfThisMoveMm / 2)
			{
				// we will reach max velocity then run at it and then decelerate
				double accelerationTime = GetTimeToAccelerateDistance(startingVelocityMmPerS, distanceToMaxVelocity, acceleration) * 2;
				double runningTime = (lengthOfThisMoveMm - (distanceToMaxVelocity * 2)) / maxVelocityMmPerS;
				return accelerationTime + runningTime;
			}
			else
			{
				// we will accelerate to the center then decelerate
				double accelerationTime = GetTimeToAccelerateDistance(startingVelocityMmPerS, lengthOfThisMoveMm / 2, acceleration) * 2;
				return accelerationTime;
			}
		}

		private static double GetDistanceToReachEndingVelocity(double startingVelocityMmPerS, double endingVelocityMmPerS, double accelerationMmPerS2)
		{
			double endingVelocityMmPerS2 = endingVelocityMmPerS * endingVelocityMmPerS;
			double startingVelocityMmPerS2 = startingVelocityMmPerS * startingVelocityMmPerS;
			return (endingVelocityMmPerS2 - startingVelocityMmPerS2) / (2.0 * accelerationMmPerS2);
		}

		private static double GetTimeToAccelerateDistance(double startingVelocityMmPerS, double distanceMm, double accelerationMmPerS2)
		{
			// d = vi * t + .5 * a * t^2;
			// t = (√(vi^2+2ad)-vi)/a
			double startingVelocityMmPerS2 = startingVelocityMmPerS * startingVelocityMmPerS;
			double distanceAcceleration2 = 2 * accelerationMmPerS2 * distanceMm;
			return (Math.Sqrt(startingVelocityMmPerS2 + distanceAcceleration2) - startingVelocityMmPerS) / accelerationMmPerS2;
		}

		private static bool RunningIn32Bit()
		{
            if (IntPtr.Size == 4)
            {
                return true;
            }

            return false;
        }
        #endregion Static Functions
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { extendObservable } from 'mobx';

export default function initAttributes(options = {}) {
	let { model } = options;
  extendObservable(model, model.constructor.attributes);
}


text:
Typus User Guide
================

**Typus** is a control panel for `Rails`_ applications to allow
trusted users edit structured content.

It's not a CMS with a full working system but it provides a part of the system:
authentication, permissions and basic look and feel for your websites control
panel. So using `Rails`_ with **Typus** lets you concentrate on your
application instead of the bits to manage the system.

**Typus** is the "old latin" word for **type** which stands for:

    A category of people or things having common characteristics.

Key Features
------------

* Built-in Authentication and Access Control Lists.
* CRUD and custom actions for your models on a clean interface.
* Customizable and extensible templates.
* Integrated `paperclip`_ and `dragonfly`_ attachments viewer.
* Supports Rails 4.0 and 3.2.
* Tested with **SQLite3**, **MySQL** and **PostgreSQL**.
* **MIT License**, the same as `Rails`_.

.. _See available translations: https://github.com/typus/typus/tree/master/config/locales
.. _paperclip: http://rubygems.org/gems/paperclip
.. _dragonfly: http://rubygems.org/gems/dragonfly

Support
-------

You can directly participate in the support and development of **Typus**,
including new features, by hiring our team to work on your project. We offer
customization services for modules and extensions for a fee.

Send your inquiries to contact@typuscmf.com.

Installation
------------

Before installing make sure your application does not have any controller
under ``controllers/admin`` as all **Typus** controllers will be generated
there.

To install **Typus**, edit the application ``Gemfile`` and add:

.. code-block:: ruby

  gem 'typus'

  # Bundle edge Typus instead:
  # gem 'typus', github: 'typus/typus'

Install the **RubyGem** using ``bundler``:

.. code-block:: bash

  bundle install

**Typus** expects to have models to manage, so run the generator in order to
generate the required configuration files:

.. code-block:: bash

  rails generate typus

Start the application server, go to http://0.0.0.0:3000/admin and follow the
instructions.

By default **Typus** will not enable any authentication mechanism. If you want
to add ``session`` authentication you need to run a generator and migrate your
application database:

.. code-block:: bash

  rails generate typus:migration
  rake db:migrate

This generator creates a new model, ``AdminUser`` and adds some settings which
will be stored under ``config/typus`` folder. You can see some options of this
generator running the following command:

.. code-block:: bash

  rails generate typus:migration -h

If you want to customize views you can copy default views to your application:

.. code-block:: bash

  rails generate typus:views

To see a list of **Typus** related tasks run:

.. code-block:: bash

  rake -T typus

Configuration
-------------

.. toctree::
  :maxdepth: 1

  configuration/initializers
  configuration/resources
  configuration/resource
  configuration/roles
  customization/selectors
  customization/custom_css_and_js

Customization
-------------

.. toctree::
  :maxdepth: 1
  :glob:

  customization/*

Recipes
-------

.. toctree::
  :maxdepth: 1
  :glob:

  recipes/*

Misc
----

.. toctree::
  :maxdepth: 1

  usage
  upgrade

Contribute
----------

All of our hard work and help/support is free. We do have expenses to pay for
this project and your donations do allow us to spend more time building and
supporting the project.

Some interesting ways to contribute to the project:

* **Fork the project** - Fork the project on `GitHub`_ and make it better.
* **Tell everybody about Typus** - Let us know and we'll link back to you as well.
* **Hire us** to work on your next project - we build websites large and small.

.. _GitHub: https://github.com/typus/typus/
.. _Rails: http://rubyonrails.org/

Credits
=======

Somehow involved in the project:

* `Yukihiro "matz" Matsumoto`_ creator of `Ruby`_, in my opinion, the most
  beautiful programming language.
* `David Heinemeier Hansson`_ for creating `Rails`_.
* `Django Admin`_ who inspired part of the  development, specially templates
  rendering and user interface.
* Our `Contributors`_.

.. _Yukihiro "matz" Matsumoto: http://www.rubyist.net/~matz
.. _Ruby: http://ruby-lang.org/
.. _David Heinemeier Hansson: http://loudthinking.com/
.. _Rails: http://rubyonrails.org/
.. _Django Admin: http://www.djangoproject.com/
.. _Contributors: http://github.com/typus/typus/contributors

MIT License
===========

.. code-block:: none

  Copyright (c) 2007-2015 Francesc Esplugas Marti

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package upload

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
)

type testPath struct {
	Path        string
	ContentType string
	Valid       bool
}

var (
	testTmp, err        = ioutil.TempDir("", "artifacts-test-upload")
	testArtifactPathDir = filepath.Join(testTmp, "artifact")
	testArtifactPaths   = []*testPath{
		&testPath{
			Path:        filepath.Join(testArtifactPathDir, "foo"),
			ContentType: "text/plain; charset=utf-8",
			Valid:       true,
		},
		&testPath{
			Path:        filepath.Join(testArtifactPathDir, "foo.csv"),
			ContentType: "text/csv; charset=utf-8",
			Valid:       true,
		},
		&testPath{
			Path:        filepath.Join(testArtifactPathDir, "nonexistent"),
			ContentType: "application/octet-stream",
			Valid:       false,
		},
		&testPath{
			Path:        filepath.Join(testArtifactPathDir, "unreadable"),
			ContentType: "application/octet-stream",
			Valid:       false,
		},
	}
)

func init() {
	os.Clearenv()

	if err != nil {
		log.Panicf("game over: %v\n", err)
	}

	err = os.MkdirAll(testArtifactPathDir, 0755)
	if err != nil {
		log.Panicf("game over: %v\n", err)
	}

	for _, p := range testArtifactPaths {
		if filepath.Base(p.Path) == "nonexistent" {
			continue
		}

		fd, err := os.Create(p.Path)
		if err != nil {
			log.Panicf("game over: %v\n", err)
		}

		defer fd.Close()

		for i := 0; i < 512; i++ {
			fmt.Fprintf(fd, "something\n")
		}

		if filepath.Base(p.Path) == "unreadable" {
			fd.Chmod(0000)
		}
	}
}

func setenvs(e map[string]string) error {
	for k, v := range e {
		err := os.Setenv(k, v)
		if err != nil {
			return err
		}
	}

	return nil
}


text:
package org.kie.server.api;

public class Version {

    private final int    major;
    private final int    minor;
    private final int    revision;
    private final String classifier;

    public Version(int major, int minor, int revision, String classifier) {
        super();
        this.major = major;
        this.minor = minor;
        this.revision = revision;
        this.classifier = classifier;
    }

    public int getMajor() {
        return major;
    }

    public int getMinor() {
        return minor;
    }

    public int getRevision() {
        return revision;
    }

    public String getClassifier() {
        return classifier;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((classifier == null) ? 0 : classifier.hashCode());
        result = prime * result + major;
        result = prime * result + minor;
        result = prime * result + revision;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Version other = (Version) obj;
        if (classifier == null) {
            if (other.classifier != null)
                return false;
        } else if (!classifier.equals(other.classifier))
            return false;
        if (major != other.major)
            return false;
        if (minor != other.minor)
            return false;
        if (revision != other.revision)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return major + "." + minor + "." + revision + (classifier != null ? classifier : "");
    }

}


text:
using System;
using System.Collections;
using System.IO;
using System.Text;
using MySql.Data.Common;
using System.Data;
using MySql.Data.MySqlClient.Properties;
using System.Collections.Generic;

namespace MySql.Data.MySqlClient
{
  internal abstract class Statement
  {
    protected MySqlCommand command;
    protected string commandText;
    private List<MySqlPacket> buffers;

    private Statement(MySqlCommand cmd)
    {
      command = cmd;
      buffers = new List<MySqlPacket>();
    }

    public Statement(MySqlCommand cmd, string text)
      : this(cmd)
    {
      commandText = text;
    }

    #region Properties

    public virtual string ResolvedCommandText
    {
      get { return commandText; }
    }

    protected Driver Driver
    {
      get { return command.Connection.driver; }
    }

    protected MySqlConnection Connection
    {
      get { return command.Connection; }
    }

    protected MySqlParameterCollection Parameters
    {
      get { return command.Parameters; }
    }

    #endregion

    public virtual void Close(MySqlDataReader reader)
    {
    }

    public virtual void Resolve(bool preparing)
    {
    }

    public virtual void Execute()
    {
      // we keep a reference to this until we are done
      BindParameters();
      ExecuteNext();
    }

    public virtual bool ExecuteNext()
    {
      if (buffers.Count == 0)
        return false;

      MySqlPacket packet = (MySqlPacket)buffers[0];
      //MemoryStream ms = stream.InternalBuffer;
      Driver.SendQuery(packet);
      buffers.RemoveAt(0);
      return true;
    }

    protected virtual void BindParameters()
    {
      MySqlParameterCollection parameters = command.Parameters;
      int index = 0;

      while (true)
      {
        InternalBindParameters(ResolvedCommandText, parameters, null);

        // if we are not batching, then we are done.  This is only really relevant the
        // first time through
        if (command.Batch == null) return;
        while (index < command.Batch.Count)
        {
          MySqlCommand batchedCmd = command.Batch[index++];
          MySqlPacket packet = (MySqlPacket)buffers[buffers.Count - 1];

          // now we make a guess if this statement will fit in our current stream
          long estimatedCmdSize = batchedCmd.EstimatedSize();
          if (((packet.Length - 4) + estimatedCmdSize) > Connection.driver.MaxPacketSize)
          {
            // it won't, so we setup to start a new run from here
            parameters = batchedCmd.Parameters;
            break;
          }

          // looks like we might have room for it so we remember the current end of the stream
          buffers.RemoveAt(buffers.Count - 1);
          //long originalLength = packet.Length - 4;

          // and attempt to stream the next command
          string text = ResolvedCommandText;
          if (text.StartsWith("(", StringComparison.Ordinal))
            packet.WriteStringNoNull(", ");
          else
            packet.WriteStringNoNull("; ");
          InternalBindParameters(text, batchedCmd.Parameters, packet);
          if ((packet.Length - 4) > Connection.driver.MaxPacketSize)
          {
            //TODO
            //stream.InternalBuffer.SetLength(originalLength);
            parameters = batchedCmd.Parameters;
            break;
          }
        }
        if (index == command.Batch.Count)
          return;
      }
    }

    private void InternalBindParameters(string sql, MySqlParameterCollection parameters,
        MySqlPacket packet)
    {
      bool sqlServerMode = command.Connection.Settings.SqlServerMode;

      if (packet == null)
      {
        packet = new MySqlPacket(Driver.Encoding);
        packet.Version = Driver.Version;
        packet.WriteByte(0);
      }

      MySqlTokenizer tokenizer = new MySqlTokenizer(sql);
      tokenizer.ReturnComments = true;
      tokenizer.SqlServerMode = sqlServerMode;

      int pos = 0;
      string token = tokenizer.NextToken();
      int parameterCount = 0;
      while (token != null)
      {
        // serialize everything that came before the token (i.e. whitespace)
        packet.WriteStringNoNull(sql.Substring(pos, tokenizer.StartIndex - pos));
        pos = tokenizer.StopIndex;
        if (MySqlTokenizer.IsParameter(token))
        {
          if ((!parameters.containsUnnamedParameters && token.Length == 1 && parameterCount > 0) || parameters.containsUnnamedParameters && token.Length > 1)
            throw new MySqlException(Resources.MixedParameterNamingNotAllowed);

          parameters.containsUnnamedParameters = token.Length == 1;
          if (SerializeParameter(parameters, packet, token, parameterCount))
            token = null;
          parameterCount++;
        }
        if (token != null)
        {
          if (sqlServerMode && tokenizer.Quoted && token.StartsWith("[", StringComparison.Ordinal))
            token = String.Format("`{0}`", token.Substring(1, token.Length - 2));
          packet.WriteStringNoNull(token);
        }
        token = tokenizer.NextToken();
      }
      buffers.Add(packet);
    }

    protected virtual bool ShouldIgnoreMissingParameter(string parameterName)
    {
      if (Connection.Settings.AllowUserVariables)
        return true;
      if (parameterName.StartsWith("@" + StoredProcedure.ParameterPrefix, StringComparison.OrdinalIgnoreCase))
        return true;
      if (parameterName.Length > 1 &&
          (parameterName[1] == '`' || parameterName[1] == '\''))
        return true;
      return false;
    }

    /// <summary>
    /// Serializes the given parameter to the given memory stream
    /// </summary>
    /// <remarks>
    /// <para>This method is called by PrepareSqlBuffers to convert the given
    /// parameter to bytes and write those bytes to the given memory stream.
    /// </para>
    /// </remarks>
    /// <returns>True if the parameter was successfully serialized, false otherwise.</returns>
    private bool SerializeParameter(MySqlParameterCollection parameters,
                                    MySqlPacket packet, string parmName, int parameterIndex)
    {
      MySqlParameter parameter = null;

      if (!parameters.containsUnnamedParameters)
        parameter = parameters.GetParameterFlexible(parmName, false);
      else
      {
        if (parameterIndex <= parameters.Count)
          parameter = parameters[parameterIndex];
        else
          throw new MySqlException(Resources.ParameterIndexNotFound);
      }

      if (parameter == null)
      {
        // if we are allowing user variables and the parameter name starts with @
        // then we can't throw an exception
        if (parmName.StartsWith("@", StringComparison.Ordinal) && ShouldIgnoreMissingParameter(parmName))
          return false;
        throw new MySqlException(
            String.Format(Resources.ParameterMustBeDefined, parmName));
      }
      parameter.Serialize(packet, false, Connection.Settings);
      return true;
    }
  }
}


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

<title>Uses of Class input.Participant</title>
<meta name="date" content="2016-03-25">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
input.Participant

Packages that use Participant

Package
Description

input

Provides the classes necessary to parse and read a CSV input file,
 check the file for syntax or formatting errors, and generate a
 ScheduleInformation object representing the data collected from
 the input file.

schedule_structure

Provides the classes necessary to define the high-level
 structure of a Schedule.

scheduling_algorithm

Provides the classes necessary to generate a Schedule from
 ScheduleInformation gathered from an input file.

Uses of Participant in input

Fields in input with type parameters of type Participant

Modifier and Type
Field and Description

private java.util.ArrayList<Participant>
Participant.badPartners

A list of participants that this participant does not
 want to work with for team events

private java.util.ArrayList<Participant>
Participant.goodPartners

A list of participants that this participant prefers
 to work with for team events

private java.util.ArrayList<Participant>
ScheduleInformation.participants

A list of all of the students in the class

private java.util.ArrayList<Participant>
InputHandler.participants

List of participants

Methods in input that return Participant

Modifier and Type
Method and Description

private Participant
InputHandler.lookupParticipant(java.lang.String name,
                 java.util.ArrayList<Participant> par)

Methods in input that return types with arguments of type Participant

Modifier and Type
Method and Description

java.util.ArrayList<Participant>
Participant.getBadPartners()

Gets the list of participants that this participant does not
 want to work with for team events.

java.util.ArrayList<Participant>
Participant.getGoodPartners()

Gets the list of participants that this participant wants
 to work with on team events.

java.util.ArrayList<Participant>
ScheduleInformation.getParticipants()

Gets the list of participants contained in the schedule
 information

private java.util.ArrayList<Participant>
InputHandler.parseParticipants()

Extracts participants from CSV file

Methods in input with parameters of type Participant

Modifier and Type
Method and Description

void
Participant.addBadPartner(Participant badPartner)

Adds a participant to the list of participants that this
 participant would prefer not to work with for team
 events.

void
Participant.addGoodPartner(Participant goodPartner)

Adds a participant to the list of participants that this
 participant would prefer to work with for team events.

void
ScheduleInformation.addParticipant(Participant participant)

Adds a participant to the list of participants

Method parameters in input with type arguments of type Participant

Modifier and Type
Method and Description

private Participant
InputHandler.lookupParticipant(java.lang.String name,
                 java.util.ArrayList<Participant> par)

Uses of Participant in schedule_structure

Fields in schedule_structure with type parameters of type Participant

Modifier and Type
Field and Description

private java.util.ArrayList<Participant>
ScheduleEvent.participants

List containing every participant in this event

java.util.HashMap<java.lang.String,java.util.ArrayList<Participant>>
Schedule.participantsRemaining

A hashmap of lists for remaining participants

Methods in schedule_structure that return types with arguments of type Participant

Modifier and Type
Method and Description

java.util.ArrayList<Participant>
ScheduleEvent.getParticipants()

private java.util.HashMap<java.lang.String,java.util.ArrayList<Participant>>
Schedule.initializeArrayLists()

Initializes array lists for each event containing all of the participants
 times the number of times they must complete the event.

Methods in schedule_structure with parameters of type Participant

Modifier and Type
Method and Description

boolean
ScheduleEvent.addParticipant(Participant person)

Adds a participant to this event, implying that the corresponding person
 is directly and equally involved with this event as every other listed
 participant.

Method parameters in schedule_structure with type arguments of type Participant

Modifier and Type
Method and Description

int
ScheduleEvent.addParticipants(java.util.ArrayList<Participant> people)

Adds a list of participants to this event, implying that the corresponding people
 are directly and equally involved with this event as every other listed
 participant.

Uses of Participant in scheduling_algorithm

Methods in scheduling_algorithm that return types with arguments of type Participant

Modifier and Type
Method and Description

private java.util.HashMap<java.lang.String,java.util.ArrayList<Participant>>
SchedulingAlgorithm.initializeArrayLists()

Initializes array lists for each event containing all of the participants
 times the number of times they must complete the event.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package kops

import (
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

var (
	SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
	AddToScheme   = SchemeBuilder.AddToScheme
)

//var GroupFactoryRegistry = make(announced.APIGroupFactoryRegistry)
//
//var Registry = registered.NewOrDie(os.Getenv("KOPS_API_VERSIONS"))
//
//var Scheme = runtime.NewScheme()
//
//var Codecs = serializer.NewCodecFactory(Scheme)
//
//// ParameterCodec handles versioning of objects that are converted to query parameters.
//var ParameterCodec = runtime.NewParameterCodec(Scheme)

// GroupName is the group name use in this package
const GroupName = "kops.k8s.io"

// SchemeGroupVersion is the group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal}

//// Kind takes an unqualified kind and returns a Group qualified GroupKind
//func Kind(kind string) schema.GroupKind {
//	return SchemeGroupVersion.WithKind(kind).GroupKind()
//}

// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
	return SchemeGroupVersion.WithResource(resource).GroupResource()
}

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&Cluster{},
		&ClusterList{},
		&InstanceGroup{},
		&InstanceGroupList{},
		&Keyset{},
		&KeysetList{},
		&SSHCredential{},
		&SSHCredentialList{},
	)
	//metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

func (obj *Cluster) GetObjectKind() schema.ObjectKind {
	return &obj.TypeMeta
}
func (obj *InstanceGroup) GetObjectKind() schema.ObjectKind {
	return &obj.TypeMeta
}
func (obj *Keyset) GetObjectKind() schema.ObjectKind {
	return &obj.TypeMeta
}
func (obj *SSHCredential) GetObjectKind() schema.ObjectKind {
	return &obj.TypeMeta
}


text:
#ifndef __ASM_MIPS_SECTIONS_H
#define __ASM_MIPS_SECTIONS_H

#include <asm-generic/sections.h>

/**
 * __rel_start: Relocation data generated by the mips-relocs tool
 *
 * See arch/mips/lib/reloc.c for details on the format & use of this data.
 */
extern uint8_t __rel_start[];

#endif


text:
"""This module contains API wrappers for the Geo TM service.
NOTE: The Geo Traffic Management Service is deprecated. Legacy users of the
service should contact Concierge for any questions on adding a Geo Traffic
Management  service to your zone. All other users should use Traffic Director
(DSF) instead.
"""
from dyn.tm.records import (ARecord, AAAARecord, CERTRecord,
                            CNAMERecord, DHCIDRecord, DNAMERecord,
                            DNSKEYRecord, DSRecord, KEYRecord, KXRecord,
                            LOCRecord, IPSECKEYRecord, MXRecord, NAPTRRecord,
                            PTRRecord, PXRecord, NSAPRecord, RPRecord,
                            NSRecord, SPFRecord, SRVRecord, TXTRecord)
from dyn.tm.session import DynectSession

__author__ = 'jnappi'
__all__ = ['GeoARecord', 'GeoAAAARecord', 'GeoCERTRecord', 'GeoCNAMERecord',
           'GeoDHCIDRecord', 'GeoDNAMERecord', 'GeoDNSKEYRecord',
           'GeoDSRecord', 'GeoKEYRecord', 'GeoKXRecord', 'GeoLOCRecord',
           'GeoIPSECKEYRecord', 'GeoMXRecord', 'GeoNAPTRRecord',
           'GeoPTRRecord', 'GeoPXRecord', 'GeoNSAPRecord', 'GeoRPRecord',
           'GeoNSRecord', 'GeoSPFRecord', 'GeoSRVRecord', 'GeoTXTRecord',
           'GeoRegionGroup', 'Geo']

class GeoARecord(ARecord):
    """An :class:`ARecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, weight, serve_count, label=None, ttl=None, *args,
                 **kwargs):
        """Create a :class:`GeoARecord` object

        :param weight: The weight for this :class:`GeoARecord`
        :param serve_count: The serve count for this :class:`GeoARecord`
        :param *args: Non keyword args for the associated :class:`ARecord`
        :param label: A unique label for this :class:`GeoARecord`
        :param ttl: TTL for the associated :class:`ARecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`ARecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoARecord, self).__init__(*args, **kwargs)
        self.weight = weight
        self.serve_count = serve_count
        self.label = label
        self._ttl = ttl

class GeoAAAARecord(AAAARecord):
    """An :class:`AAAARecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, weight, serve_count, label=None, ttl=None, *args,
                 **kwargs):
        """Create a :class:`GeoAAAARecord` object

        :param weight: The weight for this :class:`GeoAAAARecord`
        :param serve_count: The serve count for this :class:`GeoAAAARecord`
        :param *args: Non keyword args for the associated :class:`AAAARecord`
        :param label: A unique label for this :class:`GeoAAAARecord`
        :param ttl: TTL for the associated :class:`AAAARecord`
        :param **kwargs: Keyword args for the associated :class:`AAAARecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoAAAARecord, self).__init__(*args, **kwargs)
        self.weight = weight
        self.serve_count = serve_count
        self.label = label
        self._ttl = ttl

class GeoCERTRecord(CERTRecord):
    """An :class:`CERTRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoCERTRecord` object

        :param *args: Non keyword args for the associated :class:`CERTRecord`
        :param label: A unique label for this :class:`GeoCERTRecord`
        :param ttl: TTL for the associated :class:`CERTRecord`
        :param **kwargs: Keyword args for the associated :class:`CERTRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoCERTRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoCNAMERecord(CNAMERecord):
    """An :class:`CNAMERecord` object which is able to store additional data
    for use by a :class:`Geo` service.
    """
    def __init__(self, weight, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoCNAMERecord` object

        :param weight: The weight for this :class:`GeoCNAMERecord`
        :param *args: Non keyword args for the associated :class:`CNAMERecord`
        :param label: A unique label for this :class:`GeoCNAMERecord`
        :param ttl: TTL for the associated :class:`CNAMERecord`
        :param **kwargs: Keyword args for the associated :class:`CNAMERecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoCNAMERecord, self).__init__(*args, **kwargs)
        self.weight = weight
        self.label = label
        self._ttl = ttl

class GeoDHCIDRecord(DHCIDRecord):
    """An :class:`DHCIDRecord` object which is able to store additional data
    for use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoCNAMERecord` object

        :param *args: Non keyword args for the associated :class:`DHCIDRecord`
        :param label: A unique label for this :class:`GeoDHCIDRecord`
        :param ttl: TTL for the associated :class:`DHCIDRecord`
        :param **kwargs: Keyword args for the associated :class:`DHCIDRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoDHCIDRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoDNAMERecord(DNAMERecord):
    """An :class:`DNAMERecord` object which is able to store additional data
    for use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoDNAMERecord` object

        :param *args: Non keyword args for the associated :class:`DNAMERecord`
        :param label: A unique label for this :class:`GeoDNAMERecord`
        :param ttl: TTL for the associated :class:`DNAMERecord`
        :param **kwargs: Keyword args for the associated :class:`DNAMERecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoDNAMERecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoDNSKEYRecord(DNSKEYRecord):
    """An :class:`DNSKEYRecord` object which is able to store additional data
    for use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoDNSKEYRecord` object

        :param *args: Non keyword args for the associated :class:`DNSKEYRecord`
        :param label: A unique label for this :class:`GeoDNSKEYRecord`
        :param ttl: TTL for the associated :class:`DNSKEYRecord`
        :param **kwargs: Keyword args for the associated :class:`DNSKEYRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoDNSKEYRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoDSRecord(DSRecord):
    """An :class:`DSRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoDSRecord` object

        :param *args: Non keyword args for the associated :class:`DSRecord`
        :param label: A unique label for this :class:`GeoDSRecord`
        :param ttl: TTL for the associated :class:`DSRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`DSRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoDSRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoKEYRecord(KEYRecord):
    """An :class:`KEYRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoKEYRecord` object

        :param *args: Non keyword args for the associated :class:`KEYRecord`
        :param label: A unique label for this :class:`GeoKEYRecord`
        :param ttl: TTL for the associated :class:`KEYRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`KEYRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoKEYRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoKXRecord(KXRecord):
    """An :class:`KXRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoKXRecord` object

        :param *args: Non keyword args for the associated :class:`KXRecord`
        :param label: A unique label for this :class:`GeoKXRecord`
        :param ttl: TTL for the associated :class:`KXRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`KXRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoKXRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoLOCRecord(LOCRecord):
    """An :class:`LOCRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoLOCRecord` object

        :param *args: Non keyword args for the associated :class:`LOCRecord`
        :param label: A unique label for this :class:`GeoLOCRecord`
        :param ttl: TTL for the associated :class:`LOCRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`LOCRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoLOCRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoIPSECKEYRecord(IPSECKEYRecord):
    """An :class:`IPSECKEYRecord` object which is able to store additional data
    for use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoIPSECKEYRecord` object

        :param *args: Non keyword args for the associated
            :class:`IPSECKEYRecord`
        :param label: A unique label for this :class:`GeoIPSECKEYRecord`
        :param ttl: TTL for the associated :class:`IPSECKEYRecord`, will
            override a ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated
            :class:`IPSECKEYRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoIPSECKEYRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoMXRecord(MXRecord):
    """An :class:`MXRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoMXRecord` object

        :param *args: Non keyword args for the associated :class:`MXRecord`
        :param label: A unique label for this :class:`GeoMXRecord`
        :param ttl: TTL for the associated :class:`MXRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`MXRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoMXRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoNAPTRRecord(NAPTRRecord):
    """An :class:`NAPTRRecord` object which is able to store additional data
    for use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoNAPTRRecord` object

        :param *args: Non keyword args for the associated :class:`NAPTRRecord`
        :param label: A unique label for this :class:`GeoNAPTRRecord`
        :param ttl: TTL for the associated :class:`NAPTRRecord`, will override
            a ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`NAPTRRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoNAPTRRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoPTRRecord(PTRRecord):
    """An :class:`PTRRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoPTRRecord` object

        :param *args: Non keyword args for the associated :class:`PTRRecord`
        :param label: A unique label for this :class:`GeoPTRRecord`
        :param ttl: TTL for the associated :class:`PTRRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`PTRRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoPTRRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoPXRecord(PXRecord):
    """An :class:`PXRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoPXRecord` object

        :param *args: Non keyword args for the associated :class:`PXRecord`
        :param label: A unique label for this :class:`GeoPXRecord`
        :param ttl: TTL for the associated :class:`PXRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`PXRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoPXRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoNSAPRecord(NSAPRecord):
    """An :class:`NSAPRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoNSAPRecord` object

        :param *args: Non keyword args for the associated :class:`NSAPRecord`
        :param label: A unique label for this :class:`GeoNSAPRecord`
        :param ttl: TTL for the associated :class:`NSAPRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`NSAPRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoNSAPRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoRPRecord(RPRecord):
    """An :class:`RPRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoRPRecord` object

        :param *args: Non keyword args for the associated :class:`RPRecord`
        :param label: A unique label for this :class:`GeoRPRecord`
        :param ttl: TTL for the associated :class:`RPRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`RPRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoRPRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoNSRecord(NSRecord):
    """An :class:`NSRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoNSRecord` object

        :param *args: Non keyword args for the associated :class:`NSRecord`
        :param label: A unique label for this :class:`GeoNSRecord`
        :param ttl: TTL for the associated :class:`NSRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`NSRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoNSRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoSPFRecord(SPFRecord):
    """An :class:`SPFRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoSPFRecord` object

        :param *args: Non keyword args for the associated :class:`SPFRecord`
        :param label: A unique label for this :class:`GeoSPFRecord`
        :param ttl: TTL for the associated :class:`SPFRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`SPFRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoSPFRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoSRVRecord(SRVRecord):
    """An :class:`SRVRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoSRVRecord` object

        :param *args: Non keyword args for the associated :class:`SRVRecord`
        :param label: A unique label for this :class:`GeoSRVRecord`
        :param ttl: TTL for the associated :class:`SRVRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`SRVRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoSRVRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoTXTRecord(TXTRecord):
    """An :class:`TXTRecord` object which is able to store additional data for
    use by a :class:`Geo` service.
    """
    def __init__(self, label=None, ttl=None, *args, **kwargs):
        """Create a :class:`GeoTXTRecord` object

        :param *args: Non keyword args for the associated :class:`TXTRecord`
        :param label: A unique label for this :class:`GeoTXTRecord`
        :param ttl: TTL for the associated :class:`TXTRecord`, will override a
            ttl specified in *args or **kwargs
        :param **kwargs: Keyword args for the associated :class:`TXTRecord`
        """
        # Set api flag so the record isn't really created
        kwargs['create'] = False
        super(GeoTXTRecord, self).__init__(*args, **kwargs)
        self.label = label
        self._ttl = ttl

class GeoRegionGroup(object):
    """docstring for GeoRegionGroup"""
    def __init__(self, countries, name, geo_records, **kwargs):
        """Create a :class:`GeoRegionGroup` object

        :param countries: A list of ISO-3166 two letter codes to represent the
            names of countries and their subdivisions or one of the predefined
            groups.
        :param name: Name of this :class:`GeoRegionGroup`
        :param geo_records: A `list` of custom Geo DNSRecord subclass type
            objects
        """
        super(GeoRegionGroup, self).__init__()
        self.uri = None
        self._service_name = self._group_name = self._countries = None
        self._countries = countries
        self._name = name
        self.geo_records = geo_records
        # TODO: implement return data (GET) object creation
        if 'api' in kwargs:
            del kwargs['api']
            for key, val in kwargs.items():
                setattr(self, '_' + key, val)

    def _post(self, countries, name, geo_records):
        self._countries = countries
        self._name = name
        self.geo_records = geo_records
        api_args = {'service_name': self._service_name,
                    'group_name': self._group_name,
                    'countries': self._countries, 'name': self._name}
        return api_args

    def _get(self):
        api_args = {}
        response = DynectSession.get_session().execute(self.uri, 'GET',
                                                       api_args)
        for key, val in response['data'].items():
            setattr(self, '_' + key, val)

    @property
    def countries(self):
        return self._countries

    def delete(self):
        api_args = {}
        DynectSession.get_session().execute(self.uri, 'DELETE', api_args)

class Geo(object):
    """docstring for Geo"""
    def __init__(self, service_name, *args, **kwargs):
        """Create a new :class:`Geo` object

        :param service_name: The name of this Geo Service
        :param groups: A list of :class:`GeoRegionGroup`'s
        :param nodes: A list of :class:`GeoNode`'s
        :param ttl: Time to Live for each record in the service
        """
        super(Geo, self).__init__()
        self._service_name = service_name
        self.uri = '/Geo/{}/'.format(self._service_name)
        self._groups = self._nodes = self._ttl = None
        if 'api' in kwargs:
            del kwargs['api']
            for key, val in kwargs.items():
                setattr(self, '_' + key, val)
        elif len(args) == 0 and len(kwargs) == 0:
            self._get()
        else:
            self._post(*args, **kwargs)

    def _post(self, groups, ttl=None):
        """Create a new :class:`Geo` service on the DynECT System"""
        self._groups = groups
        self._ttl = ttl
        api_args = {'groups': []}
        nodes = []
        for group in groups:
            weight = {}
            serve_count = {}
            ttls = {}
            label = {}
            rdata = {}
            for record in group.geo_records:
                weight_name = ''.join([record.rec_name, '_weight'])
                serve_name = ''.join([record.rec_name, '_serve_count'])
                ttl_name = ''.join([record.rec_name, '_ttl'])
                label_name = ''.join([record.rec_name, '_label'])
                rdata_name = ''.join([record.rec_name, '_rdata'])
                # Build weight hash
                if hasattr(record, 'weight'):
                    if weight_name in weight:
                        weight[weight_name].append(record.weight)
                    else:
                        weight[weight_name] = [record.weight]
                # Build serve_count hash
                if hasattr(record, 'serve_count'):
                    serve_count[serve_name] = str(record.serve_count)
                # Build ttl hash
                if ttl_name in serve_count:
                    ttls[ttl_name] = str(record.ttl) or str(self._ttl)
                # Build label hash
                autolabel = ''
                if label_name in label:
                    label[label_name].append(record.label or autolabel)
                else:
                    label[label_name] = [record.label or autolabel]
                # Build rdata hash
                if rdata_name in rdata:
                    rdata[rdata_name].append(record.geo_rdata)
                else:
                    rdata[rdata_name] = [record.geo_rdata]
                nodes.append(record.geo_node)
            group_data = {'weight': weight, 'serve_count': serve_count,
                          'ttl': ttls, 'label': label, 'rdata': rdata,
                          'countries': group.countries, 'name': group._name}
            api_args['groups'].append(group_data)
        if self._ttl:
            api_args['ttl'] = self._ttl
        api_args['nodes'] = nodes
        response = DynectSession.get_session().execute(self.uri, 'POST',
                                                       api_args)
        for key, val in response['data'].items():
            if key == 'groups':
                pass
            elif key == 'nodes':
                pass
            else:
                setattr(self, '_' + key, val)

    def _get(self):
        """Get an existing :class:`Geo` service from the DynECT System"""
        api_args = {}
        response = DynectSession.get_session().execute(self.uri, 'GET',
                                                       api_args)
        for key, val in response['data'].items():
            if key == 'groups':
                pass
            elif key == 'nodes':
                pass
            else:
                setattr(self, '_' + key, val)

    def _update(self, api_args):
        """Private Update method"""
        response = DynectSession.get_session().execute(self.uri, 'PUT',
                                                       api_args)
        for key, val in response['data'].items():
            if key == 'groups':
                pass
            elif key == 'nodes':
                pass
            else:
                setattr(self, '_' + key, val)

    @property
    def service_name(self):
        return self._service_name

    @service_name.setter
    def service_name(self, new_name):
        self._service_name = new_name
        api_args = {'new_name': self._service_name}
        self._update(api_args)
        self.uri = '/Geo/{}/'.format(self._service_name)

    @property
    def groups(self):
        return self._groups

    @groups.setter
    def groups(self, value):
        self._groups = value
        api_args = {'groups': self._groups.to_json()}
        self._update(api_args)

    @property
    def nodes(self):
        return self._nodes

    @nodes.setter
    def nodes(self, value):
        self._nodes = value
        api_args = {'nodes': self._nodes.to_json()}
        self._update(api_args)

    def activate(self):
        """Activate this :class:`Geo` service on the DynECT System"""
        api_args = {'activate': True}
        self._update(api_args)

    def deactivate(self):
        """Deactivate this :class:`Geo` service on the DynECT System"""
        api_args = {'deactivate': True}
        self._update(api_args)

    def delete(self):
        """Delete this :class:`Geo` service from the DynECT System"""
        api_args = {}
        DynectSession.get_session().execute(self.uri, 'DELETE', api_args)


text:
//#ifdef _DEBUG
//#pragma comment(lib,"Leapd.lib")
//#else
#pragma comment(lib,"Leap.lib")
//#endif

using namespace Causality;
using namespace Causality::Devices;
using namespace Causality::Devices::Internal;

unique_ptr<StaticArmature> TrackedHand::s_pHandArmature;

#pragma region HandArmatureStaticDefination
static const char * const HandJointNames[TrackedHand::JointType_Count]=
{
	"Wrist",
	"ThumbMetacarpal",
	"ThumbProximal",
	"ThumbIntermediate",
	"ThumbDistal",
	"IndexMetacarpal",
	"IndexProximal",
	"IndexIntermediate",
	"IndexDistal",
	"MiddleMetacarpal",
	"MiddleProximal",
	"MiddleIntermediate",
	"MiddleDistal",
	"RingMetacarpal",
	"RingProximal",
	"RingIntermediate",
	"RingDistal",
	"PinkyMetacarpal",
	"PinkyProximal",
	"PinkyIntermediate",
	"PinkyDistal"
};

int TrackedHand::s_HandArmatureParentMap[TrackedHand::JointType_Count]=
{
	JointType_Null,
	JointType_Wrist,
	JointType_ThumbMetacarpal,
	JointType_ThumbProximal,
	JointType_ThumbIntermediate,
	JointType_Wrist,
	JointType_IndexMetacarpal,
	JointType_IndexProximal,
	JointType_IndexIntermediate,
	JointType_Wrist,
	JointType_MiddleMetacarpal,
	JointType_MiddleProximal,
	JointType_MiddleIntermediate,
	JointType_Wrist,
	JointType_RingMetacarpal,
	JointType_RingProximal,
	JointType_RingIntermediate,
	JointType_Wrist,
	JointType_PinkyMetacarpal,
	JointType_PinkyProximal,
	JointType_PinkyIntermediate,
};
#pragma endregion

void TrackedHand::IntializeHandArmature()
{
	if (s_pHandArmature) return;
	s_pHandArmature.reset(new StaticArmature((size_t)JointType_Count, s_HandArmatureParentMap, HandJointNames));
}

class Devices::Internal::LeapListener : public Leap::Listener
{
public:
	LeapListener(LeapSensor* pLeap)
	{
		m_pSensor = pLeap;
		m_pause = false;
		m_hasNewFrame = false;
		m_lostThreshold = 30;
	}
	~LeapListener()
	{
	}

	LeapListener(const LeapListener&) = delete;

	virtual void onConnect(const Leap::Controller & controller) override;
	virtual void onDisconnect(const Leap::Controller &controller) override;
	virtual void onFrame(const Leap::Controller &controller) override;

	void processLostHands();

	bool pullFrame(const Leap::Controller & controller);

	void processHand(const Leap::Hand& leaphand, TrackedHand& hand, bool isNew, time_t time);

	LeapSensor*					m_pSensor;
	Leap::Frame					m_frame;
	Matrix4x4					m_world;
	int							m_lostThreshold;
	bool						m_pause;
	bool						m_hasNewFrame;
	std::list<TrackedHand>		m_hands;
};

std::weak_ptr<LeapSensor> LeapSensor::wpCurrentDevice;

std::shared_ptr<LeapSensor> Causality::Devices::LeapSensor::GetForCurrentView()
{
	if (wpCurrentDevice.expired())
	{
		auto pDevice = std::make_shared<LeapSensor>(false,true);
		wpCurrentDevice = pDevice;
		return pDevice;
	}
	else
	{
		return wpCurrentDevice.lock();
	}
}

LeapSensor::LeapSensor()
	:
	m_useEvent(false),
	m_isFixed(true),
	m_started(false),
	m_connected(false)
{
	pController = new Leap::Controller();
	pListener.reset(new LeapListener(this));
}

LeapSensor::LeapSensor(bool useEvent, bool isFixed)
	: LeapSensor()
{
	Initialize(useEvent, isFixed);
}

void LeapSensor::Initialize(bool useEvent, bool isFixed)
{
	TrackedHand::IntializeHandArmature();

	if (m_started)
		Stop();

	using namespace DirectX;
	m_useEvent = useEvent;
	m_isFixed = isFixed;
	if (!isFixed)
		pController->setPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD);
}

LeapSensor::~LeapSensor()
{
	if (pListener && pController)
		pController->removeListener(*pListener.get());
	pListener.reset();
	//if (pController) delete pController;
}

Leap::Controller & LeapSensor::Controller() {
	return *pController;
}

const Leap::Controller & LeapSensor::Controller() const {
	return *pController;
}

//void LeapSensor::SetMotionProvider(DirectX::ILocatable * pHeadLoc, DirectX::IOriented * pHeadOrient)
//{
//	pHeadLocation = pHeadLoc;
//	pHeadOrientation = pHeadOrient;
//}

void LeapSensor::SetDeviceWorldCoord(const DirectX::Matrix4x4 & m)
{
	using namespace DirectX;
	if (pListener)
		pListener->m_world = m;
}

DirectX::XMMATRIX LeapSensor::ToWorldTransform() const
{
	using namespace DirectX;
	//if (pHeadLocation && pHeadOrientation)
	//	return m_world * XMMatrixRigidTransform(pHeadOrientation->GetOrientation() ,pHeadLocation->GetPosition());
	//else
	return pListener->m_world;
}

void LeapListener::onConnect(const Leap::Controller & controller)
{
	m_pSensor->Connected(*m_pSensor);
	std::cout << "[Leap] Device Connected." << std::endl;
}

void LeapListener::onDisconnect(const Leap::Controller & controller)
{
	m_pSensor->Disconnected(*m_pSensor);
	std::cout << "[Leap] Device Disconnected." << std::endl;
}

void LeapListener::onFrame(const Leap::Controller & controller)
{
	if (m_pause)
		m_hasNewFrame = false;
	else
		m_hasNewFrame = pullFrame(controller);	//m_pSensor->FrameArrived(controller);

	if (!m_hasNewFrame)	return;

	// Process experied bodies
	processLostHands();

	for (const auto& leaphand : m_frame.hands())
	{
		auto itr = std::find(m_hands.begin(), m_hands.end(), (int64_t)leaphand.id());
		bool isNew = itr == m_hands.end();
		if (isNew && leaphand.isValid())
		{
			itr = m_hands.emplace(m_hands.end(), (int64_t)leaphand.id(), leaphand.isLeft());
			itr->m_pSensor = m_pSensor;
		}
		else if (!isNew && !leaphand.isValid()) // this means not tracked
		{
			continue;
		}

		auto& hand = *itr;

		processHand(leaphand, hand, isNew, m_frame.timestamp());

		if (isNew)
		{
			auto& hand = m_hands.back();
			m_pSensor->HandTracked(hand);
		}
	}
}

void LeapListener::processLostHands()
{
	for (auto itr = m_hands.begin(), end = m_hands.end(); itr != end;)
	{
		itr->IncreaseLostFrameCount();
		if (itr->GetLostFrameCount() >= m_lostThreshold)
		{
			if (itr->m_isTracked)
			{
				itr->m_isTracked = false;
				itr->Lost(*itr);
				m_pSensor->HandLost(*itr);
				int refcount = itr->RefCount();
				std::cout << "Hands Lost : ID = " << itr->GetTrackId() << "RefCount = " << refcount << std::endl;
			}
			if (itr->RefCount() <= 0)
				itr = m_hands.erase(itr);
			else
				++itr;
		}
		else
			++itr;
	}

}

bool LeapListener::pullFrame(const Leap::Controller & controller)
{
	auto frame = controller.frame();
	if (!frame.isValid() || m_frame == frame)
		return false;
	m_frame = std::move(frame);
	return true;
}

void LeapListener::processHand(const Leap::Hand& leaphand, TrackedHand& hand, bool isNew, time_t time)
{
	Vector3 s, t;
	ArmatureFrame frame(TrackedHand::JointType_Count);

	hand.m_isTracked = true;
	hand.ResetLostFrameCount();

	bool isLeft = leaphand.isLeft();

	auto lbasis = leaphand.basis();
	lbasis.origin = leaphand.wristPosition();
	if (isLeft)	lbasis.zBasis *= -1;

	auto basis = lbasis.toMatrix4x4<Matrix4x4>();
	basis *= m_world;
	basis.Decompose(s, frame[0].GblRotation, frame[0].GblTranslation);

	for (auto& finger : leaphand.fingers())
	{
		auto fid = finger.type();
		for (int bid = Leap::Bone::Type::TYPE_METACARPAL;
				 bid <= Leap::Bone::TYPE_DISTAL; ++bid)
		{
			auto leapbone = finger.bone((Leap::Bone::Type)bid);
			auto& bone = frame[fid*4 + bid+1];
			auto lbasis = leapbone.basis();
			lbasis.origin = leapbone.nextJoint();
			if (isLeft)
				lbasis.zBasis *= -1;
			basis = lbasis.toMatrix4x4<Matrix4x4>();
			basis *= m_world;
			basis.Decompose(s, bone.GblRotation, bone.GblTranslation);
			bone.StoreConfidence(leaphand.confidence());
		}
	}

	auto& armature = hand.m_armature;
	FrameRebuildLocal(armature, frame);

	if (isNew)
		hand.SetArmatureProportion(frame);

	hand.PushFrame(time,std::move(frame));

	if (isNew)
	{
		m_pSensor->HandTracked(hand);
		std::cout << "New Hand Tracked : ID = " << hand.GetTrackId() << std::endl;
	}
}

bool LeapSensor::Initialize(const ParamArchive * archive)
{
	IsometricTransform world;
	world.Scale = Vector3(0.001f); // convert unit mm to m , factor 1mm = 0.01m
	GetParam(archive, "translation", world.Translation);
	GetParam(archive, "scale", world.Scale);
	Vector3 eular;
	GetParam(archive, "rotation", eular);
	world.Rotation = Quaternion::CreateFromYawPitchRoll(eular.y, eular.x, eular.z);
	SetDeviceWorldCoord(world.TransformMatrix());

	bool useEvent = false, isFixed = true;
	GetParam(archive, "asynchronize", useEvent);
	GetParam(archive, "fixed", isFixed);
	Initialize(useEvent, isFixed);

	return true;
}

bool LeapSensor::Start()
{
	if (m_started) return false;

	if (m_useEvent)
		pController->addListener(*pListener);
	m_started = true;
	return m_started;
}

void LeapSensor::Stop()
{
	if (!Disconnected.empty() && m_connected)
	{
		m_connected = false;
		Disconnected(*this);
	}

	if (m_started && m_useEvent)
		pController->removeListener(*pListener);
}

bool LeapSensor::Update()
{
	bool connected = pController->isConnected();
	bool prev = m_connected;

	if (prev != connected)
		m_connected = connected;

	if (connected && !prev)
		pListener->onConnect(*pController);
	else if (!connected && prev)
		pListener->onDisconnect(*pController);

	if (connected)
	{
		pListener->onFrame(*pController);
		return pListener->m_hasNewFrame;
	}
	return connected;
}

bool LeapSensor::IsStreaming() const
{
	return !pListener && pController->isConnected() && m_started;
}

bool LeapSensor::IsAsychronize() const
{
	return m_useEvent;
}

bool LeapSensor::Pause()
{
	pListener->m_pause = true;
	return true;
}

bool LeapSensor::Resume()
{
	pListener->m_pause = false;
	return true;
}

const std::list<TrackedHand>& Causality::Devices::LeapSensor::GetTrackedHands() const
{
	return pListener->m_hands;
}

std::list<TrackedHand>& Causality::Devices::LeapSensor::GetTrackedHands()
{
	return pListener->m_hands;
}

TrackedHand::TrackedHand(int64_t id, bool isLeft)
	: TrackedArmature(*s_pHandArmature)
{
	m_id = id;
	m_isLeft = isLeft;
}

TrackedHand::~TrackedHand()
{
}


text:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
|==========================================================
| Initialize Variable Parser Class
|==========================================================
|
*/
if ( ! class_exists('_Parser'))
{
	require_once(BASEPATH.'libraries/Parser'.EXT);
}

$obj =& get_instance();
$obj->parser = new _Parser();
$obj->ci_is_loaded[] = 'parser';

?>


text:
require 'socket'

describe 'Socket::AncillaryData.int' do
  before do
    @data = Socket::AncillaryData.int(:INET, :SOCKET, :RIGHTS, 4)
  end

  it 'returns a Socket::AncillaryData' do
    @data.should be_an_instance_of(Socket::AncillaryData)
  end

  it 'sets the family to AF_INET' do
    @data.family.should == Socket::AF_INET
  end

  it 'sets the level SOL_SOCKET' do
    @data.level.should == Socket::SOL_SOCKET
  end

  it 'sets the type SCM_RIGHTS' do
    @data.type.should == Socket::SCM_RIGHTS
  end

  it 'sets the data to a packed String' do
    @data.data.should == [4].pack('I')
  end
end

describe 'Socket::AncillaryData#int' do
  it 'returns the data as a Fixnum' do
    data = Socket::AncillaryData.int(:UNIX, :SOCKET, :RIGHTS, 4)

    data.int.should == 4
  end

  it 'raises when the data is not a Fixnum' do
    data = Socket::AncillaryData.new(:UNIX, :SOCKET, :RIGHTS, 'ugh')

    proc { data.int }.should raise_error(TypeError)
  end
end


text:
package de.uni.freiburg.iig.telematik.sepia.petrinet.pt.properties.wfnet;

import de.uni.freiburg.iig.telematik.sepia.mg.abstr.AbstractMarkingGraph;
import de.uni.freiburg.iig.telematik.sepia.petrinet.properties.NetCheckingProperties;
import de.uni.freiburg.iig.telematik.sepia.petrinet.properties.PNProperties.InOutPlaces;
import de.uni.freiburg.iig.telematik.sepia.petrinet.properties.PropertyCheckingResult;

public class WFNetProperties extends NetCheckingProperties {

	public PropertyCheckingResult hasWFNetStructure = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult validInOutPlaces = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult strongConnectedness = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult safeness = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult optionToCompleteAndProperCompletion = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult isSoundWFNet = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult isStructuredWFNet = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult noDeadTransitions = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult validInitialMarking = PropertyCheckingResult.UNKNOWN;
	public PropertyCheckingResult isBounded = PropertyCheckingResult.UNKNOWN;
	public InOutPlaces inOutPlaces = null;
	public AbstractMarkingGraph markingGraph = null;

	public boolean isWFNet(){
		return exception == null;
	}
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Seno Aiko
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var gTestfile = 'regress-350621.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 350621;
var summary = 'for-in loops over generator objects';
var actual = '';
var expect = '';

//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------

function test()
{
  enterFunc ('test');
  printBugNumber(BUGNUMBER);
  printStatus (summary);

  var LOOPS = 500;

  function gen1() {
    for (var a = 1; a <= LOOPS; ++a)
      yield;
  }

  function gen2() {
    for (var b in gen1())
      yield;
  }

  function test_it(RUNS) {
    for (var c = 1; c <= RUNS; ++c) {
      var count = 0;
      for (var d in gen2()) {
        // The next line is needed to demonstrate the bug.
        // Note that simply omitting the "x" triggers the bug far less often.
        Object("x");
        ++count;
      }
      if (count != LOOPS) {
        print("Test run " + c + ": test failed, count = " + count +
	      ", should be " + LOOPS);
        var failed = true;
      }
    }
    actual = !failed;
    if (!failed)
    {
      print("Test passed.");
    }
  }

  expect = true;
  test_it(20);

  reportCompare(expect, actual, summary);

  exitFunc ('test');
}


text:
Thuriot.be
====================

Old website's theme, because nostalgia.
Because I'm hosting it on GitHub, doesn't mean anyone can use this for their site.

![Site](https://cloud.githubusercontent.com/assets/544444/5286926/94be8a66-7b28-11e4-99f2-1332fd7f6e57.png)


text:
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * HproseFormatter.h                                      *
 *                                                        *
 * hprose formatter class header for Objective-C.         *
 *                                                        *
 * LastModified: Apr 12, 2014                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

#import <Foundation/Foundation.h>

@interface HproseFormatter : NSObject;

+ (id) serialize:(id)obj;
+ (id) serialize:(id)obj simple:(BOOL)simple;

+ (id) unserialize:(NSData *)data;
+ (id) unserialize:(NSData *)data withClass:(Class)cls;
+ (id) unserialize:(NSData *)data withType:(char)type;
+ (id) unserialize:(NSData *)data withClass:(Class)cls withType:(char)type;
+ (id) unserialize:(NSData *)data simple:(BOOL)simple;
+ (id) unserialize:(NSData *)data withClass:(Class)cls simple:(BOOL)simple;
+ (id) unserialize:(NSData *)data withType:(char)type simple:(BOOL)simple;
+ (id) unserialize:(NSData *)data withClass:(Class)cls withType:(char)type simple:(BOOL)simple;

@end


text:
require 'simplecov'
SimpleCov.start do
  add_filter "/spec/"
end

require 'sqrl'

# Delets the specified file both before and after a test.
def clean_file(filename, &block)
  File.delete(filename) if File.exist? filename
  block.call
ensure
  File.delete(filename) if File.exist? filename
end


text:
package com.github.jjYBdx4IL.utils.vmmgmt;

//CHECKSTYLE:OFF
/**
 *
 * @author jjYBdx4IL
 */
public enum ConnectType {

    QemuSystem("qemu:///system"),
    QemuSession("qemu:///session");

    private final String value;

    private ConnectType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}


text:
Florijncoin (FLC)

New DutchCoin for people, not persons!

600.000.000 coins available
Block every 60 secs
Start block reward 1000 coins

Linux dependencies:

sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get install libcurl4-openssl-dev build-essential libboost-dev libdb48-dev openssl libdb++-dev git qt-sdk

# florijncoin
start testnet

./florijncoind -testnet -connect=iptoconnect -listen=1 -testnet=1 -testnet_config=1 &


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~    Copyright 2019 Andrey Mukamolov
  ~
  ~    Licensed under the Apache License, Version 2.0 (the "License");
  ~    you may not use this file except in compliance with the License.
  ~    You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~    Unless required by applicable law or agreed to in writing, software
  ~    distributed under the License is distributed on an "AS IS" BASIS,
  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~    See the License for the specific language governing permissions and
  ~    limitations under the License.
  -->

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
  <shortcut
    android:enabled="true"
    android:icon="@drawable/ic_scan_qrcode_shortcut"
    android:shortcutDisabledMessage="@string/scan_shortcut_disabled_message"
    android:shortcutId="scan"
    android:shortcutLongLabel="@string/scan_shortcut_long_label"
    android:shortcutShortLabel="@string/scan_shortcut_short_label">
    <intent
      android:action="android.intent.action.VIEW"
      android:targetClass="com.bookcrossing.mobile.ui.scan.ScanActivity"
      android:targetPackage="com.bookcrossing.mobile" />
  </shortcut>
  <shortcut
    android:enabled="true"
    android:icon="@drawable/ic_release_shortcut"
    android:shortcutDisabledMessage="@string/release_shortcut_disabled_message"
    android:shortcutId="release"
    android:shortcutLongLabel="@string/release_shortcut_long_label"
    android:shortcutShortLabel="@string/release_shortcut_short_label">
    <intent
      android:action="android.intent.action.VIEW"
      android:targetClass="com.bookcrossing.mobile.ui.main.MainActivity"
      android:targetPackage="com.bookcrossing.mobile">
      <extra
        android:name="targetFragment"
        android:value="BookReleaseFragment" />
    </intent>
  </shortcut>
  <shortcut
    android:enabled="true"
    android:icon="@drawable/ic_map_shortcut"
    android:shortcutDisabledMessage="@string/map_shortcut_disabled_message"
    android:shortcutId="map"
    android:shortcutLongLabel="@string/map_shortcut_long_label"
    android:shortcutShortLabel="@string/map_shortcut_short_label">
    <intent
      android:action="android.intent.action.VIEW"
      android:targetClass="com.bookcrossing.mobile.ui.main.MainActivity"
      android:targetPackage="com.bookcrossing.mobile">
      <extra
        android:name="targetFragment"
        android:value="MapsFragment" />
    </intent>
  </shortcut>
</shortcuts>


text:
#ifndef _EFI_SMM_PERIODIC_TIMER_DISPATCH_H_
#define _EFI_SMM_PERIODIC_TIMER_DISPATCH_H_

//
// Global ID for the Periodic Timer SMI Protocol
//
#define EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL_GUID \
  { \
    0x9cca03fc, 0x4c9e, 0x4a19, {0x9b, 0x6, 0xed, 0x7b, 0x47, 0x9b, 0xde, 0x55 } \
  }

typedef struct _EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL  EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL;

//
// Related Definitions
//

typedef struct {
  ///
  /// The minimum period of time that the child gets called, in 100 nanosecond units.
  /// The child will be called back after a time greater than the time Period.
  ///
  UINT64  Period;
  ///
  /// The period of time interval between SMIs.  Children of this interface
  /// should use this field when registering for periodic timer intervals when a finer
  /// granularity periodic SMI is desired.  Valid values for this field are those returned
  /// by GetNextInterval.  A value of 0 indicates the parent is allowed to use any SMI
  /// interval period to satisfy the requested period.
  ///
  UINT64  SmiTickInterval;
  ///
  /// The actual time in 100 nanosecond units elapsed since last called. A
  /// value of 0 indicates an unknown amount of time.
  ///
  UINT64  ElapsedTime;
} EFI_SMM_PERIODIC_TIMER_DISPATCH_CONTEXT;

//
// Member functions
//
/**
  Dispatch function for a Periodic Timer SMI handler.

  @param  DispatchHandle        The handle of this dispatch function.
  @param  DispatchContext       The pointer to the dispatch function's context.
                                The DispatchContext fields are filled in
                                by the dispatching driver prior to
                                invoking this dispatch function.

  @return None

**/
typedef
VOID
(EFIAPI *EFI_SMM_PERIODIC_TIMER_DISPATCH)(
  IN EFI_HANDLE                                DispatchHandle,
  IN EFI_SMM_PERIODIC_TIMER_DISPATCH_CONTEXT   *DispatchContext
  );

/**
  Returns the next SMI tick period supported by the chipset.  The order
  returned is from longest to shortest interval period.

  @param  This                  The protocol instance pointer.
  @param  SmiTickInterval       The pointer to pointer of next shorter SMI interval
                                period supported by the child. This parameter works as a get-first,
                                get-next field. The first time this function is called, *SmiTickInterval
                                should be set to NULL to get the longest SMI interval. The returned
                                *SmiTickInterval should be passed in on subsequent calls to get the
                                next shorter interval period until *SmiTickInterval = NULL.

  @retval EFI_SUCCESS           The service returned successfully.

**/
typedef
EFI_STATUS
(EFIAPI *EFI_SMM_PERIODIC_TIMER_INTERVAL)(
  IN EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL           *This,
  IN OUT UINT64                                         **SmiTickInterval
  );

/**
  Register a child SMI source dispatch function with a parent SMM driver

  @param  This                  The pointer to the EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL instance.
  @param  DispatchFunction      The function to install.
  @param  DispatchContext       The pointer to the dispatch function's context.
                                Indicates to the register
                                function the period at which the dispatch function
                                should be invoked.
  @param  DispatchHandle        The handle generated by the dispatcher to track the function instance.

  @retval EFI_SUCCESS           The dispatch function has been successfully
                                registered, and the SMI source has been enabled.
  @retval EFI_DEVICE_ERROR      The driver was unable to enable the SMI source.
  @retval EFI_OUT_OF_RESOURCES  Not enough memory (system or SMM) to manage this
                                child.
  @retval EFI_INVALID_PARAMETER DispatchContext is invalid. The period input value
                                is not within valid range.

**/
typedef
EFI_STATUS
(EFIAPI *EFI_SMM_PERIODIC_TIMER_REGISTER)(
  IN EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL          *This,
  IN EFI_SMM_PERIODIC_TIMER_DISPATCH                   DispatchFunction,
  IN EFI_SMM_PERIODIC_TIMER_DISPATCH_CONTEXT           *DispatchContext,
  OUT EFI_HANDLE                                       *DispatchHandle
  );

/**
  Unregisters a periodic timer service.

  @param  This                  The pointer to the EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL instance.
  @param  DispatchHandle        The handle of the service to remove.

  @retval EFI_SUCCESS           The dispatch function has been successfully
                                unregistered, and the SMI source has been disabled
                                if there are no other registered child dispatch
                                functions for this SMI source.
  @retval EFI_INVALID_PARAMETER The handle is invalid.

**/
typedef
EFI_STATUS
(EFIAPI *EFI_SMM_PERIODIC_TIMER_UNREGISTER)(
  IN EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL          *This,
  IN EFI_HANDLE                                        DispatchHandle
  );

//
// Interface structure for the SMM Periodic Timer Dispatch Protocol
//
/**
  Provides the parent dispatch service for the periodical timer SMI source generator.
**/
struct _EFI_SMM_PERIODIC_TIMER_DISPATCH_PROTOCOL {
  ///
  /// Installs a child service to be dispatched by this protocol.
  ///
  EFI_SMM_PERIODIC_TIMER_REGISTER   Register;

  ///
  /// Removes a child service dispatched by this protocol.
  ///
  EFI_SMM_PERIODIC_TIMER_UNREGISTER UnRegister;

  ///
  /// Returns the next SMI tick period that is supported by the chipset.
  ///
  EFI_SMM_PERIODIC_TIMER_INTERVAL   GetNextShorterInterval;
};

extern EFI_GUID gEfiSmmPeriodicTimerDispatchProtocolGuid;

#endif


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

namespace AskerBundle\Entity\Test;

use AskerBundle\Entity\ExerciseModel\ExerciseModel;

/**
 * Class TestModelPosition
 *
 * @author Baptiste Cablé <baptiste.cable@liris.cnrs.fr>
 */
class TestModelPosition
{
    /**
     * @var ExerciseModel
     */
    private $exerciseModel;

    /**
     * @var TestModel
     */
    private $testModel;

    /**
     * @var int
     */
    private $position;

    /**
     * Set position
     *
     * @param int $position
     */
    public function setPosition($position)
    {
        $this->position = $position;
    }

    /**
     * Get position
     *
     * @return int
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set testModel
     *
     * @param TestModel $testModel
     */
    public function setTestModel($testModel)
    {
        $this->testModel = $testModel;
    }

    /**
     * Get testModel
     *
     * @return TestModel
     */
    public function getTestModel()
    {
        return $this->testModel;
    }

    /**
     * Set exerciseModel
     *
     * @param \AskerBundle\Entity\ExerciseModel\ExerciseModel $exerciseModel
     */
    public function setExerciseModel($exerciseModel)
    {
        $this->exerciseModel = $exerciseModel;
    }

    /**
     * Get exerciseModel
     *
     * @return \AskerBundle\Entity\ExerciseModel\ExerciseModel
     */
    public function getExerciseModel()
    {
        return $this->exerciseModel;
    }

}