import "../Contacts"
import "../Groups"
import "../common"
import QtQuick 1.1
import com.nokia.meego 1.0
WAPage {
    id: selectorroot
    property alias contactsTitle:contactsSelector.title
    property alias groupsTitle:groupsSelector.title
    property int show:2 //0:all, 1:contacts, 2:groups
    property bool multiSelect:false

    signal selected(variant selectedItem)

    tools:selectorTools

    TabGroup {
        id: tabGroups
        currentTab: contactsSelector

       SyncedContactsList{
            id:contactsSelector

            Connections {
                onSelected:selected(selectedItem)
            }
            height: parent.height
        }
        GroupsList {
            id: groupsSelector
            Connections {
                onSelected:selected(selectedItem)
            }
            height: parent.height
        }
    }

    ToolBarLayout {

        id:selectorTools

        ToolIcon {
            platformIconId: "toolbar-back"
            onClicked: pageStack.pop()
        }

        ButtonRow {
            style: TabButtonStyle { inverted:theme.inverted }

            TabButton {
                id: contactsButton
                platformStyle: TabButtonStyle{inverted:theme.inverted}
                text: qsTr("Contacts")
                //iconSource: "image://theme/icon-m-toolbar-new-chat" + (theme.inverted ? "-white" : "")
                tab: contactsSelector
            }
            TabButton {
                id: groupsbButton
                platformStyle: TabButtonStyle{inverted: theme.inverted}
                text: qsTr("Groups")
                //iconSource: "common/images/book" + (theme.inverted ? "-white" : "") + ".png";
                tab: groupsSelector
            }
        }

    }
}


// /** @file
// Instance of S3 PCI Library based on PCI and S3 BootScript Library.
//
// S3 PCI Services that perform PCI Configuration cycles and
// also enable the PCI operation to be replayed during an S3 resume.
//
// Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
//
// This program and the accompanying materials are
// licensed and made available under the terms and conditions of the BSD License
// which accompanies this distribution.  The full text of the license may be found at
// http://opensource.org/licenses/bsd-license.php
//
// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
//
// **/

#string STR_MODULE_ABSTRACT             #language en-US "Instance of S3 PCI Library based on PCI and S3 BootScript Library"

#string STR_MODULE_DESCRIPTION          #language en-US "S3 PCI Services that perform PCI Configuration cycles and also enable the PCI operation to be replayed during an S3 resume."


/* crypto/ecdh/ecdh.h */
/* ====================================================================
 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 *
 * The Elliptic Curve Public-Key Crypto Library (ECC Code) included
 * herein is developed by SUN MICROSYSTEMS, INC., and is contributed
 * to the OpenSSL project.
 *
 * The ECC Code is licensed pursuant to the OpenSSL open source
 * license provided below.
 *
 * The ECDH software is originally written by Douglas Stebila of
 * Sun Microsystems Laboratories.
 *
 */
/* ====================================================================
 * Copyright (c) 2000-2002 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */
#ifndef HEADER_ECDH_H
#define HEADER_ECDH_H

#include <openssl/opensslconf.h>

#ifdef OPENSSL_NO_ECDH
#error ECDH is disabled.
#endif

#include <openssl/ec.h>
#include <openssl/ossl_typ.h>
#ifndef OPENSSL_NO_DEPRECATED
#include <openssl/bn.h>
#endif

#ifdef __cplusplus
extern "C" {
#endif

const ECDH_METHOD *ECDH_OpenSSL(void);

void	  ECDH_set_default_method(const ECDH_METHOD *);
const ECDH_METHOD *ECDH_get_default_method(void);
int 	  ECDH_set_method(EC_KEY *, const ECDH_METHOD *);

int ECDH_compute_key(void *out, size_t outlen, const EC_POINT *pub_key, EC_KEY *ecdh,
                     void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen));

int 	  ECDH_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new
		*new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
int 	  ECDH_set_ex_data(EC_KEY *d, int idx, void *arg);
void 	  *ECDH_get_ex_data(EC_KEY *d, int idx);

/* BEGIN ERROR CODES */
/* The following lines are auto generated by the script mkerr.pl. Any changes
 * made after this point may be overwritten when the script is next run.
 */
void ERR_load_ECDH_strings(void);

/* Error codes for the ECDH functions. */

/* Function codes. */
#define ECDH_F_ECDH_CHECK				 102
#define ECDH_F_ECDH_COMPUTE_KEY				 100
#define ECDH_F_ECDH_DATA_NEW_METHOD			 101

/* Reason codes. */
#define ECDH_R_KDF_FAILED				 102
#define ECDH_R_NON_FIPS_METHOD				 103
#define ECDH_R_NO_PRIVATE_VALUE				 100
#define ECDH_R_POINT_ARITHMETIC_FAILURE			 101

#ifdef  __cplusplus
}
#endif
#endif


using Zinnia.Data.Collection.List;
using Zinnia.Rule;
using Zinnia.Tracking;

namespace Test.Zinnia.Tracking
{
    using NUnit.Framework;
    using System.Collections;
    using Test.Zinnia.Utility.Mock;
    using Test.Zinnia.Utility.Stub;
    using UnityEngine;
    using UnityEngine.TestTools;
    using Assert = UnityEngine.Assertions.Assert;

    public class SurfaceLocatorTest
    {
        private GameObject containingObject;
        private SurfaceLocator subject;
        private WaitForFixedUpdate waitForFixedUpdate = new WaitForFixedUpdate();

        [SetUp]
        public void SetUp()
        {
            Physics.autoSimulation = false;
            containingObject = new GameObject("ContainingObject");
            subject = containingObject.AddComponent<SurfaceLocator>();
        }

        [TearDown]
        public void TearDown()
        {
            Object.DestroyImmediate(subject);
            Object.DestroyImmediate(containingObject);
            Physics.autoSimulation = true;
        }

        [Test]
        public void ValidSurface()
        {
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 5f;

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            //Process just calls Locate() so may as well just test the first point
            Physics.Simulate(Time.fixedDeltaTime);
            subject.Process();

            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            subject.gameObject.SetActive(false);
            subject.gameObject.SetActive(true);

            Assert.AreEqual(null, subject.surfaceData.Transform);

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [Test]
        public void MissingSurface()
        {
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.down;

            Physics.Simulate(Time.fixedDeltaTime);
            subject.Locate();
            Assert.IsFalse(surfaceLocatedMock.Received);
            Assert.IsNull(subject.surfaceData.Transform);

            Object.DestroyImmediate(searchOrigin);
        }

        [Test]
        public void InvalidLocateSameSurface()
        {
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 5f;

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            //Process just calls Locate() so may as well just test the first point
            Physics.Simulate(Time.fixedDeltaTime);
            subject.Process();

            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            surfaceLocatedMock.Reset();

            subject.Process();

            Assert.IsFalse(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [Test]
        public void ValidLocateSameSurfaceIgnoreEquality()
        {
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 5f;

            subject.MustChangePosition = false;
            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            //Process just calls Locate() so may as well just test the first point
            Physics.Simulate(Time.fixedDeltaTime);
            subject.Process();

            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            surfaceLocatedMock.Reset();

            subject.Process();

            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator InvalidSurfaceDueToTargetValidity()
        {
            Physics.autoSimulation = true;

            GameObject invalidSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            invalidSurface.transform.position = Vector3.forward * 5f;
            invalidSurface.AddComponent<RuleStub>();
            NegationRule negationRule = invalidSurface.AddComponent<NegationRule>();
            AnyComponentTypeRule anyComponentTypeRule = invalidSurface.AddComponent<AnyComponentTypeRule>();
            SerializableTypeComponentObservableList rules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeRule.ComponentTypes = rules;
            rules.Add(typeof(RuleStub));

            negationRule.Rule = new RuleContainer
            {
                Interface = anyComponentTypeRule
            };
            subject.TargetValidity = new RuleContainer
            {
                Interface = negationRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsFalse(surfaceLocatedMock.Received);
            Assert.IsNull(subject.surfaceData.Transform);

            Object.DestroyImmediate(invalidSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator ValidSurfaceDueToTargetValidity()
        {
            Physics.autoSimulation = true;

            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 5f;
            validSurface.AddComponent<RuleStub>();
            AnyComponentTypeRule anyComponentTypeRule = validSurface.AddComponent<AnyComponentTypeRule>();
            SerializableTypeComponentObservableList rules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeRule.ComponentTypes = rules;
            rules.Add(typeof(RuleStub));

            subject.TargetValidity = new RuleContainer
            {
                Interface = anyComponentTypeRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator ValidSurfaceDueToEventualTargetValidity()
        {
            Physics.autoSimulation = true;

            GameObject invalidSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 10f;
            invalidSurface.transform.position = Vector3.forward * 5f;
            invalidSurface.AddComponent<RuleStub>();
            NegationRule negationRule = invalidSurface.AddComponent<NegationRule>();
            AnyComponentTypeRule anyComponentTypeRule = invalidSurface.AddComponent<AnyComponentTypeRule>();
            SerializableTypeComponentObservableList rules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeRule.ComponentTypes = rules;
            rules.Add(typeof(RuleStub));

            negationRule.Rule = new RuleContainer
            {
                Interface = anyComponentTypeRule
            };
            subject.TargetValidity = new RuleContainer
            {
                Interface = negationRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            Object.DestroyImmediate(invalidSurface);
            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator InvalidSurfaceDueToTargetPointValidity()
        {
            Physics.autoSimulation = true;

            GameObject invalidSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            invalidSurface.transform.position = Vector3.forward * 5f;
            invalidSurface.AddComponent<RuleStub>();
            NegationRule negationRule = invalidSurface.AddComponent<NegationRule>();
            Vector3RuleStub vector3Point = invalidSurface.AddComponent<Vector3RuleStub>();
            vector3Point.toMatch = invalidSurface.transform.position - (Vector3.forward * invalidSurface.transform.localScale.z * 0.5f);
            yield return null;

            negationRule.Rule = new RuleContainer
            {
                Interface = vector3Point
            };
            subject.TargetPointValidity = new RuleContainer
            {
                Interface = negationRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();

            yield return waitForFixedUpdate;
            Assert.IsFalse(surfaceLocatedMock.Received);
            Assert.IsNull(subject.surfaceData.Transform);

            Object.DestroyImmediate(invalidSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator ValidSurfaceDueToTargetPointValidity()
        {
            Physics.autoSimulation = true;

            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 5f;
            Vector3RuleStub vector3Point = validSurface.AddComponent<Vector3RuleStub>();
            vector3Point.toMatch = validSurface.transform.position - (Vector3.forward * validSurface.transform.localScale.z * 0.5f);
            yield return null;

            subject.TargetPointValidity = new RuleContainer
            {
                Interface = vector3Point
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.AreEqual(validSurface.transform, subject.surfaceData.Transform);

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator MissingSurfaceDueToLocatorTermination()
        {
            Physics.autoSimulation = true;

            GameObject terminatingSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            terminatingSurface.transform.position = Vector3.forward * 5f;
            terminatingSurface.AddComponent<RuleStub>();

            AnyComponentTypeRule anyComponentTypeRule = terminatingSurface.AddComponent<AnyComponentTypeRule>();
            SerializableTypeComponentObservableList rules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeRule.ComponentTypes = rules;
            rules.Add(typeof(RuleStub));

            subject.LocatorTermination = new RuleContainer
            {
                Interface = anyComponentTypeRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsFalse(surfaceLocatedMock.Received);
            Assert.IsNull(subject.surfaceData.Transform);

            Object.DestroyImmediate(terminatingSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator NoSurfaceDueToLocatorTermination()
        {
            Physics.autoSimulation = true;

            GameObject terminatingSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 10f;
            terminatingSurface.transform.position = Vector3.forward * 5f;
            terminatingSurface.AddComponent<RuleStub>();

            AnyComponentTypeRule anyComponentTypeRule = terminatingSurface.AddComponent<AnyComponentTypeRule>();
            SerializableTypeComponentObservableList rules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeRule.ComponentTypes = rules;
            rules.Add(typeof(RuleStub));

            subject.LocatorTermination = new RuleContainer
            {
                Interface = anyComponentTypeRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsFalse(surfaceLocatedMock.Received);
            Assert.IsNull(subject.surfaceData.Transform);

            Object.DestroyImmediate(terminatingSurface);
            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator NoSurfaceDueToLocatorTerminationWithMidInvalidTarget()
        {
            Physics.autoSimulation = true;

            GameObject invalidSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject terminatingSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 15f;
            terminatingSurface.transform.position = Vector3.forward * 10f;
            terminatingSurface.AddComponent<RuleStub>();

            AnyComponentTypeRule anyComponentTypeLocatorTerminationRule = terminatingSurface.AddComponent<AnyComponentTypeRule>();
            SerializableTypeComponentObservableList locatorTerminationRules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeLocatorTerminationRule.ComponentTypes = locatorTerminationRules;
            locatorTerminationRules.Add(typeof(RuleStub));

            subject.LocatorTermination = new RuleContainer
            {
                Interface = anyComponentTypeLocatorTerminationRule
            };

            yield return null;

            invalidSurface.transform.position = Vector3.forward * 5f;
            invalidSurface.AddComponent<AudioListener>();
            NegationRule negationRule = invalidSurface.AddComponent<NegationRule>();
            AnyComponentTypeRule anyComponentTypeTargetValidityRule = invalidSurface.AddComponent<AnyComponentTypeRule>();
            SerializableTypeComponentObservableList targetValidityRules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeTargetValidityRule.ComponentTypes = targetValidityRules;
            targetValidityRules.Add(typeof(AudioListener));

            negationRule.Rule = new RuleContainer
            {
                Interface = anyComponentTypeTargetValidityRule
            };
            subject.TargetValidity = new RuleContainer
            {
                Interface = negationRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsFalse(surfaceLocatedMock.Received);
            Assert.IsNull(subject.surfaceData.Transform);

            Object.DestroyImmediate(invalidSurface);
            Object.DestroyImmediate(terminatingSurface);
            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [Test]
        public void EventsNotEmittedOnInactiveGameObject()
        {
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 5f;

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;
            subject.gameObject.SetActive(false);
            Physics.Simulate(Time.fixedDeltaTime);
            subject.Process();

            Assert.IsFalse(surfaceLocatedMock.Received);

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [Test]
        public void EventsNotEmittedOnDisabledComponent()
        {
            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.transform.position = Vector3.forward * 5f;

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;
            subject.enabled = false;
            Physics.Simulate(Time.fixedDeltaTime);
            subject.Process();

            Assert.IsFalse(surfaceLocatedMock.Received);

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(searchOrigin);
        }

        [UnityTest]
        public IEnumerator NearestSurface()
        {
            Physics.autoSimulation = true;

            GameObject validSurface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject validSurface2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
            GameObject searchOrigin = new GameObject("SearchOrigin");
            validSurface.name = "validSurface";
            validSurface2.name = "validSurface2";

            UnityEventListenerMock surfaceLocatedMock = new UnityEventListenerMock();
            subject.SurfaceLocated.AddListener(surfaceLocatedMock.Listen);

            validSurface.AddComponent<RuleStub>();
            AnyComponentTypeRule anyComponentTypeRule = validSurface.AddComponent<AnyComponentTypeRule>();
            validSurface2.AddComponent<RuleStub>();

            SerializableTypeComponentObservableList rules = containingObject.AddComponent<SerializableTypeComponentObservableList>();
            yield return null;

            anyComponentTypeRule.ComponentTypes = rules;
            rules.Add(typeof(RuleStub));

            subject.TargetValidity = new RuleContainer
            {
                Interface = anyComponentTypeRule
            };

            subject.SearchOrigin = searchOrigin;
            subject.SearchDirection = Vector3.forward;

            validSurface.transform.position = Vector3.forward * 5f;
            validSurface2.transform.position = Vector3.forward * 4.9f;
            GameObject nearestSurface = validSurface2;

            yield return waitForFixedUpdate;
            subject.Locate();
            yield return waitForFixedUpdate;
            Assert.IsTrue(surfaceLocatedMock.Received);
            Assert.IsTrue(nearestSurface.transform == subject.surfaceData.Transform, "The returned surfaceData.Transform is not the nearest");

            Object.DestroyImmediate(validSurface);
            Object.DestroyImmediate(validSurface2);
            Object.DestroyImmediate(searchOrigin);
        }
    }
}


import {MigrationInterface, QueryRunner} from "typeorm";

export class userDeathDateTypeFix1566466897538 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "deathtime"`);
        await queryRunner.query(`ALTER TABLE "users" ADD "deathtime" TIME`);
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "deathtime"`);
        await queryRunner.query(`ALTER TABLE "users" ADD "deathtime" TIME WITH TIME ZONE`);
    }

}


//
//  DCValueConverter.h
//  DCKeyValueObjectMapping
//
//  Created by Diego Chohfi on 4/13/12.
//  Copyright (c) 2012 None. All rights reserved.
//

#import <Foundation/Foundation.h>

@class DCDynamicAttribute, DCParserConfiguration;

@protocol DCValueConverter <NSObject>

@required
- (id)transformValue:(id)value forDynamicAttribute:(DCDynamicAttribute *)attribute dictionary:(NSDictionary *)dictionary parentObject:(id)parentObject;
- (id)serializeValue:(id)value forDynamicAttribute:(DCDynamicAttribute *)attribute;
- (BOOL)canTransformValueForClass:(Class)cls;

@end


// run-pass
#![allow(dead_code)]
// Test that this fairly specialized, but also reasonable, pattern
// typechecks. The pattern involves regions bound in closures that
// wind up related to inference variables.
//
// NB. Changes to the region implementations have broken this pattern
// a few times, but it happens to be used in the compiler so those
// changes were caught. However, those uses in the compiler could
// easily get changed or refactored away in the future.

#![feature(box_syntax)]

struct Ctxt<'tcx> {
    x: &'tcx Vec<isize>
}

struct Foo<'a,'tcx:'a> {
    cx: &'a Ctxt<'tcx>,
}

impl<'a,'tcx> Foo<'a,'tcx> {
    fn bother(&mut self) -> isize {
        self.elaborate_bounds(Box::new(|this| {
            // (*) Here: type of `this` is `&'f0 Foo<&'f1, '_2>`,
            // where `'f0` and `'f1` are fresh, free regions that
            // result from the bound regions on the closure, and `'2`
            // is a region inference variable created by the call. Due
            // to the constraints on the type, we find that `'_2 : 'f1
            // + 'f2` must hold (and can be assumed by the callee).
            // Region inference has to do some clever stuff to avoid
            // inferring `'_2` to be `'static` in this case, because
            // it is created outside the closure but then related to
            // regions bound by the closure itself. See the
            // `region_constraints.rs` file (and the `givens` field, in
            // particular) for more details.
            this.foo()
        }))
    }

    fn foo(&mut self) -> isize {
        22
    }

    fn elaborate_bounds(
        &mut self,
        mut mk_cand: Box<dyn for<'b> FnMut(&mut Foo<'b, 'tcx>) -> isize>)
        -> isize
    {
        mk_cand(self)
    }
}

fn main() {
    let v = vec![];
    let cx = Ctxt { x: &v };
    let mut foo = Foo { cx: &cx };
    assert_eq!(foo.bother(), 22); // just so the code is not dead, basically
}


export NODE_ENV="development" && ./scripts/start-emulator.sh

pushd android; rm -rf ./.gradle && ./gradlew --configure-on-demand; popd

export NODE_ENV="development" && ./scripts/start-simulator.sh

export NODE_ENV="test" && ./scripts/start-simulator.sh

export NODE_ENV="test" && ./scripts/start-emulator.sh

EXPO_WEB_E2E_ENV=development jest -c e2e/jest.config.web.json

EXPO_WEB_E2E_ENV=production jest -c e2e/jest.config.web.json

open -a /Applications/Android\ Studio.app ./android

open -a Xcode ./ios/BareExpo.xcworkspace

watchman watch-del-all && rm -rf /tmp/metro-bundler-cache-* && rm -rf /tmp/haste-map-react-native-packager-*

rm -rf ios/build/; kill $(lsof -t -i:8081)

detox clean-framework-cache && detox build-framework-cache

detox test -c android.emu.debug --loglevel warn

watchman watch-del-all; detox test -c android.emu.release -l verbose --cleanup

detox test -c ios.sim.debug --loglevel warn --take-screenshots failing

watchman watch-del-all; detox test -c ios.sim.release -l verbose --cleanup --take-screenshots failing

rm -rf node_modules; rm -rf ios/Pods/ && rm -rf ios/build/ && rm -rf android/.gradle

cp -a ../../../react-native/React/DevSupport/ ../../react-native-lab/react-native/React/DevSupport/

expo-branch expo-camera expo-face-detector unimodules-face-detector-interface expo-payments-stripe expo-ads-facebook expo-ads-admob expo-apple-authentication expo-updates expo-splash-screen expo-module-template

bare-expo

cd android && ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug && cd ..

cd android && ./gradlew assembleRelease assembleAndroidTest -DtestBuildType=release && cd ..


/*
   Unix SMB/CIFS implementation.
   Low-level sessionid.tdb access functions
   Copyright (C) Volker Lendecke 2010

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "system/filesys.h"
#include "dbwrap/dbwrap.h"
#include "dbwrap/dbwrap_open.h"
#include "session.h"
#include "util_tdb.h"
#include "smbd/globals.h"

struct sessionid_traverse_read_state {
	int (*fn)(const char *key, struct sessionid *session,
		  void *private_data);
	void *private_data;
};

static int sessionid_traverse_read_fn(struct smbXsrv_session_global0 *global,
				      void *private_data)
{
	struct sessionid_traverse_read_state *state =
		(struct sessionid_traverse_read_state *)private_data;
	struct auth_session_info *session_info = global->auth_session_info;
	struct sessionid session = {
		.uid = -1,
		.gid = -1,
		.id_num = global->session_global_id,
		.connect_start = nt_time_to_unix(global->creation_time),
		.pid = global->channels[0].server_id,
		.connection_dialect = global->connection_dialect,
	};

	if (session_info != NULL) {
		session.uid = session_info->unix_token->uid;
		session.gid = session_info->unix_token->gid;
		strncpy(session.username,
			session_info->unix_info->unix_name,
			sizeof(fstring)-1);
	}

	strncpy(session.remote_machine,
		global->channels[0].remote_name,
		sizeof(fstring)-1);
	strncpy(session.hostname,
		global->channels[0].remote_address,
		sizeof(fstring)-1);
	strncpy(session.netbios_name,
		global->channels[0].remote_name,
		sizeof(fstring)-1);
	snprintf(session.id_str, sizeof(fstring)-1,
		 "smb/%u", global->session_global_id);
	strncpy(session.ip_addr_str,
		global->channels[0].remote_address,
		sizeof(fstring)-1);

	session.encryption_flags = global->encryption_flags;
	session.cipher = global->channels[0].encryption_cipher;
	session.signing_flags = global->signing_flags;

	return state->fn(NULL, &session, state->private_data);
}

NTSTATUS sessionid_traverse_read(int (*fn)(const char *key,
					  struct sessionid *session,
					  void *private_data),
				 void *private_data)
{
	struct sessionid_traverse_read_state state;
	NTSTATUS status;

	state.fn = fn;
	state.private_data = private_data;
	status = smbXsrv_session_global_traverse(sessionid_traverse_read_fn,
						 &state);

	return status;
}


/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v1

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

func addConversionFuncs(scheme *runtime.Scheme) error {
	// Add non-generated conversion functions here. Currently there are none.
	return nil
}


CC  = clang$(TOOLCHAIN_SUFFIX)
CXX = clang++$(TOOLCHAIN_SUFFIX)
LD  = clang++$(TOOLCHAIN_SUFFIX)
AR  = ar$(TOOLCHAIN_SUFFIX)

ifneq ($(STDCXX),)
CXXFLAGS_STDCXX = -std=$(STDCXX)
else
ifeq ($(shell printf '\n' > bin/empty.cpp ; if $(CXX) -std=c++17 -c bin/empty.cpp -o bin/empty.out > /dev/null 2>&1 ; then echo 'c++17' ; fi ), c++17)
CXXFLAGS_STDCXX = -std=c++17
else
ifeq ($(shell printf '\n' > bin/empty.cpp ; if $(CXX) -std=c++14 -c bin/empty.cpp -o bin/empty.out > /dev/null 2>&1 ; then echo 'c++14' ; fi ), c++14)
CXXFLAGS_STDCXX = -std=c++14
else
ifeq ($(shell printf '\n' > bin/empty.cpp ; if $(CXX) -std=c++11 -c bin/empty.cpp -o bin/empty.out > /dev/null 2>&1 ; then echo 'c++11' ; fi ), c++11)
CXXFLAGS_STDCXX = -std=c++11
endif
endif
endif
endif
CFLAGS_STDC = -std=c99
CXXFLAGS += $(CXXFLAGS_STDCXX)
CFLAGS += $(CFLAGS_STDC)

CPPFLAGS +=
CXXFLAGS += -fPIC
CFLAGS   += -fPIC
LDFLAGS  +=
LDLIBS   += -lm
ARFLAGS  := rcs

ifeq ($(CHECKED_ADDRESS),1)
CXXFLAGS += -fsanitize=address
CFLAGS   += -fsanitize=address
endif

ifeq ($(CHECKED_UNDEFINED),1)
CXXFLAGS += -fsanitize=undefined
CFLAGS   += -fsanitize=undefined
endif

CXXFLAGS_WARNINGS += -Wmissing-declarations -Wshift-count-negative -Wshift-count-overflow -Wshift-overflow -Wshift-sign-overflow -Wshift-op-parentheses
CFLAGS_WARNINGS   += -Wmissing-prototypes   -Wshift-count-negative -Wshift-count-overflow -Wshift-overflow -Wshift-sign-overflow -Wshift-op-parentheses

#CXXFLAGS_WARNINGS += -Wdocumentation
#CXXFLAGS_WARNINGS += -Wconversion
#CXXFLAGS_WARNINGS += -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-shadow -Wno-sign-conversion -Wno-weak-vtables

ifeq ($(MODERN),1)
LDFLAGS  += -fuse-ld=lld
CXXFLAGS_WARNINGS += -Wpedantic -Wframe-larger-than=20000
#CXXFLAGS_WARNINGS += -Wdouble-promotion -Wframe-larger-than=16000
CFLAGS_WARNINGS   += -Wpedantic -Wframe-larger-than=4000
#CFLAGS_WARNINGS   += -Wdouble-promotion
LDFLAGS_WARNINGS  += -Wl,-no-undefined -Wl,--detect-odr-violations
CXXFLAGS_WARNINGS += -Wdeprecated -Wextra-semi -Wnon-virtual-dtor -Wreserved-id-macro
endif

CFLAGS_SILENT += -Wno-unused-parameter -Wno-unused-function -Wno-cast-qual

EXESUFFIX=


# -*- coding: utf-8 -*-

# Copyright 2010 Dirk Holtwick, holtwick.it
#
# 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.

from hashlib import md5
from reportlab.lib.enums import TA_RIGHT
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.utils import flatten, open_for_read, getStringIO, \
    LazyImageReader, haveImages
from reportlab.platypus.doctemplate import BaseDocTemplate, PageTemplate, IndexingFlowable
from reportlab.platypus.flowables import Flowable, CondPageBreak, \
    KeepInFrame, ParagraphAndImage
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.platypus.tables import Table, TableStyle
from xhtml2pdf.reportlab_paragraph import Paragraph
from xhtml2pdf.util import getUID, getBorderStyle
from types import StringType, TupleType, ListType, IntType
import StringIO
import cgi
import copy
import logging
import reportlab.pdfbase.pdfform as pdfform
import sys

try:
    import PIL.Image as PILImage
except:
    try:
        import Image as PILImage
    except:
        PILImage = None

log = logging.getLogger("xhtml2pdf")

MAX_IMAGE_RATIO = 0.95

class PTCycle(list):
    def __init__(self):
        self._restart = 0
        self._idx = 0
        list.__init__(self)

    def cyclicIterator(self):
        while 1:
            yield self[self._idx]
            self._idx += 1
            if self._idx >= len(self):
                self._idx = self._restart

class PmlMaxHeightMixIn:
    def setMaxHeight(self, availHeight):
        self.availHeightValue = availHeight
        if availHeight < 70000:
            if hasattr(self, "canv"):
                if not hasattr(self.canv, "maxAvailHeightValue"):
                    self.canv.maxAvailHeightValue = 0
                self.availHeightValue = self.canv.maxAvailHeightValue = max(
                    availHeight,
                    self.canv.maxAvailHeightValue)
        else:
            self.availHeightValue = availHeight
        if not hasattr(self, "availHeightValue"):
            self.availHeightValue = 0
        return self.availHeightValue

    def getMaxHeight(self):
        if not hasattr(self, "availHeightValue"):
            return 0
        return self.availHeightValue

class PmlBaseDoc(BaseDocTemplate):
    """
    We use our own document template to get access to the canvas
    and set some informations once.
    """

    def beforePage(self):

        # Tricky way to set producer, because of not real privateness in Python
        info = "pisa HTML to PDF <http://www.htmltopdf.org>"
        self.canv._doc.info.producer = info

        '''
        # Convert to ASCII because there is a Bug in Reportlab not
        # supporting other than ASCII. Send to list on 23.1.2007

        author = toString(self.pml_data.get("author", "")).encode("ascii","ignore")
        subject = toString(self.pml_data.get("subject", "")).encode("ascii","ignore")
        title = toString(self.pml_data.get("title", "")).encode("ascii","ignore")
        # print repr((author,title,subject))

        self.canv.setAuthor(author)
        self.canv.setSubject(subject)
        self.canv.setTitle(title)

        if self.pml_data.get("fullscreen", 0):
            self.canv.showFullScreen0()

        if self.pml_data.get("showoutline", 0):
            self.canv.showOutline()

        if self.pml_data.get("duration", None) is not None:
            self.canv.setPageDuration(self.pml_data["duration"])
        '''

    def afterFlowable(self, flowable):
        # Does the flowable contain fragments?
        if getattr(flowable, "outline", False):
            self.notify('TOCEntry', (
                flowable.outlineLevel,
                cgi.escape(copy.deepcopy(flowable.text), 1),
                self.page))

    def handle_nextPageTemplate(self, pt):
        '''
        if pt has also templates for even and odd page convert it to list
        '''
        has_left_template = self._has_template_for_name(pt + '_left')
        has_right_template = self._has_template_for_name(pt + '_right')

        if has_left_template and has_right_template:
            pt = [pt + '_left', pt + '_right']

        '''On endPage change to the page template with name or index pt'''
        if type(pt) is StringType:
            if hasattr(self, '_nextPageTemplateCycle'):
                del self._nextPageTemplateCycle
            for t in self.pageTemplates:
                if t.id == pt:
                    self._nextPageTemplateIndex = self.pageTemplates.index(t)
                    return
            raise ValueError("can't find template('%s')" % pt)
        elif type(pt) is IntType:
            if hasattr(self, '_nextPageTemplateCycle'):
                del self._nextPageTemplateCycle
            self._nextPageTemplateIndex = pt
        elif type(pt) in (ListType, TupleType):
            #used for alternating left/right pages
            #collect the refs to the template objects, complain if any are bad
            c = PTCycle()
            for ptn in pt:
            #special case name used to short circuit the iteration
                if ptn == '*':
                    c._restart = len(c)
                    continue
                for t in self.pageTemplates:
                    if t.id == ptn.strip():
                        c.append(t)
                        break
            if not c:
                raise ValueError("No valid page templates in cycle")
            elif c._restart > len(c):
                raise ValueError("Invalid cycle restart position")

            #ensure we start on the first one$
            self._nextPageTemplateCycle = c.cyclicIterator()
        else:
            raise TypeError("Argument pt should be string or integer or list")

    def _has_template_for_name(self, name):
        for template in self.pageTemplates:
            if template.id == name.strip():
                return True
        return False

class PmlPageTemplate(PageTemplate):
    PORTRAIT = 'portrait'
    LANDSCAPE = 'landscape'
    # by default portrait
    pageorientation = PORTRAIT

    def __init__(self, **kw):
        self.pisaStaticList = []
        self.pisaBackgroundList = []
        self.pisaBackground = None
        PageTemplate.__init__(self, **kw)
        self._page_count = 0
        self._first_flow = True

    def isFirstFlow(self, canvas):
        if self._first_flow:
            if canvas.getPageNumber() <= self._page_count:
                self._first_flow = False
            else:
                self._page_count = canvas.getPageNumber()
                canvas._doctemplate._page_count = canvas.getPageNumber()
        return self._first_flow

    def isPortrait(self):
        return self.pageorientation == self.PORTRAIT

    def isLandscape(self):
        return self.pageorientation == self.LANDSCAPE

    def beforeDrawPage(self, canvas, doc):
        canvas.saveState()
        try:

            # Background
            pisaBackground = None
            if (self.isFirstFlow(canvas)
                and hasattr(self, "pisaBackground")
                and self.pisaBackground
                and (not self.pisaBackground.notFound())):

                # Is image not PDF
                if self.pisaBackground.mimetype.startswith("image/"):

                    try:
                        img = PmlImageReader(StringIO.StringIO(self.pisaBackground.getData()))
                        iw, ih = img.getSize()
                        pw, ph = canvas._pagesize

                        width = pw  # min(iw, pw) # max
                        wfactor = float(width) / iw
                        height = ph  # min(ih, ph) # max
                        hfactor = float(height) / ih
                        factor_min = min(wfactor, hfactor)

                        if self.isPortrait():
                            w = iw * factor_min
                            h = ih * factor_min
                            canvas.drawImage(img, 0, ph - h, w, h)
                        elif self.isLandscape():
                            factor_max = max(wfactor, hfactor)
                            h = ih * factor_max
                            w = iw * factor_min
                            canvas.drawImage(img, 0, 0, w, h)
                    except:
                        log.exception("Draw background")

                # PDF!
                else:
                    pisaBackground = self.pisaBackground

            if pisaBackground:
                self.pisaBackgroundList.append(pisaBackground)

            def pageNumbering(objList):
                for obj in flatten(objList):
                    if isinstance(obj, PmlParagraph):
                        for frag in obj.frags:
                            if frag.pageNumber:
                                frag.text = str(pagenumber)
                            elif frag.pageCount:
                                frag.text = str(canvas._doctemplate._page_count)

                    elif isinstance(obj, PmlTable):
                        # Flatten the cells ([[1,2], [3,4]] becomes [1,2,3,4])
                        flat_cells = [item for sublist in obj._cellvalues for item in sublist]
                        pageNumbering(flat_cells)

            try:

                # Paint static frames
                pagenumber = canvas.getPageNumber()
                for frame in self.pisaStaticList:
                    frame = copy.deepcopy(frame)
                    story = frame.pisaStaticStory
                    pageNumbering(story)

                    frame.addFromList(story, canvas)

            except Exception:  # TODO: Kill this!
                log.debug("PmlPageTemplate", exc_info=1)
        finally:
            canvas.restoreState()

_ctr = 1

class PmlImageReader(object):  # TODO We need a factory here, returning either a class for java or a class for PIL
    """
    Wraps up either PIL or Java to get data from bitmaps
    """
    _cache = {}

    def __init__(self, fileName):
        if isinstance(fileName, PmlImageReader):
            self.__dict__ = fileName.__dict__   # borgize
            return
            #start wih lots of null private fields, to be populated by
        #the relevant engine.
        self.fileName = fileName
        self._image = None
        self._width = None
        self._height = None
        self._transparent = None
        self._data = None
        imageReaderFlags = 0
        if PILImage and isinstance(fileName, PILImage.Image):
            self._image = fileName
            self.fp = getattr(fileName, 'fp', None)
            try:
                self.fileName = self._image.fileName
            except AttributeError:
                self.fileName = 'PILIMAGE_%d' % id(self)
        else:
            try:
                self.fp = open_for_read(fileName, 'b')
                if isinstance(self.fp, StringIO.StringIO().__class__):
                    imageReaderFlags = 0  # avoid messing with already internal files
                if imageReaderFlags > 0:  # interning
                    data = self.fp.read()
                    if imageReaderFlags & 2:  # autoclose
                        try:
                            self.fp.close()
                        except:
                            pass
                    if imageReaderFlags & 4:  # cache the data
                        if not self._cache:
                            from rl_config import register_reset
                            register_reset(self._cache.clear)

                        data = self._cache.setdefault(md5(data).digest(), data)
                    self.fp = getStringIO(data)
                elif imageReaderFlags == - 1 and isinstance(fileName, (str, unicode)):
                    #try Ralf Schmitt's re-opening technique of avoiding too many open files
                    self.fp.close()
                    del self.fp  # will become a property in the next statement
                    self.__class__ = LazyImageReader
                if haveImages:
                    #detect which library we are using and open the image
                    if not self._image:
                        self._image = self._read_image(self.fp)
                    if getattr(self._image, 'format', None) == 'JPEG':
                        self.jpeg_fh = self._jpeg_fh
                else:
                    from reportlab.pdfbase.pdfutils import readJPEGInfo

                    try:
                        self._width, self._height, c = readJPEGInfo(self.fp)
                    except:
                        raise RuntimeError('Imaging Library not available, unable to import bitmaps only jpegs')
                    self.jpeg_fh = self._jpeg_fh
                    self._data = self.fp.read()
                    self._dataA = None
                    self.fp.seek(0)
            except:  # TODO: Kill the catch-all
                et, ev, tb = sys.exc_info()
                if hasattr(ev, 'args'):
                    a = str(ev.args[- 1]) + (' fileName=%r' % fileName)
                    ev.args = ev.args[: - 1] + (a,)
                    raise et, ev, tb
                else:
                    raise

    def _read_image(self, fp):
        if sys.platform[0:4] == 'java':
            from javax.imageio import ImageIO
            from java.io import ByteArrayInputStream
            input_stream = ByteArrayInputStream(fp.read())
            return ImageIO.read(input_stream)
        elif PILImage:
            return PILImage.open(fp)

    def _jpeg_fh(self):
        fp = self.fp
        fp.seek(0)
        return fp

    def jpeg_fh(self):
        return None

    def getSize(self):
        if self._width is None or self._height is None:
            if sys.platform[0:4] == 'java':
                self._width = self._image.getWidth()
                self._height = self._image.getHeight()
            else:
                self._width, self._height = self._image.size
        return self._width, self._height

    def getRGBData(self):
        "Return byte array of RGB data as string"
        if self._data is None:
            self._dataA = None
            if sys.platform[0:4] == 'java':
                import jarray  # TODO: Move to top.
                from java.awt.image import PixelGrabber

                width, height = self.getSize()
                buffer = jarray.zeros(width * height, 'i')
                pg = PixelGrabber(self._image, 0, 0, width, height, buffer, 0, width)
                pg.grabPixels()
                # there must be a way to do this with a cast not a byte-level loop,
                # I just haven't found it yet...
                pixels = []
                a = pixels.append
                for rgb in buffer:
                    a(chr((rgb >> 16) & 0xff))
                    a(chr((rgb >> 8) & 0xff))
                    a(chr(rgb & 0xff))
                self._data = ''.join(pixels)
                self.mode = 'RGB'
            else:
                im = self._image
                mode = self.mode = im.mode
                if mode == 'RGBA':
                    im.load()
                    self._dataA = PmlImageReader(im.split()[3])
                    im = im.convert('RGB')
                    self.mode = 'RGB'
                elif mode not in ('L', 'RGB', 'CMYK'):
                    im = im.convert('RGB')
                    self.mode = 'RGB'
                if hasattr(im, 'tobytes'):
                    self._data = im.tobytes()
                else:
                    # PIL compatibility
                    self._data = im.tostring()
        return self._data

    def getImageData(self):
        width, height = self.getSize()
        return width, height, self.getRGBData()

    def getTransparent(self):
        if sys.platform[0:4] == 'java':
            return None
        elif "transparency" in self._image.info:
            transparency = self._image.info["transparency"] * 3
            palette = self._image.palette
            if hasattr(palette, 'palette'):
                palette = palette.palette
            elif hasattr(palette, 'data'):
                palette = palette.data
            else:
                return None

            # 8-bit PNGs could give an empty string as transparency value, so
            # we have to be careful here.
            try:
                return map(ord, palette[transparency:transparency + 3])
            except:
                return None
        else:
            return None

    def __str__(self):
        try:
            fn = self.fileName.read()
            if not fn:
                fn = id(self)
            return "PmlImageObject_%s" % hash(fn)
        except:
            fn = self.fileName
            if not fn:
                fn = id(self)
            return fn

class PmlImage(Flowable, PmlMaxHeightMixIn):

    def __init__(self, data, width=None, height=None, mask="auto", mimetype=None, **kw):
        self.kw = kw
        self.hAlign = 'CENTER'
        self._mask = mask
        self._imgdata = data
        # print "###", repr(data)
        self.mimetype = mimetype
        img = self.getImage()
        if img:
            self.imageWidth, self.imageHeight = img.getSize()
        self.drawWidth = width or self.imageWidth
        self.drawHeight = height or self.imageHeight

    def wrap(self, availWidth, availHeight):
        " This can be called more than once! Do not overwrite important data like drawWidth "
        availHeight = self.setMaxHeight(availHeight)
        # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight
        width = min(self.drawWidth, availWidth)
        wfactor = float(width) / self.drawWidth
        height = min(self.drawHeight, availHeight * MAX_IMAGE_RATIO)
        hfactor = float(height) / self.drawHeight
        factor = min(wfactor, hfactor)
        self.dWidth = self.drawWidth * factor
        self.dHeight = self.drawHeight * factor
        # print "imgage result", factor, self.dWidth, self.dHeight
        return self.dWidth, self.dHeight

    def getImage(self):
        img = PmlImageReader(StringIO.StringIO(self._imgdata))
        return img

    def draw(self):
        img = self.getImage()
        self.canv.drawImage(
            img,
            0, 0,
            self.dWidth,
            self.dHeight,
            mask=self._mask)

    def identity(self, maxLen=None):
        r = Flowable.identity(self, maxLen)
        return r

class PmlParagraphAndImage(ParagraphAndImage, PmlMaxHeightMixIn):
    def wrap(self, availWidth, availHeight):
        self.I.canv = self.canv
        result = ParagraphAndImage.wrap(self, availWidth, availHeight)
        del self.I.canv
        return result

    def split(self, availWidth, availHeight):
        # print "# split", id(self)
        if not hasattr(self, "wI"):
            self.wI, self.hI = self.I.wrap(availWidth, availHeight)  # drawWidth, self.I.drawHeight
        return ParagraphAndImage.split(self, availWidth, availHeight)

class PmlParagraph(Paragraph, PmlMaxHeightMixIn):
    def _calcImageMaxSizes(self, availWidth, availHeight):
        self.hasImages = False
        for frag in self.frags:
            if hasattr(frag, "cbDefn") and frag.cbDefn.kind == "img":
                img = frag.cbDefn
                if img.width > 0 and img.height > 0:
                    self.hasImages = True
                    width = min(img.width, availWidth)
                    wfactor = float(width) / img.width
                    height = min(img.height, availHeight * MAX_IMAGE_RATIO)  # XXX 99% because 100% do not work...
                    hfactor = float(height) / img.height
                    factor = min(wfactor, hfactor)
                    img.height *= factor
                    img.width *= factor

    def wrap(self, availWidth, availHeight):

        availHeight = self.setMaxHeight(availHeight)

        style = self.style

        self.deltaWidth = style.paddingLeft + style.paddingRight + style.borderLeftWidth + style.borderRightWidth
        self.deltaHeight = style.paddingTop + style.paddingBottom + style.borderTopWidth + style.borderBottomWidth

        # reduce the available width & height by the padding so the wrapping
        # will use the correct size
        availWidth -= self.deltaWidth
        availHeight -= self.deltaHeight

        # Modify maxium image sizes
        self._calcImageMaxSizes(availWidth, availHeight)

        # call the base class to do wrapping and calculate the size
        Paragraph.wrap(self, availWidth, availHeight)

        #self.height = max(1, self.height)
        #self.width = max(1, self.width)

        # increase the calculated size by the padding
        self.width = self.width + self.deltaWidth
        self.height = self.height + self.deltaHeight

        return self.width, self.height

    def split(self, availWidth, availHeight):

        if len(self.frags) <= 0:
            return []

        #the split information is all inside self.blPara
        if not hasattr(self, 'deltaWidth'):
            self.wrap(availWidth, availHeight)

        availWidth -= self.deltaWidth
        availHeight -= self.deltaHeight

        return Paragraph.split(self, availWidth, availHeight)

    def draw(self):

        # Create outline
        if getattr(self, "outline", False):

            # Check level and add all levels
            last = getattr(self.canv, "outlineLast", - 1) + 1
            while last < self.outlineLevel:
                # print "(OUTLINE",  last, self.text
                key = getUID()
                self.canv.bookmarkPage(key)
                self.canv.addOutlineEntry(
                    self.text,
                    key,
                    last,
                    not self.outlineOpen)
                last += 1
            self.canv.outlineLast = self.outlineLevel

            key = getUID()

            self.canv.bookmarkPage(key)
            self.canv.addOutlineEntry(
                self.text,
                key,
                self.outlineLevel,
                not self.outlineOpen)
            last += 1

        # Draw the background and borders here before passing control on to
        # ReportLab. This is because ReportLab can't handle the individual
        # components of the border independently. This will also let us
        # support more border styles eventually.
        canvas = self.canv
        style = self.style
        bg = style.backColor
        leftIndent = style.leftIndent
        bp = 0  # style.borderPadding

        x = leftIndent - bp
        y = - bp
        w = self.width - (leftIndent + style.rightIndent) + 2 * bp
        h = self.height + 2 * bp

        if bg:
            # draw a filled rectangle (with no stroke) using bg color
            canvas.saveState()
            canvas.setFillColor(bg)
            canvas.rect(x, y, w, h, fill=1, stroke=0)
            canvas.restoreState()

        # we need to hide the bg color (if any) so Paragraph won't try to draw it again
        style.backColor = None

        # offset the origin to compensate for the padding
        canvas.saveState()
        canvas.translate(
            (style.paddingLeft + style.borderLeftWidth),
            -1 * (style.paddingTop + style.borderTopWidth))  # + (style.leading / 4)))

        # Call the base class draw method to finish up
        Paragraph.draw(self)
        canvas.restoreState()

        # Reset color because we need it again if we run 2-PASS like we
        # do when using TOC
        style.backColor = bg

        canvas.saveState()

        def _drawBorderLine(bstyle, width, color, x1, y1, x2, y2):
            # We need width and border style to be able to draw a border
            if width and getBorderStyle(bstyle):
                # If no color for border is given, the text color is used (like defined by W3C)
                if color is None:
                    color = style.textColor
                    # print "Border", bstyle, width, color
                if color is not None:
                    canvas.setStrokeColor(color)
                    canvas.setLineWidth(width)
                    canvas.line(x1, y1, x2, y2)

        _drawBorderLine(style.borderLeftStyle,
                        style.borderLeftWidth,
                        style.borderLeftColor,
                        x, y, x, y + h)
        _drawBorderLine(style.borderRightStyle,
                        style.borderRightWidth,
                        style.borderRightColor,
                        x + w, y, x + w, y + h)
        _drawBorderLine(style.borderTopStyle,
                        style.borderTopWidth,
                        style.borderTopColor,
                        x, y + h, x + w, y + h)
        _drawBorderLine(style.borderBottomStyle,
                        style.borderBottomWidth,
                        style.borderBottomColor,
                        x, y, x + w, y)

        canvas.restoreState()

class PmlKeepInFrame(KeepInFrame, PmlMaxHeightMixIn):
    def wrap(self, availWidth, availHeight):
        availWidth = max(availWidth, 1.0)
        availHeight = max(availHeight, 1.0)
        self.maxWidth = availWidth
        self.maxHeight = self.setMaxHeight(availHeight)
        return KeepInFrame.wrap(self, availWidth, availHeight)

class PmlTable(Table, PmlMaxHeightMixIn):
    def _normWidth(self, w, maxw):
        """
        Helper for calculating percentages
        """
        if type(w) == type(""):
            w = ((maxw / 100.0) * float(w[: - 1]))
        elif (w is None) or (w == "*"):
            w = maxw
        return min(w, maxw)

    def _listCellGeom(self, V, w, s, W=None, H=None, aH=72000):
        # print "#", self.availHeightValue
        if aH == 72000:
            aH = self.getMaxHeight() or aH
        return Table._listCellGeom(self, V, w, s, W=W, H=H, aH=aH)

    def wrap(self, availWidth, availHeight):

        self.setMaxHeight(availHeight)

        # Strange bug, sometime the totalWidth is not set !?
        try:
            self.totalWidth
        except:
            self.totalWidth = availWidth

        # Prepare values
        totalWidth = self._normWidth(self.totalWidth, availWidth)
        remainingWidth = totalWidth
        remainingCols = 0
        newColWidths = self._colWidths

        # Calculate widths that are fix
        # IMPORTANT!!! We can not substitute the private value
        # self._colWidths therefore we have to modify list in place
        for i, colWidth in enumerate(newColWidths):
            if (colWidth is not None) or (colWidth == '*'):
                colWidth = self._normWidth(colWidth, totalWidth)
                remainingWidth -= colWidth
            else:
                remainingCols += 1
                colWidth = None
            newColWidths[i] = colWidth

        # Distribute remaining space
        minCellWidth = totalWidth * 0.01
        if remainingCols > 0:
            for i, colWidth in enumerate(newColWidths):
                if colWidth is None:
                    newColWidths[i] = max(minCellWidth, remainingWidth / remainingCols)  # - 0.1

        # Bigger than totalWidth? Lets reduce the fix entries propotionally

        if sum(newColWidths) > totalWidth:
            quotient = totalWidth / sum(newColWidths)
            for i in range(len(newColWidths)):
                newColWidths[i] = newColWidths[i] * quotient

        # To avoid rounding errors adjust one col with the difference
        diff = sum(newColWidths) - totalWidth
        if diff > 0:
            newColWidths[0] -= diff

        return Table.wrap(self, availWidth, availHeight)

class PmlPageCount(IndexingFlowable):
    def __init__(self):
        IndexingFlowable.__init__(self)
        self.second_round = False

    def isSatisfied(self):
        s = self.second_round
        self.second_round = True
        return s

    def drawOn(self, canvas, x, y, _sW=0):
        pass

class PmlTableOfContents(TableOfContents):
    def wrap(self, availWidth, availHeight):
        """
        All table properties should be known by now.
        """

        widths = (availWidth - self.rightColumnWidth,
                  self.rightColumnWidth)

        # makes an internal table which does all the work.
        # we draw the LAST RUN's entries!  If there are
        # none, we make some dummy data to keep the table
        # from complaining
        if len(self._lastEntries) == 0:
            _tempEntries = [(0, 'Placeholder for table of contents', 0)]
        else:
            _tempEntries = self._lastEntries

        lastMargin = 0
        tableData = []
        tableStyle = [
            ('VALIGN', (0, 0), (- 1, - 1), 'TOP'),
            ('LEFTPADDING', (0, 0), (- 1, - 1), 0),
            ('RIGHTPADDING', (0, 0), (- 1, - 1), 0),
            ('TOPPADDING', (0, 0), (- 1, - 1), 0),
            ('BOTTOMPADDING', (0, 0), (- 1, - 1), 0),
        ]
        for i, entry in enumerate(_tempEntries):
            level, text, pageNum = entry[:3]
            leftColStyle = self.levelStyles[level]
            if i:  # Not for first element
                tableStyle.append((
                    'TOPPADDING',
                    (0, i), (- 1, i),
                    max(lastMargin, leftColStyle.spaceBefore)))
                # print leftColStyle.leftIndent
            lastMargin = leftColStyle.spaceAfter
            #right col style is right aligned
            rightColStyle = ParagraphStyle(name='leftColLevel%d' % level,
                                           parent=leftColStyle,
                                           leftIndent=0,
                                           alignment=TA_RIGHT)
            leftPara = Paragraph(text, leftColStyle)
            rightPara = Paragraph(str(pageNum), rightColStyle)
            tableData.append([leftPara, rightPara])

        self._table = Table(
            tableData,
            colWidths=widths,
            style=TableStyle(tableStyle))

        self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight)
        return self.width, self.height

class PmlRightPageBreak(CondPageBreak):
    def __init__(self):
        pass

    def wrap(self, availWidth, availHeight):
        if not self.canv.getPageNumber() % 2:
            self.width = availWidth
            self.height = availHeight
            return availWidth, availHeight
        self.width = self.height = 0
        return 0, 0

class PmlLeftPageBreak(CondPageBreak):
    def __init__(self):
        pass

    def wrap(self, availWidth, availHeight):
        if self.canv.getPageNumber() % 2:
            self.width = availWidth
            self.height = availHeight
            return availWidth, availHeight
        self.width = self.height = 0
        return 0, 0

# --- Pdf Form

class PmlInput(Flowable):
    def __init__(self, name, type="text", width=10, height=10, default="", options=[]):
        self.width = width
        self.height = height
        self.type = type
        self.name = name
        self.default = default
        self.options = options

    def wrap(self, *args):
        return self.width, self.height

    def draw(self):
        c = self.canv

        c.saveState()
        c.setFont("Helvetica", 10)
        if self.type == "text":
            pdfform.textFieldRelative(c, self.name, 0, 0, self.width, self.height)
            c.rect(0, 0, self.width, self.height)
        elif self.type == "radio":
            c.rect(0, 0, self.width, self.height)
        elif self.type == "checkbox":
            if self.default:
                pdfform.buttonFieldRelative(c, self.name, "Yes", 0, 0)
            else:
                pdfform.buttonFieldRelative(c, self.name, "Off", 0, 0)
            c.rect(0, 0, self.width, self.height)
        elif self.type == "select":
            pdfform.selectFieldRelative(c, self.name, self.default, self.options, 0, 0, self.width, self.height)
            c.rect(0, 0, self.width, self.height)

        c.restoreState()


/******************************************************************************
*                 SOFA, Simulation Open-Framework Architecture                *
*                    (c) 2006 INRIA, USTL, UJF, CNRS, MGH                     *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "OpenCLMemoryManager.h"


mach_port_set_mscount

Function - Change the target port's make-send count.

SYNOPSIS

kern_return_t   mach_port_set_mscount
                (ipc_space_t                               <var>task</var>,
                 mach_port_name_t                          <var>name</var>,
                 mach_port_mscount_t                    <var>mscount</var>);

PARAMETERS

 <var>task</var>

[in task send right]
The task owning the receive right.

 <var>name</var>

[in scalar]
<var>task</var>'s name for the receive right.

 <var>mscount</var>

[in scalar]
New value for the make-send count for the receive right.

DESCRIPTION

The mach_port_set_mscount function changes the make-send
count of <var>task</var>'s
receive right named <var>name</var>.
A port's make-send count specifies the number of send rights that have
been generated via the port's receive right.  A port's make-send count
is set to zero when the port is first allocated; the count is reset to
zero each time the port's receive right is transferred via a Mach message.

NOTES

This interface is machine word length specific because of the port name
parameter.

RETURN VALUES

 KERN_INVALID_NAME

<var>name</var> did not denote a right.

 KERN_INVALID_RIGHT

<var>name</var> denoted a right, but not a receive right.

RELATED INFORMATION

Functions:
mach_port_get_attributes.


// Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: test.fbe
// Version: 1.4.0.0

package com.chronoxor.test.fbe;

// Fast Binary Encoding EnumSimple array field model
public final class FieldModelArrayEnumSimple extends com.chronoxor.fbe.FieldModel
{
    private final FieldModelEnumSimple _model;
    private final long _size;

    public FieldModelArrayEnumSimple(com.chronoxor.fbe.Buffer buffer, long offset, long size)
    {
        super(buffer, offset);
        _model = new FieldModelEnumSimple(buffer, offset);
        _size = size;
    }

    // Get the field size
    @Override
    public long fbeSize() { return _size * _model.fbeSize(); }
    // Get the field extra size
    @Override
    public long fbeExtra() { return 0; }

    // Get the array offset
    public long getOffset() { return 0; }
    // Get the array size
    public long getSize() { return _size; }

    // Array index operator
    public FieldModelEnumSimple getItem(long index)
    {
        assert ((_buffer.getOffset() + fbeOffset() + fbeSize()) <= _buffer.getSize()) : "Model is broken!";
        assert (index < _size) : "Index is out of bounds!";

        _model.fbeOffset(fbeOffset());
        _model.fbeShift(index * _model.fbeSize());
        return _model;
    }

    // Check if the array is valid
    @Override
    public boolean verify()
    {
        if ((_buffer.getOffset() + fbeOffset() + fbeSize()) > _buffer.getSize())
            return false;

        _model.fbeOffset(fbeOffset());
        for (long i = _size; i-- > 0;)
        {
            if (!_model.verify())
                return false;
            _model.fbeShift(_model.fbeSize());
        }

        return true;
    }

    // Get the array
    public com.chronoxor.test.EnumSimple[] get()
    {
        var values = new com.chronoxor.test.EnumSimple[(int)_size];

        var fbeModel = getItem(0);
        for (long i = 0; i < _size; i++)
        {
            values[(int)i] = fbeModel.get();
            fbeModel.fbeShift(fbeModel.fbeSize());
        }
        return values;
    }

    // Get the array
    public void get(com.chronoxor.test.EnumSimple[] values)
    {
        assert (values != null) : "Invalid values parameter!";
        if (values == null)
            throw new IllegalArgumentException("Invalid values parameter!");

        var fbeModel = getItem(0);
        for (long i = 0; (i < values.length) && (i < _size); i++)
        {
            values[(int)i] = fbeModel.get();
            fbeModel.fbeShift(fbeModel.fbeSize());
        }
    }

    // Get the array as java.util.ArrayList
    public void get(java.util.ArrayList<com.chronoxor.test.EnumSimple> values)
    {
        assert (values != null) : "Invalid values parameter!";
        if (values == null)
            throw new IllegalArgumentException("Invalid values parameter!");

        values.clear();
        values.ensureCapacity((int)_size);

        var fbeModel = getItem(0);
        for (long i = _size; i-- > 0;)
        {
            com.chronoxor.test.EnumSimple value = fbeModel.get();
            values.add(value);
            fbeModel.fbeShift(fbeModel.fbeSize());
        }
    }

    // Set the array
    public void set(com.chronoxor.test.EnumSimple[] values)
    {
        assert (values != null) : "Invalid values parameter!";
        if (values == null)
            throw new IllegalArgumentException("Invalid values parameter!");

        assert ((_buffer.getOffset() + fbeOffset() + fbeSize()) <= _buffer.getSize()) : "Model is broken!";
        if ((_buffer.getOffset() + fbeOffset() + fbeSize()) > _buffer.getSize())
            return;

        var fbeModel = getItem(0);
        for (long i = 0; (i < values.length) && (i < _size); i++)
        {
            fbeModel.set(values[(int)i]);
            fbeModel.fbeShift(fbeModel.fbeSize());
        }
    }

    // Set the array as java.util.ArrayList
    public void set(java.util.ArrayList<com.chronoxor.test.EnumSimple> values)
    {
        assert (values != null) : "Invalid values parameter!";
        if (values == null)
            throw new IllegalArgumentException("Invalid values parameter!");

        assert ((_buffer.getOffset() + fbeOffset() + fbeSize()) <= _buffer.getSize()) : "Model is broken!";
        if ((_buffer.getOffset() + fbeOffset() + fbeSize()) > _buffer.getSize())
            return;

        var fbeModel = getItem(0);
        for (long i = 0; (i < values.size()) && (i < _size); i++)
        {
            fbeModel.set(values.get((int)i));
            fbeModel.fbeShift(fbeModel.fbeSize());
        }
    }
}


package li.cil.oc.api.internal;

import li.cil.oc.api.component.RackMountable;
import li.cil.oc.api.machine.MachineHost;
import li.cil.oc.api.network.EnvironmentHost;

/**
 * This interface is implemented as a marker by servers in racks.
 *

 * This is implemented by servers in server racks, which serve as their
 * computer components' environment. That means you can use this to check for
 * servers by using either:
 *

 *     if (node.host() instanceof Server) {
 *

 *

 * You can get a reference to a server either via the above cast, or via a
 * {@link li.cil.oc.api.internal.Rack#getMountable(int)}.
 *

 * The only purpose is to allow identifying node environments as servers
 * via the API, i.e. without having to link against internal classes. This
 * also means that you should not implement this.
 */
public interface Server extends EnvironmentHost, MachineHost, Tiered, RackMountable {
    /**
     * The server rack this server is in.
     */
    Rack rack();

    /**
     * The slot of the server rack this server is in.
     */
    int slot();
}


package com.dtalk.dd.protobuf.base;

import com.dtalk.dd.config.SysConstant;
import com.dtalk.dd.utils.Logger;

/**
 * TCP协议的头文件
 *
 * @author dolphinWang
 * @time 2014/04/30
 */
public class Header {

    private int length; // 数据包长度，包括包头

    private short version; // 版本号

    private short flag;

    private short serviceId; // SID

    private short commandId; // CID

    private short seqnum;

    private short reserved; // 保留，可用于如序列号等

    public Header() {

        length = 0;

        version = 0;

        serviceId = 0;

        commandId = 0;

        reserved = 0;

        flag = 0;

        seqnum = 0;

    }

    public short getFlag() {

        return flag;

    }

    public void setFlag(short flag) {

        this.flag = flag;

    }

    public short getSeqnum() {

        return seqnum;

    }

    public void setSeqnum(short seq) {

        this.seqnum = seq;

    }

    /**
     * 头文件的压包函数
     *
     * @return 数据包
     */

    public DataBuffer encode() {
        DataBuffer db = new DataBuffer(SysConstant.PROTOCOL_HEADER_LENGTH);
        db.writeInt(length);
        db.writeShort(version);
        db.writeShort(flag);
        db.writeShort(serviceId);
        db.writeShort(commandId);
        db.writeShort(seqnum);
        db.writeShort(reserved);
        return db;

    }

    /**
     * 头文件的解包函数
     *
     * @param buffer
     */

    public void decode(DataBuffer buffer) {

        if (null == buffer)
            return;
        try {
            length = buffer.readInt();
            version = buffer.readShort();
            flag = buffer.readShort();
            serviceId = buffer.readShort();
            commandId = buffer.readShort();
            seqnum = buffer.readShort();
            reserved = buffer.readShort();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    @Override

    public String toString() {

        return "Header [length=" + length + ", version=" + version + ", flag="

                + flag + ", serviceId=" + serviceId + ", commandId="

                + commandId + ", seq=" + seqnum + ", reserved=" + reserved

                + "]";
    }

    public short getCommandId() {
        return commandId;
    }

    public void setCommandId(short commandID) {
        this.commandId = commandID;
    }

    public short getServiceId() {
        return serviceId;
    }

    public void setServiceId(short serviceID) {
        this.serviceId = serviceID;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public short getVersion() {
        return version;
    }

    public void setVersion(short version) {
        this.version = version;
    }

    public int getReserved() {
        return reserved;
    }

    public void setReserved(short reserved) {
        this.reserved = reserved;
    }
}


<?xml version="1.0" ?>

<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<!-- solrconfig-basic.xml plus a queryParser element -->
<config>
  <luceneMatchVersion>${tests.luceneMatchVersion:LATEST}</luceneMatchVersion>
  <dataDir>${solr.data.dir:}</dataDir>
  <xi:include href="solrconfig.snippet.randomindexconfig.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/>
  <directoryFactory name="DirectoryFactory" class="${solr.directoryFactory:solr.RAMDirectoryFactory}"/>
  <schemaFactory class="ClassicIndexSchemaFactory"/>
  <requestHandler name="/select" class="solr.SearchHandler" />
  <queryParser name="testxmlparser" class="XmlQParserPlugin">
    <str name="HandyQuery">org.apache.solr.search.HandyQueryBuilder</str>
    <str name="HelloQuery">org.apache.solr.search.HelloQueryBuilder</str>
    <str name="GoodbyeQuery">org.apache.solr.search.GoodbyeQueryBuilder</str>
  </queryParser>
</config>


package Beverge;

/**
 * 具体的浓缩咖啡
 * Created by jimersylee on 17-8-19.
 */
public class Espresso extends Beverage {

    public Espresso() {
        description="Espresso";//description变量继承自Beverage
    }

    @Override
    public double cost() {
        return 1.99;
    }
}


/**
 * Copyright (c) 2012, The University of Southampton and the individual contributors.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *   * 	Redistributions of source code must retain the above copyright notice,
 * 	this list of conditions and the following disclaimer.
 *
 *   *	Redistributions in binary form must reproduce the above copyright notice,
 * 	this list of conditions and the following disclaimer in the documentation
 * 	and/or other materials provided with the distribution.
 *
 *   *	Neither the name of the University of Southampton nor the names of its
 * 	contributors may be used to endorse or promote products derived from this
 * 	software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.openimaj.twitter;

import java.io.IOException;
import java.util.Scanner;

/**
 * {@link GeneralJSONTwitterRawText} extends {@link GeneralJSONTwitter} to provide an object that can
 * read raw strings. It can also then be used by USMFFStatus to
 * fill a USMFSStatus with the relevant twitter fields.
 *
 * @author Laurence Willmore (lgw1e10@ecs.soton.ac.uk), Sina Samangooei (ss@ecs.soton.ac.uk)
 *
 */
public class GeneralJSONTwitterRawText extends GeneralJSONTwitter {
	@Override
	public void readASCII(Scanner in) throws IOException {
		this.text = in.nextLine();
	}

	@Override
	public GeneralJSON instanceFromString(String line) {
		GeneralJSONTwitterRawText ret = new GeneralJSONTwitterRawText();
		ret.text = line;
		return ret ;
	}
}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.gobblin.data.management.copy.replication;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import org.apache.gobblin.dataset.FileSystemDataset;
import org.apache.gobblin.util.HadoopUtils;

/**
 * {@link FileSystemDataset} wrapper class for {@link HadoopFsEndPoint}
 * @author mitu
 *
 */
public class HadoopFsEndPointDataset implements FileSystemDataset{

  private final HadoopFsEndPoint endPoint;
  private Path qualifiedDatasetRoot;

  public HadoopFsEndPointDataset(HadoopFsEndPoint endPoint){
    this.endPoint = endPoint;
    Configuration conf = HadoopUtils.newConfiguration();
    try {
      FileSystem fs = FileSystem.get(this.endPoint.getFsURI(), conf);
      qualifiedDatasetRoot =  fs.makeQualified(this.endPoint.getDatasetPath());
    } catch (IOException e1) {
      // ignored
      qualifiedDatasetRoot = this.endPoint.getDatasetPath();
    }
  }

  @Override
  public String datasetURN() {
    return this.qualifiedDatasetRoot.toString();
  }

  @Override
  public Path datasetRoot() {
    return this.qualifiedDatasetRoot;
  }
}


package org.datatransferproject.cloud.microsoft.cosmos;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;

/** Configuration required to initialize the Azure job store */
class TableStoreConfiguration {
  private String accountName;
  private String accountKey;
  private String blobKey;
  private String partitionKey;
  private ObjectMapper mapper;

  public String getAccountName() {
    return accountName;
  }

  public String getAccountKey() {
    return accountKey;
  }

  public String getPartitionKey() {
    return partitionKey;
  }

  public String getBlobKey() {
    return blobKey;
  }

  public ObjectMapper getMapper() {
    return mapper;
  }

  public static class Builder {
    private final TableStoreConfiguration configuration;

    public static Builder newInstance() {
      return new Builder();
    }

    public Builder accountName(String accountName) {
      configuration.accountName = accountName;
      return this;
    }

    public Builder accountKey(String accountKey) {
      configuration.accountKey = accountKey;
      return this;
    }

    public Builder partitionKey(String partitionKey) {
      configuration.partitionKey = partitionKey;
      return this;
    }

    public Builder blobKey(String blobKey) {
      configuration.blobKey = blobKey;
      return this;
    }

    public Builder mapper(ObjectMapper mapper) {
      configuration.mapper = mapper;
      return this;
    }

    public TableStoreConfiguration build() {
      Preconditions.checkNotNull(configuration.accountName);
      Preconditions.checkNotNull(configuration.accountKey);
      Preconditions.checkNotNull(configuration.partitionKey);
      Preconditions.checkNotNull(configuration.blobKey);
      Preconditions.checkNotNull(configuration.mapper);
      return configuration;
    }

    private Builder() {
      configuration = new TableStoreConfiguration();
    }
  }
}


/*
	Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
	Available via Academic Free License >= 2.1 OR the modified BSD license.
	see: http://dojotoolkit.org/license for details
*/

//>>built
define("dojo/_base/lang",["./kernel","../has","../sniff"],function(_1,_2){
_2.add("bug-for-in-skips-shadowed",function(){
for(var i in {toString:1}){
return 0;
}
return 1;
});
var _3=_2("bug-for-in-skips-shadowed")?"hasOwnProperty.valueOf.isPrototypeOf.propertyIsEnumerable.toLocaleString.toString.constructor".split("."):[],_4=_3.length,_5=function(_6,_7,_8){
var p,i=0,_9=_1.global;
if(!_8){
if(!_6.length){
return _9;
}else{
p=_6[i++];
try{
_8=_1.scopeMap[p]&&_1.scopeMap[p][1];
}
catch(e){
}
_8=_8||(p in _9?_9[p]:(_7?_9[p]={}:undefined));
}
}
while(_8&&(p=_6[i++])){
_8=(p in _8?_8[p]:(_7?_8[p]={}:undefined));
}
return _8;
},_a=Object.prototype.toString,_b=function(_c,_d,_e){
return (_e||[]).concat(Array.prototype.slice.call(_c,_d||0));
},_f=/\{([^\}]+)\}/g;
var _10={_extraNames:_3,_mixin:function(_11,_12,_13){
var _14,s,i,_15={};
for(_14 in _12){
s=_12[_14];
if(!(_14 in _11)||(_11[_14]!==s&&(!(_14 in _15)||_15[_14]!==s))){
_11[_14]=_13?_13(s):s;
}
}
if(_2("bug-for-in-skips-shadowed")){
if(_12){
for(i=0;i<_4;++i){
_14=_3[i];
s=_12[_14];
if(!(_14 in _11)||(_11[_14]!==s&&(!(_14 in _15)||_15[_14]!==s))){
_11[_14]=_13?_13(s):s;
}
}
}
}
return _11;
},mixin:function(_16,_17){
if(!_16){
_16={};
}
for(var i=1,l=arguments.length;i<l;i++){
_10._mixin(_16,arguments[i]);
}
return _16;
},setObject:function(_18,_19,_1a){
var _1b=_18.split("."),p=_1b.pop(),obj=_5(_1b,true,_1a);
return obj&&p?(obj[p]=_19):undefined;
},getObject:function(_1c,_1d,_1e){
return _5(_1c.split("."),_1d,_1e);
},exists:function(_1f,obj){
return _10.getObject(_1f,false,obj)!==undefined;
},isString:function(it){
return (typeof it=="string"||it instanceof String);
},isArray:function(it){
return it&&(it instanceof Array||typeof it=="array");
},isFunction:function(it){
return _a.call(it)==="[object Function]";
},isObject:function(it){
return it!==undefined&&(it===null||typeof it=="object"||_10.isArray(it)||_10.isFunction(it));
},isArrayLike:function(it){
return it&&it!==undefined&&!_10.isString(it)&&!_10.isFunction(it)&&!(it.tagName&&it.tagName.toLowerCase()=="form")&&(_10.isArray(it)||isFinite(it.length));
},isAlien:function(it){
return it&&!_10.isFunction(it)&&/\{\s*\[native code\]\s*\}/.test(String(it));
},extend:function(_20,_21){
for(var i=1,l=arguments.length;i<l;i++){
_10._mixin(_20.prototype,arguments[i]);
}
return _20;
},_hitchArgs:function(_22,_23){
var pre=_10._toArray(arguments,2);
var _24=_10.isString(_23);
return function(){
var _25=_10._toArray(arguments);
var f=_24?(_22||_1.global)[_23]:_23;
return f&&f.apply(_22||this,pre.concat(_25));
};
},hitch:function(_26,_27){
if(arguments.length>2){
return _10._hitchArgs.apply(_1,arguments);
}
if(!_27){
_27=_26;
_26=null;
}
if(_10.isString(_27)){
_26=_26||_1.global;
if(!_26[_27]){
throw (["lang.hitch: scope[\"",_27,"\"] is null (scope=\"",_26,"\")"].join(""));
}
return function(){
return _26[_27].apply(_26,arguments||[]);
};
}
return !_26?_27:function(){
return _27.apply(_26,arguments||[]);
};
},delegate:(function(){
function TMP(){
};
return function(obj,_28){
TMP.prototype=obj;
var tmp=new TMP();
TMP.prototype=null;
if(_28){
_10._mixin(tmp,_28);
}
return tmp;
};
})(),_toArray:_2("ie")?(function(){
function _29(obj,_2a,_2b){
var arr=_2b||[];
for(var x=_2a||0;x<obj.length;x++){
arr.push(obj[x]);
}
return arr;
};
return function(obj){
return ((obj.item)?_29:_b).apply(this,arguments);
};
})():_b,partial:function(_2c){
var arr=[null];
return _10.hitch.apply(_1,arr.concat(_10._toArray(arguments)));
},clone:function(src){
if(!src||typeof src!="object"||_10.isFunction(src)){
return src;
}
if(src.nodeType&&"cloneNode" in src){
return src.cloneNode(true);
}
if(src instanceof Date){
return new Date(src.getTime());
}
if(src instanceof RegExp){
return new RegExp(src);
}
var r,i,l;
if(_10.isArray(src)){
r=[];
for(i=0,l=src.length;i<l;++i){
if(i in src){
r.push(_10.clone(src[i]));
}
}
}else{
r=src.constructor?new src.constructor():{};
}
return _10._mixin(r,src,_10.clone);
},trim:String.prototype.trim?function(str){
return str.trim();
}:function(str){
return str.replace(/^\s\s*/,"").replace(/\s\s*$/,"");
},replace:function(_2d,map,_2e){
return _2d.replace(_2e||_f,_10.isFunction(map)?map:function(_2f,k){
return _10.getObject(k,false,map);
});
}};
1&&_10.mixin(_1,_10);
return _10;
});


#!/bin/sh

FILEPATH=$1
ORIG_FILENAME=$2
ORIG_UID=$3
ORIG_GID=$4
ORIG_MODE=$5
ORIG_SELINUXLABEL=$6

INFO=$(file ${FILEPATH}|grep "ELF 32-bit LSB  executable, ARM, EABI5")

if [ -z "$INFO" ]; then
    echo -n ${ORIG_FILENAME} "not an ARM32 elf file"
fi


/*
 *  squareScene.h
 *  sceneExample
 *
 *  Created by zachary lieberman on 11/30/10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#ifndef _SQUARE_SCENE
#define _SQUARE_SCENE

#include "ofMain.h"
#include "baseScene.h"

class squareScene : public baseScene {

	void setup();
	void update();
	void draw();

};

#endif