// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Numerics;

#if SYSTEM_PRIVATE_CORELIB
using Internal.Runtime.CompilerServices;
#endif

#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if SYSTEM_PRIVATE_CORELIB
#if TARGET_64BIT
using nint = System.Int64;
using nuint = System.UInt64;
#else // TARGET_64BIT
using nint = System.Int32;
using nuint = System.UInt32;
#endif // TARGET_64BIT
#else
using nint = System.Int64; // https://github.com/dotnet/runtime/issues/33575 - use long/ulong outside of corelib until the compiler supports it
using nuint = System.UInt64;
#endif

namespace System.Text.Unicode
{
    internal static unsafe partial class Utf16Utility
    {
#if DEBUG && SYSTEM_PRIVATE_CORELIB
        static Utf16Utility()
        {
            Debug.Assert(sizeof(nint) == IntPtr.Size && nint.MinValue < 0, "nint is defined incorrectly.");
            Debug.Assert(sizeof(nuint) == IntPtr.Size && nuint.MinValue == 0, "nuint is defined incorrectly.");
        }
#endif // DEBUG && SYSTEM_PRIVATE_CORELIB

        // Returns &inputBuffer[inputLength] if the input buffer is valid.
        /// <summary>
        /// Given an input buffer <paramref name="pInputBuffer"/> of char length <paramref name="inputLength"/>,
        /// returns a pointer to where the first invalid data appears in <paramref name="pInputBuffer"/>.
        /// </summary>
        /// <remarks>
        /// Returns a pointer to the end of <paramref name="pInputBuffer"/> if the buffer is well-formed.
        /// </remarks>
        public static char* GetPointerToFirstInvalidChar(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment)
        {
            Debug.Assert(inputLength >= 0, "Input length must not be negative.");
            Debug.Assert(pInputBuffer != null || inputLength == 0, "Input length must be zero if input buffer pointer is null.");

            // First, we'll handle the common case of all-ASCII. If this is able to
            // consume the entire buffer, we'll skip the remainder of this method's logic.

            int numAsciiCharsConsumedJustNow = (int)ASCIIUtility.GetIndexOfFirstNonAsciiChar(pInputBuffer, (uint)inputLength);
            Debug.Assert(0 <= numAsciiCharsConsumedJustNow && numAsciiCharsConsumedJustNow <= inputLength);

            pInputBuffer += (uint)numAsciiCharsConsumedJustNow;
            inputLength -= numAsciiCharsConsumedJustNow;

            if (inputLength == 0)
            {
                utf8CodeUnitCountAdjustment = 0;
                scalarCountAdjustment = 0;
                return pInputBuffer;
            }

            // If we got here, it means we saw some non-ASCII data, so within our
            // vectorized code paths below we'll handle all non-surrogate UTF-16
            // code points branchlessly. We'll only branch if we see surrogates.
            //
            // We still optimistically assume the data is mostly ASCII. This means that the
            // number of UTF-8 code units and the number of scalars almost matches the number
            // of UTF-16 code units. As we go through the input and find non-ASCII
            // characters, we'll keep track of these "adjustment" fixups. To get the
            // total number of UTF-8 code units required to encode the input data, add
            // the UTF-8 code unit count adjustment to the number of UTF-16 code units
            // seen.  To get the total number of scalars present in the input data,
            // add the scalar count adjustment to the number of UTF-16 code units seen.

            long tempUtf8CodeUnitCountAdjustment = 0;
            int tempScalarCountAdjustment = 0;

            if (Sse2.IsSupported)
            {
                if (inputLength >= Vector128<ushort>.Count)
                {
                    Vector128<ushort> vector0080 = Vector128.Create((ushort)0x80);
                    Vector128<ushort> vectorA800 = Vector128.Create((ushort)0xA800);
                    Vector128<short> vector8800 = Vector128.Create(unchecked((short)0x8800));
                    Vector128<ushort> vectorZero = Vector128<ushort>.Zero;

                    do
                    {
                        Vector128<ushort> utf16Data = Sse2.LoadVector128((ushort*)pInputBuffer); // unaligned
                        uint mask;

                        Vector128<ushort> charIsNonAscii;
                        if (Sse41.IsSupported)
                        {
                            // Sets the 0x0080 bit of each element in 'charIsNonAscii' if the corresponding
                            // input was 0x0080 <= [value]. (i.e., [value] is non-ASCII.)

                            charIsNonAscii = Sse41.Min(utf16Data, vector0080);
                        }
                        else
                        {
                            // Sets the 0x0080 bit of each element in 'charIsNonAscii' if the corresponding
                            // input was 0x0080 <= [value] <= 0x7FFF. The case where 0x8000 <= [value] will
                            // be handled in a few lines.

                            charIsNonAscii = Sse2.AndNot(Sse2.CompareGreaterThan(vector0080.AsInt16(), utf16Data.AsInt16()).AsUInt16(), vector0080);
                        }

#if DEBUG
                        // Quick check to ensure we didn't accidentally set the 0x8000 bit of any element.
                        uint debugMask = (uint)Sse2.MoveMask(charIsNonAscii.AsByte());
                        Debug.Assert((debugMask & 0b_1010_1010_1010_1010) == 0, "Shouldn't have set the 0x8000 bit of any element in 'charIsNonAscii'.");
#endif // DEBUG

                        // Sets the 0x8080 bits of each element in 'charIsNonAscii' if the corresponding
                        // input was 0x0800 <= [value]. This also handles the missing range a few lines above.

                        Vector128<ushort> charIsThreeByteUtf8Encoded = Sse2.Subtract(vectorZero, Sse2.ShiftRightLogical(utf16Data, 11));

                        mask = (uint)Sse2.MoveMask(Sse2.Or(charIsNonAscii, charIsThreeByteUtf8Encoded).AsByte());

                        // Each even bit of mask will be 1 only if the char was >= 0x0080,
                        // and each odd bit of mask will be 1 only if the char was >= 0x0800.
                        //
                        // Example for UTF-16 input "[ 0123 ] [ 1234 ] ...":
                        //
                        //            ,-- set if char[1] is >= 0x0800
                        //            |   ,-- set if char[0] is >= 0x0800
                        //            v   v
                        // mask = ... 1 1 0 1
                        //              ^   ^-- set if char[0] is non-ASCII
                        //              `-- set if char[1] is non-ASCII
                        //
                        // This means we can popcnt the number of set bits, and the result is the
                        // number of *additional* UTF-8 bytes that each UTF-16 code unit requires as
                        // it expands. This results in the wrong count for UTF-16 surrogate code
                        // units (we just counted that each individual code unit expands to 3 bytes,
                        // but in reality a well-formed UTF-16 surrogate pair expands to 4 bytes).
                        // We'll handle this in just a moment.
                        //
                        // For now, compute the popcnt but squirrel it away. We'll fold it in to the
                        // cumulative UTF-8 adjustment factor once we determine that there are no
                        // unpaired surrogates in our data. (Unpaired surrogates would invalidate
                        // our computed result and we'd have to throw it away.)

                        uint popcnt = (uint)BitOperations.PopCount(mask);

                        // Surrogates need to be special-cased for two reasons: (a) we need
                        // to account for the fact that we over-counted in the addition above;
                        // and (b) they require separate validation.

                        utf16Data = Sse2.Add(utf16Data, vectorA800);
                        mask = (uint)Sse2.MoveMask(Sse2.CompareLessThan(utf16Data.AsInt16(), vector8800).AsByte());

                        if (mask != 0)
                        {
                            // There's at least one UTF-16 surrogate code unit present.
                            // Since we performed a pmovmskb operation on the result of a 16-bit pcmpgtw,
                            // the resulting bits of 'mask' will occur in pairs:
                            // - 00 if the corresponding UTF-16 char was not a surrogate code unit;
                            // - 11 if the corresponding UTF-16 char was a surrogate code unit.
                            //
                            // A UTF-16 high/low surrogate code unit has the bit pattern [ 11011q## ######## ],
                            // where # is any bit; q = 0 represents a high surrogate, and q = 1 represents
                            // a low surrogate. Since we added 0xA800 in the vectorized operation above,
                            // our surrogate pairs will now have the bit pattern [ 10000q## ######## ].
                            // If we logical right-shift each word by 3, we'll end up with the bit pattern
                            // [ 00010000 q####### ], which means that we can immediately use pmovmskb to
                            // determine whether a given char was a high or a low surrogate.
                            //
                            // Therefore the resulting bits of 'mask2' will occur in pairs:
                            // - 00 if the corresponding UTF-16 char was a high surrogate code unit;
                            // - 01 if the corresponding UTF-16 char was a low surrogate code unit;
                            // - ## (garbage) if the corresponding UTF-16 char was not a surrogate code unit.
                            //   Since 'mask' already has 00 in these positions (since the corresponding char
                            //   wasn't a surrogate), "mask AND mask2 == 00" holds for these positions.

                            uint mask2 = (uint)Sse2.MoveMask(Sse2.ShiftRightLogical(utf16Data, 3).AsByte());

                            // 'lowSurrogatesMask' has its bits occur in pairs:
                            // - 01 if the corresponding char was a low surrogate char,
                            // - 00 if the corresponding char was a high surrogate char or not a surrogate at all.

                            uint lowSurrogatesMask = mask2 & mask;

                            // 'highSurrogatesMask' has its bits occur in pairs:
                            // - 01 if the corresponding char was a high surrogate char,
                            // - 00 if the corresponding char was a low surrogate char or not a surrogate at all.

                            uint highSurrogatesMask = (mask2 ^ 0b_0101_0101_0101_0101u /* flip all even-numbered bits 00 <-> 01 */) & mask;

                            Debug.Assert((highSurrogatesMask & lowSurrogatesMask) == 0,
                                "A char cannot simultaneously be both a high and a low surrogate char.");

                            Debug.Assert(((highSurrogatesMask | lowSurrogatesMask) & 0b_1010_1010_1010_1010u) == 0,
                                "Only even bits (no odd bits) of the masks should be set.");

                            // Now check that each high surrogate is followed by a low surrogate and that each
                            // low surrogate follows a high surrogate. We make an exception for the case where
                            // the final char of the vector is a high surrogate, since we can't perform validation
                            // on it until the next iteration of the loop when we hope to consume the matching
                            // low surrogate.

                            highSurrogatesMask <<= 2;
                            if ((ushort)highSurrogatesMask != lowSurrogatesMask)
                            {
                                goto NonVectorizedLoop; // error: mismatched surrogate pair; break out of vectorized logic
                            }

                            if (highSurrogatesMask > ushort.MaxValue)
                            {
                                // There was a standalone high surrogate at the end of the vector.
                                // We'll adjust our counters so that we don't consider this char consumed.

                                highSurrogatesMask = (ushort)highSurrogatesMask; // don't allow stray high surrogate to be consumed by popcnt
                                popcnt -= 2; // the '0xC000_0000' bits in the original mask are shifted out and discarded, so account for that here
                                pInputBuffer--;
                                inputLength++;
                            }

                            // If we're 64-bit, we can perform the zero-extension of the surrogate pairs count for
                            // free right now, saving the extension step a few lines below. If we're 32-bit, the
                            // convertion to nuint immediately below is a no-op, and we'll pay the cost of the real
                            // 64 -bit extension a few lines below.
                            nuint surrogatePairsCountNuint = (uint)BitOperations.PopCount(highSurrogatesMask);

                            // 2 UTF-16 chars become 1 Unicode scalar

                            tempScalarCountAdjustment -= (int)surrogatePairsCountNuint;

                            // Since each surrogate code unit was >= 0x0800, we eagerly assumed
                            // it'd be encoded as 3 UTF-8 code units, so our earlier popcnt computation
                            // assumes that the pair is encoded as 6 UTF-8 code units. Since each
                            // pair is in reality only encoded as 4 UTF-8 code units, we need to
                            // perform this adjustment now.

                            if (IntPtr.Size == 8)
                            {
                                // Since we've already zero-extended surrogatePairsCountNuint, we can directly
                                // sub + sub. It's more efficient than shl + sub.
                                tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint;
                                tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint;
                            }
                            else
                            {
                                // Take the hit of the 64-bit extension now.
                                tempUtf8CodeUnitCountAdjustment -= 2 * (uint)surrogatePairsCountNuint;
                            }
                        }

                        tempUtf8CodeUnitCountAdjustment += popcnt;
                        pInputBuffer += Vector128<ushort>.Count;
                        inputLength -= Vector128<ushort>.Count;
                    } while (inputLength >= Vector128<ushort>.Count);
                }
            }
            else if (Vector.IsHardwareAccelerated)
            {
                if (inputLength >= Vector<ushort>.Count)
                {
                    Vector<ushort> vector0080 = new Vector<ushort>(0x0080);
                    Vector<ushort> vector0400 = new Vector<ushort>(0x0400);
                    Vector<ushort> vector0800 = new Vector<ushort>(0x0800);
                    Vector<ushort> vectorD800 = new Vector<ushort>(0xD800);

                    do
                    {
                        // The 'twoOrMoreUtf8Bytes' and 'threeOrMoreUtf8Bytes' vectors will contain
                        // elements whose values are 0xFFFF (-1 as signed word) iff the corresponding
                        // UTF-16 code unit was >= 0x0080 and >= 0x0800, respectively. By summing these
                        // vectors, each element of the sum will contain one of three values:
                        //
                        // 0x0000 ( 0) = original char was 0000..007F
                        // 0xFFFF (-1) = original char was 0080..07FF
                        // 0xFFFE (-2) = original char was 0800..FFFF
                        //
                        // We'll negate them to produce a value 0..2 for each element, then sum all the
                        // elements together to produce the number of *additional* UTF-8 code units
                        // required to represent this UTF-16 data. This is similar to the popcnt step
                        // performed by the SSE2 code path. This will overcount surrogates, but we'll
                        // handle that shortly.

                        Vector<ushort> utf16Data = Unsafe.ReadUnaligned<Vector<ushort>>(pInputBuffer);
                        Vector<ushort> twoOrMoreUtf8Bytes = Vector.GreaterThanOrEqual(utf16Data, vector0080);
                        Vector<ushort> threeOrMoreUtf8Bytes = Vector.GreaterThanOrEqual(utf16Data, vector0800);
                        Vector<nuint> sumVector = (Vector<nuint>)(Vector<ushort>.Zero - twoOrMoreUtf8Bytes - threeOrMoreUtf8Bytes);

                        // We'll try summing by a natural word (rather than a 16-bit word) at a time,
                        // which should halve the number of operations we must perform.

                        nuint popcnt = 0;
                        for (int i = 0; i < Vector<nuint>.Count; i++)
                        {
                            popcnt += sumVector[i];
                        }

                        uint popcnt32 = (uint)popcnt;
                        if (IntPtr.Size == 8)
                        {
                            popcnt32 += (uint)(popcnt >> 32);
                        }

                        // As in the SSE4.1 paths, compute popcnt but don't fold it in until we
                        // know there aren't any unpaired surrogates in the input data.

                        popcnt32 = (ushort)popcnt32 + (popcnt32 >> 16);

                        // Now check for surrogates.

                        utf16Data -= vectorD800;
                        Vector<ushort> surrogateChars = Vector.LessThan(utf16Data, vector0800);
                        if (surrogateChars != Vector<ushort>.Zero)
                        {
                            // There's at least one surrogate (high or low) UTF-16 code unit in
                            // the vector. We'll build up additional vectors: 'highSurrogateChars'
                            // and 'lowSurrogateChars', where the elements are 0xFFFF iff the original
                            // UTF-16 code unit was a high or low surrogate, respectively.

                            Vector<ushort> highSurrogateChars = Vector.LessThan(utf16Data, vector0400);
                            Vector<ushort> lowSurrogateChars = Vector.AndNot(surrogateChars, highSurrogateChars);

                            // We want to make sure that each high surrogate code unit is followed by
                            // a low surrogate code unit and each low surrogate code unit follows a
                            // high surrogate code unit. Since we don't have an equivalent of pmovmskb
                            // or palignr available to us, we'll do this as a loop. We won't look at
                            // the very last high surrogate char element since we don't yet know if
                            // the next vector read will have a low surrogate char element.

                            if (lowSurrogateChars[0] != 0)
                            {
                                goto Error; // error: start of buffer contains standalone low surrogate char
                            }

                            ushort surrogatePairsCount = 0;
                            for (int i = 0; i < Vector<ushort>.Count - 1; i++)
                            {
                                surrogatePairsCount -= highSurrogateChars[i]; // turns into +1 or +0
                                if (highSurrogateChars[i] != lowSurrogateChars[i + 1])
                                {
                                    goto NonVectorizedLoop; // error: mismatched surrogate pair; break out of vectorized logic
                                }
                            }

                            if (highSurrogateChars[Vector<ushort>.Count - 1] != 0)
                            {
                                // There was a standalone high surrogate at the end of the vector.
                                // We'll adjust our counters so that we don't consider this char consumed.

                                pInputBuffer--;
                                inputLength++;
                                popcnt32 -= 2;
                            }

                            nint surrogatePairsCountNint = (nint)surrogatePairsCount; // zero-extend to native int size

                            // 2 UTF-16 chars become 1 Unicode scalar

                            tempScalarCountAdjustment -= (int)surrogatePairsCountNint;

                            // Since each surrogate code unit was >= 0x0800, we eagerly assumed
                            // it'd be encoded as 3 UTF-8 code units. Each surrogate half is only
                            // encoded as 2 UTF-8 code units (for 4 UTF-8 code units total),
                            // so we'll adjust this now.

                            tempUtf8CodeUnitCountAdjustment -= surrogatePairsCountNint;
                            tempUtf8CodeUnitCountAdjustment -= surrogatePairsCountNint;
                        }

                        tempUtf8CodeUnitCountAdjustment += popcnt32;
                        pInputBuffer += Vector<ushort>.Count;
                        inputLength -= Vector<ushort>.Count;
                    } while (inputLength >= Vector<ushort>.Count);
                }
            }

        NonVectorizedLoop:

            // Vectorization isn't supported on our current platform, or the input was too small to benefit
            // from vectorization, or we saw invalid UTF-16 data in the vectorized code paths and need to
            // drain remaining valid chars before we report failure.

            for (; inputLength > 0; pInputBuffer++, inputLength--)
            {
                uint thisChar = pInputBuffer[0];
                if (thisChar <= 0x7F)
                {
                    continue;
                }

                // Bump adjustment by +1 for U+0080..U+07FF; by +2 for U+0800..U+FFFF.
                // This optimistically assumes no surrogates, which we'll handle shortly.

                tempUtf8CodeUnitCountAdjustment += (thisChar + 0x0001_F800u) >> 16;

                if (!UnicodeUtility.IsSurrogateCodePoint(thisChar))
                {
                    continue;
                }

                // Found a surrogate char. Back out the adjustment we made above, then
                // try to consume the entire surrogate pair all at once. We won't bother
                // trying to interpret the surrogate pair as a scalar value; we'll only
                // validate that its bit pattern matches what's expected for a surrogate pair.

                tempUtf8CodeUnitCountAdjustment -= 2;

                if (inputLength == 1)
                {
                    goto Error; // input buffer too small to read a surrogate pair
                }

                thisChar = Unsafe.ReadUnaligned<uint>(pInputBuffer);
                if (((thisChar - (BitConverter.IsLittleEndian ? 0xDC00_D800u : 0xD800_DC00u)) & 0xFC00_FC00u) != 0)
                {
                    goto Error; // not a well-formed surrogate pair
                }

                tempScalarCountAdjustment--; // 2 UTF-16 code units -> 1 scalar
                tempUtf8CodeUnitCountAdjustment += 2; // 2 UTF-16 code units -> 4 UTF-8 code units

                pInputBuffer++; // consumed one extra char
                inputLength--;
            }

        Error:

            // Also used for normal return.

            utf8CodeUnitCountAdjustment = tempUtf8CodeUnitCountAdjustment;
            scalarCountAdjustment = tempScalarCountAdjustment;
            return pInputBuffer;
        }
    }
}


"""High-velocity impact of an Steel projectile on an Aluminium plate"""

import numpy

# SPH equations
from pysph.sph.equation import Group

from pysph.sph.basic_equations import IsothermalEOS, ContinuityEquation, MonaghanArtificialViscosity,\
     XSPHCorrection, VelocityGradient3D

from pysph.sph.solid_mech.basic import MomentumEquationWithStress, HookesDeviatoricStressRate,\
    MonaghanArtificialStress, EnergyEquationWithStress

from pysph.sph.solid_mech.hvi import VonMisesPlasticity2D, MieGruneisenEOS, StiffenedGasEOS

from pysph.sph.gas_dynamics.basic import UpdateSmoothingLengthFromVolume

from pysph.base.utils import get_particle_array
from pysph.base.kernels import Gaussian, CubicSpline, WendlandQuintic
from pysph.solver.application import Application
from pysph.solver.solver import Solver
from pysph.sph.integrator import PECIntegrator, EPECIntegrator
from pysph.sph.integrator_step import SolidMechStep

def add_properties(pa, *props):
    for prop in props:
        pa.add_property(name=prop)

# Parameters
dx = dy = dz = 0.0005 # m
hdx = 1.3
h = hdx*dx
r = 0.005

######################################################################
# Material properties: Table (1) of "A Free Lagrange Augmented Godunov Method
# for the Simulation of Elastic-Plastic Solids", B. P. Howell and G. J. Ball,
# JCP (2002)

# ALUMINIUM
ro1 = 2785.0         # refenrence density
C1 = 5328.0          # reference sound-speed
S1 = 1.338           # Particle-shock velocity slope
gamma1 = 2.0         # Gruneisen gamma/parameter
G1 = 2.76e7          # Shear Modulus (kPa)
Yo1 = 0.3e6          # Yield stress
E1 = ro1*C1*C1       # Youngs Modulus

# STEEL
ro2 = 7900.0         # reference density
C2 = 4600.0          # reference sound-speed
S2 = 1.490           # Particle shock velocity slope
gamma2 = 2.17        # Gruneisen gamma/parameter
G2 = 8.530e7         # Shear modulus
Yo2 = 0.979e6        # Yield stress
E2 = ro2*C2*C2       # Youngs modulus

# general
v_s = 3100.0         # Projectile velocity 3.1 km/s
cs1=numpy.sqrt(E1/ro1) # speed of sound in aluminium
cs2=numpy.sqrt(E2/ro2) # speed of sound in steel

######################################################################
# SPH constants and parameters

# Monaghan-type artificial viscosity
avisc_alpha = 1.0; avisc_beta = 1.5; avisc_eta = 0.1

# XSPH epsilon
xsph_eps = 0.5

# SAV1 artificial viscosity coefficients
alpha1 = 1.0
beta1 = 1.5
eta = 0.1# in piab equation eta2 was written so final value is 0.01.(as req.)

# SAV2
alpha2 = 2.5
beta2 = 2.5
eta = 0.1# in piab equation eta2 was written so final value is 0.01.(as req.)

# XSPH
eps = 0.5

######################################################################
# Particle creation rouintes
def get_projectile_particles():

    x, y, z = numpy.mgrid[-r:r+1e-6:dx, -r:r+1e-6:dx, -r:r+1e-6:dx]
    x = x.ravel()
    y = y.ravel()
    z = z.ravel()

    d = (x*x+y*y+z*z)
    keep = numpy.flatnonzero(d<=r*r)
    x = x[keep]
    y = y[keep]
    z = z[keep]

    x = x-(r+2*dx)
    print('%d Projectile particles'%len(x))

    hf = numpy.ones_like(x) * h
    mf = numpy.ones_like(x) * dx * dy * dz * ro2
    rhof = numpy.ones_like(x) * ro2
    csf  = numpy.ones_like(x) * cs2
    u    = numpy.ones_like(x) * v_s

    pa = projectile = get_particle_array(
        name="projectile", x=x, y=y, z=z, h=hf, m=mf, rho=rhof, cs=csf, u=u)

    # add requisite properties
    # sound speed etc.
    add_properties(pa, 'e')

    # velocity gradient properties
    add_properties(pa, 'v00', 'v01', 'v02', 'v10', 'v11', 'v12', 'v20', 'v21', 'v22')

    # artificial stress properties
    add_properties(pa, 'r00', 'r01', 'r02', 'r11', 'r12', 'r22')

    # deviatoric stress components
    add_properties(pa, 's00', 's01', 's02', 's11', 's12', 's22')

    # deviatoric stress accelerations
    add_properties(pa, 'as00', 'as01', 'as02', 'as11', 'as12', 'as22')

    # deviatoric stress initial values
    add_properties(pa, 's000', 's010', 's020', 's110', 's120', 's220')

    # standard acceleration variables
    add_properties(pa, 'arho', 'au', 'av', 'aw', 'ax', 'ay', 'az', 'ae')

    # initial values
    add_properties(pa, 'rho0', 'u0', 'v0', 'w0', 'x0', 'y0', 'z0', 'e0')

    pa.add_constant('G', G2)
    pa.add_constant('n', 4)

    kernel = Gaussian(dim=3)
    wdeltap = kernel.kernel(rij=dx, h=hdx*dx)
    pa.add_constant('wdeltap', wdeltap)

    # load balancing properties
    pa.set_lb_props( list(pa.properties.keys()) )

    return projectile

def get_plate_particles():
    xarr = numpy.arange(0, 0.002+dx, dx)
    yarr = numpy.arange(-0.020, 0.02+dx, dx)
    zarr = numpy.arange(-0.02, 0.02+dx, dx)

    x, y, z = numpy.mgrid[0:0.002+dx:dx, -0.02:0.02+dx:dx, -0.02:0.02+dx:dx]
    x = x.ravel()
    y = y.ravel()
    z = z.ravel()

    print('%d Target particles'%len(x))

    hf = numpy.ones_like(x) * h
    mf = numpy.ones_like(x) * dx * dy * dz * ro1
    rhof = numpy.ones_like(x) * ro1
    csf = numpy.ones_like(x) * cs1
    pa = plate = get_particle_array(name="plate",
                                    x=x, y=y, z=z, h=hf, m=mf, rho=rhof, cs=csf)

    # add requisite properties
    # sound speed etc.
    add_properties(pa, 'e' )

    # velocity gradient properties
    add_properties(pa, 'v00', 'v01', 'v02', 'v10', 'v11', 'v12', 'v20', 'v21', 'v22')

    # artificial stress properties
    add_properties(pa, 'r00', 'r01', 'r02', 'r11', 'r12', 'r22')

    # deviatoric stress components
    add_properties(pa, 's00', 's01', 's02', 's11', 's12', 's22')

    # deviatoric stress accelerations
    add_properties(pa, 'as00', 'as01', 'as02', 'as11', 'as12', 'as22')

    # deviatoric stress initial values
    add_properties(pa, 's000', 's010', 's020', 's110', 's120', 's220')

    # standard acceleration variables
    add_properties(pa, 'arho', 'au', 'av', 'aw', 'ax', 'ay', 'az', 'ae')

    # initial values
    add_properties(pa, 'rho0', 'u0', 'v0', 'w0', 'x0', 'y0', 'z0', 'e0')

    pa.add_constant('G', G1)
    pa.add_constant('n', 4)

    kernel = Gaussian(dim=3)
    wdeltap = kernel.kernel(rij=dx, h=hdx*dx)
    pa.add_constant('wdeltap', wdeltap)
    # load balancing properties
    pa.set_lb_props( list(pa.properties.keys()) )

    # removed S_00 and similar components
    plate.v[:]=0.0
    return plate

class Impact(Application):
    def create_particles(self):
        plate      = get_plate_particles()
        projectile = get_projectile_particles()

        return [plate, projectile]

    def create_solver(self):
        dim=3
        kernel = Gaussian(dim=dim)
        #kernel = WendlandQuintic(dim=dim)

        integrator = EPECIntegrator(projectile=SolidMechStep(), plate=SolidMechStep())
        solver     = Solver(kernel=kernel, dim=dim, integrator=integrator)

        dt = 1e-9
        tf = 8e-6
        solver.set_time_step(dt)
        solver.set_final_time(tf)
        solver.set_print_freq(100)
        return solver

    def create_equations(self):
        equations = [

            # update smoothing length
            # Group(
            #     equations = [
            #         UpdateSmoothingLengthFromVolume(dest='plate',      sources=['plate', 'projectile'], dim=dim, k=hdx),
            #         UpdateSmoothingLengthFromVolume(dest='projectile', sources=['plate', 'projectile'], dim=dim, k=hdx),
            #     ],
            #     update_nnps=True,
            # ),

            # compute properties from the current state
            Group(
                equations = [
                    # EOS (compute the pressure using  one of the EOSs)

                    #MieGruneisenEOS(dest='plate',      sources=None, gamma=gamma1, r0=ro1 , c0=C1, S=S1),
                    #MieGruneisenEOS(dest='projectile', sources=None, gamma=gamma2, r0=ro2 , c0=C2, S=S2),

                    StiffenedGasEOS(dest='plate',      sources=None, gamma=gamma1, r0=ro1 , c0=C1),
                    StiffenedGasEOS(dest='projectile', sources=None, gamma=gamma2, r0=ro2 , c0=C2),

                    # compute the velocity gradient tensor
                    VelocityGradient3D(dest='plate',      sources=['plate']),
                    VelocityGradient3D(dest='projectile', sources=['projectile']),

                    # # stress
                    VonMisesPlasticity2D(dest='plate',      sources=None, flow_stress=Yo1),
                    VonMisesPlasticity2D(dest='projectile', sources=None, flow_stress=Yo2),

                    # # artificial stress to avoid clumping
                    MonaghanArtificialStress(dest='plate',      sources=None, eps=0.3),
                    MonaghanArtificialStress(dest='projectile', sources=None, eps=0.3),

                ]
            ),

            # accelerations (rho, u, v, ...)
            Group(
                equations = [

                    # continuity equation
                    ContinuityEquation(dest='plate',      sources=['projectile','plate']),
                    ContinuityEquation(dest='projectile', sources=['projectile','plate']),

                    # momentum equation
                    MomentumEquationWithStress(dest='projectile', sources=['projectile','plate',]),
                    MomentumEquationWithStress(dest='plate',      sources=['projectile','plate',]),

                    # energy equation:
                    EnergyEquationWithStress(dest='plate',      sources=['projectile','plate',],
                                               alpha=avisc_alpha, beta=avisc_beta, eta=avisc_eta),

                    EnergyEquationWithStress(dest='projectile', sources=['projectile','plate',],
                                               alpha=avisc_alpha, beta=avisc_beta,  eta=avisc_eta),

                    #avisc
                    MonaghanArtificialViscosity(dest='plate',     sources=['projectile','plate'],
                                                alpha=avisc_alpha, beta=avisc_beta),

                    MonaghanArtificialViscosity(dest='projectile', sources=['projectile','plate'],
                                               alpha=avisc_alpha, beta=avisc_beta),

                    #updates to the stress term
                    HookesDeviatoricStressRate(dest='plate',      sources=None),
                    HookesDeviatoricStressRate(dest='projectile', sources=None),

                    #position stepping
                    XSPHCorrection(dest='plate',      sources=['plate'],      eps=xsph_eps),
                    XSPHCorrection(dest='projectile', sources=['projectile'], eps=xsph_eps),

                ]
            ),

        ] # End Group list

        return equations

if __name__ == '__main__':
    app = Impact()
    app.run()


package tuf

import (
	"fmt"

	"github.com/docker/go/canonical/json"
	"github.com/theupdateframework/notary"

	"github.com/theupdateframework/notary/trustpinning"
	"github.com/theupdateframework/notary/tuf/data"
	"github.com/theupdateframework/notary/tuf/signed"
	"github.com/theupdateframework/notary/tuf/utils"
)

// ErrBuildDone is returned when any functions are called on RepoBuilder, and it
// is already finished building
var ErrBuildDone = fmt.Errorf(
	"the builder has finished building and cannot accept any more input or produce any more output")

// ErrInvalidBuilderInput is returned when RepoBuilder.Load is called
// with the wrong type of metadata for the state that it's in
type ErrInvalidBuilderInput struct{ msg string }

func (e ErrInvalidBuilderInput) Error() string {
	return e.msg
}

// ConsistentInfo is the consistent name and size of a role, or just the name
// of the role and a -1 if no file metadata for the role is known
type ConsistentInfo struct {
	RoleName data.RoleName
	fileMeta data.FileMeta
}

// ChecksumKnown determines whether or not we know enough to provide a size and
// consistent name
func (c ConsistentInfo) ChecksumKnown() bool {
	// empty hash, no size : this is the zero value
	return len(c.fileMeta.Hashes) > 0 || c.fileMeta.Length != 0
}

// ConsistentName returns the consistent name (rolename.sha256) for the role
// given this consistent information
func (c ConsistentInfo) ConsistentName() string {
	return utils.ConsistentName(c.RoleName.String(), c.fileMeta.Hashes[notary.SHA256])
}

// Length returns the expected length of the role as per this consistent
// information - if no checksum information is known, the size is -1.
func (c ConsistentInfo) Length() int64 {
	if c.ChecksumKnown() {
		return c.fileMeta.Length
	}
	return -1
}

// RepoBuilder is an interface for an object which builds a tuf.Repo
type RepoBuilder interface {
	Load(roleName data.RoleName, content []byte, minVersion int, allowExpired bool) error
	LoadRootForUpdate(content []byte, minVersion int, isFinal bool) error
	GenerateSnapshot(prev *data.SignedSnapshot) ([]byte, int, error)
	GenerateTimestamp(prev *data.SignedTimestamp) ([]byte, int, error)
	Finish() (*Repo, *Repo, error)
	BootstrapNewBuilder() RepoBuilder
	BootstrapNewBuilderWithNewTrustpin(trustpin trustpinning.TrustPinConfig) RepoBuilder

	// informative functions
	IsLoaded(roleName data.RoleName) bool
	GetLoadedVersion(roleName data.RoleName) int
	GetConsistentInfo(roleName data.RoleName) ConsistentInfo
}

// finishedBuilder refuses any more input or output
type finishedBuilder struct{}

func (f finishedBuilder) Load(roleName data.RoleName, content []byte, minVersion int, allowExpired bool) error {
	return ErrBuildDone
}
func (f finishedBuilder) LoadRootForUpdate(content []byte, minVersion int, isFinal bool) error {
	return ErrBuildDone
}
func (f finishedBuilder) GenerateSnapshot(prev *data.SignedSnapshot) ([]byte, int, error) {
	return nil, 0, ErrBuildDone
}
func (f finishedBuilder) GenerateTimestamp(prev *data.SignedTimestamp) ([]byte, int, error) {
	return nil, 0, ErrBuildDone
}
func (f finishedBuilder) Finish() (*Repo, *Repo, error)    { return nil, nil, ErrBuildDone }
func (f finishedBuilder) BootstrapNewBuilder() RepoBuilder { return f }
func (f finishedBuilder) BootstrapNewBuilderWithNewTrustpin(trustpin trustpinning.TrustPinConfig) RepoBuilder {
	return f
}
func (f finishedBuilder) IsLoaded(roleName data.RoleName) bool        { return false }
func (f finishedBuilder) GetLoadedVersion(roleName data.RoleName) int { return 0 }
func (f finishedBuilder) GetConsistentInfo(roleName data.RoleName) ConsistentInfo {
	return ConsistentInfo{RoleName: roleName}
}

// NewRepoBuilder is the only way to get a pre-built RepoBuilder
func NewRepoBuilder(gun data.GUN, cs signed.CryptoService, trustpin trustpinning.TrustPinConfig) RepoBuilder {
	return NewBuilderFromRepo(gun, NewRepo(cs), trustpin)
}

// NewBuilderFromRepo allows us to bootstrap a builder given existing repo data.
// YOU PROBABLY SHOULDN'T BE USING THIS OUTSIDE OF TESTING CODE!!!
func NewBuilderFromRepo(gun data.GUN, repo *Repo, trustpin trustpinning.TrustPinConfig) RepoBuilder {
	return &repoBuilderWrapper{
		RepoBuilder: &repoBuilder{
			repo:                 repo,
			invalidRoles:         NewRepo(nil),
			gun:                  gun,
			trustpin:             trustpin,
			loadedNotChecksummed: make(map[data.RoleName][]byte),
		},
	}
}

// repoBuilderWrapper embeds a repoBuilder, but once Finish is called, swaps
// the embed out with a finishedBuilder
type repoBuilderWrapper struct {
	RepoBuilder
}

func (rbw *repoBuilderWrapper) Finish() (*Repo, *Repo, error) {
	switch rbw.RepoBuilder.(type) {
	case finishedBuilder:
		return rbw.RepoBuilder.Finish()
	default:
		old := rbw.RepoBuilder
		rbw.RepoBuilder = finishedBuilder{}
		return old.Finish()
	}
}

// repoBuilder actually builds a tuf.Repo
type repoBuilder struct {
	repo         *Repo
	invalidRoles *Repo

	// needed for root trust pininng verification
	gun      data.GUN
	trustpin trustpinning.TrustPinConfig

	// in case we load root and/or targets before snapshot and timestamp (
	// or snapshot and not timestamp), so we know what to verify when the
	// data with checksums come in
	loadedNotChecksummed map[data.RoleName][]byte

	// bootstrapped values to validate a new root
	prevRoot                 *data.SignedRoot
	bootstrappedRootChecksum *data.FileMeta

	// for bootstrapping the next builder
	nextRootChecksum *data.FileMeta
}

func (rb *repoBuilder) Finish() (*Repo, *Repo, error) {
	return rb.repo, rb.invalidRoles, nil
}

func (rb *repoBuilder) BootstrapNewBuilder() RepoBuilder {
	return &repoBuilderWrapper{RepoBuilder: &repoBuilder{
		repo:                 NewRepo(rb.repo.cryptoService),
		invalidRoles:         NewRepo(nil),
		gun:                  rb.gun,
		loadedNotChecksummed: make(map[data.RoleName][]byte),
		trustpin:             rb.trustpin,

		prevRoot:                 rb.repo.Root,
		bootstrappedRootChecksum: rb.nextRootChecksum,
	}}
}

func (rb *repoBuilder) BootstrapNewBuilderWithNewTrustpin(trustpin trustpinning.TrustPinConfig) RepoBuilder {
	return &repoBuilderWrapper{RepoBuilder: &repoBuilder{
		repo:                 NewRepo(rb.repo.cryptoService),
		gun:                  rb.gun,
		loadedNotChecksummed: make(map[data.RoleName][]byte),
		trustpin:             trustpin,

		prevRoot:                 rb.repo.Root,
		bootstrappedRootChecksum: rb.nextRootChecksum,
	}}
}

// IsLoaded returns whether a particular role has already been loaded
func (rb *repoBuilder) IsLoaded(roleName data.RoleName) bool {
	switch roleName {
	case data.CanonicalRootRole:
		return rb.repo.Root != nil
	case data.CanonicalSnapshotRole:
		return rb.repo.Snapshot != nil
	case data.CanonicalTimestampRole:
		return rb.repo.Timestamp != nil
	default:
		return rb.repo.Targets[roleName] != nil
	}
}

// GetLoadedVersion returns the metadata version, if it is loaded, or 1 (the
// minimum valid version number) otherwise
func (rb *repoBuilder) GetLoadedVersion(roleName data.RoleName) int {
	switch {
	case roleName == data.CanonicalRootRole && rb.repo.Root != nil:
		return rb.repo.Root.Signed.Version
	case roleName == data.CanonicalSnapshotRole && rb.repo.Snapshot != nil:
		return rb.repo.Snapshot.Signed.Version
	case roleName == data.CanonicalTimestampRole && rb.repo.Timestamp != nil:
		return rb.repo.Timestamp.Signed.Version
	default:
		if tgts, ok := rb.repo.Targets[roleName]; ok {
			return tgts.Signed.Version
		}
	}

	return 1
}

// GetConsistentInfo returns the consistent name and size of a role, if it is known,
// otherwise just the rolename and a -1 for size (both of which are inside a
// ConsistentInfo object)
func (rb *repoBuilder) GetConsistentInfo(roleName data.RoleName) ConsistentInfo {
	info := ConsistentInfo{RoleName: roleName} // starts out with unknown filemeta
	switch roleName {
	case data.CanonicalTimestampRole:
		// we do not want to get a consistent timestamp, but we do want to
		// limit its size
		info.fileMeta.Length = notary.MaxTimestampSize
	case data.CanonicalSnapshotRole:
		if rb.repo.Timestamp != nil {
			info.fileMeta = rb.repo.Timestamp.Signed.Meta[roleName.String()]
		}
	case data.CanonicalRootRole:
		switch {
		case rb.bootstrappedRootChecksum != nil:
			info.fileMeta = *rb.bootstrappedRootChecksum
		case rb.repo.Snapshot != nil:
			info.fileMeta = rb.repo.Snapshot.Signed.Meta[roleName.String()]
		}
	default:
		if rb.repo.Snapshot != nil {
			info.fileMeta = rb.repo.Snapshot.Signed.Meta[roleName.String()]
		}
	}
	return info
}

func (rb *repoBuilder) Load(roleName data.RoleName, content []byte, minVersion int, allowExpired bool) error {
	return rb.loadOptions(roleName, content, minVersion, allowExpired, false, false)
}

// LoadRootForUpdate adds additional flags for updating the root.json file
func (rb *repoBuilder) LoadRootForUpdate(content []byte, minVersion int, isFinal bool) error {
	if err := rb.loadOptions(data.CanonicalRootRole, content, minVersion, !isFinal, !isFinal, true); err != nil {
		return err
	}
	if !isFinal {
		rb.prevRoot = rb.repo.Root
	}
	return nil
}

// loadOptions adds additional flags that should only be used for updating the root.json
func (rb *repoBuilder) loadOptions(roleName data.RoleName, content []byte, minVersion int, allowExpired, skipChecksum, allowLoaded bool) error {
	if !data.ValidRole(roleName) {
		return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s is an invalid role", roleName)}
	}

	if !allowLoaded && rb.IsLoaded(roleName) {
		return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s has already been loaded", roleName)}
	}

	var err error
	switch roleName {
	case data.CanonicalRootRole:
		break
	case data.CanonicalTimestampRole, data.CanonicalSnapshotRole, data.CanonicalTargetsRole:
		err = rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole})
	default: // delegations
		err = rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole, data.CanonicalTargetsRole})
	}
	if err != nil {
		return err
	}

	switch roleName {
	case data.CanonicalRootRole:
		return rb.loadRoot(content, minVersion, allowExpired, skipChecksum)
	case data.CanonicalSnapshotRole:
		return rb.loadSnapshot(content, minVersion, allowExpired)
	case data.CanonicalTimestampRole:
		return rb.loadTimestamp(content, minVersion, allowExpired)
	case data.CanonicalTargetsRole:
		return rb.loadTargets(content, minVersion, allowExpired)
	default:
		return rb.loadDelegation(roleName, content, minVersion, allowExpired)
	}
}

func (rb *repoBuilder) checkPrereqsLoaded(prereqRoles []data.RoleName) error {
	for _, req := range prereqRoles {
		if !rb.IsLoaded(req) {
			return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s must be loaded first", req)}
		}
	}
	return nil
}

// GenerateSnapshot generates a new snapshot given a previous (optional) snapshot
// We can't just load the previous snapshot, because it may have been signed by a different
// snapshot key (maybe from a previous root version).  Note that we need the root role and
// targets role to be loaded, because we need to generate metadata for both (and we need
// the root to be loaded so we can get the snapshot role to sign with)
func (rb *repoBuilder) GenerateSnapshot(prev *data.SignedSnapshot) ([]byte, int, error) {
	switch {
	case rb.repo.cryptoService == nil:
		return nil, 0, ErrInvalidBuilderInput{msg: "cannot generate snapshot without a cryptoservice"}
	case rb.IsLoaded(data.CanonicalSnapshotRole):
		return nil, 0, ErrInvalidBuilderInput{msg: "snapshot has already been loaded"}
	case rb.IsLoaded(data.CanonicalTimestampRole):
		return nil, 0, ErrInvalidBuilderInput{msg: "cannot generate snapshot if timestamp has already been loaded"}
	}

	if err := rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole}); err != nil {
		return nil, 0, err
	}

	// If there is no previous snapshot, we need to generate one, and so the targets must
	// have already been loaded.  Otherwise, so long as the previous snapshot structure is
	// valid (it has a targets meta), we're good.
	switch prev {
	case nil:
		if err := rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalTargetsRole}); err != nil {
			return nil, 0, err
		}

		if err := rb.repo.InitSnapshot(); err != nil {
			rb.repo.Snapshot = nil
			return nil, 0, err
		}
	default:
		if err := data.IsValidSnapshotStructure(prev.Signed); err != nil {
			return nil, 0, err
		}
		rb.repo.Snapshot = prev
	}

	sgnd, err := rb.repo.SignSnapshot(data.DefaultExpires(data.CanonicalSnapshotRole))
	if err != nil {
		rb.repo.Snapshot = nil
		return nil, 0, err
	}

	sgndJSON, err := json.Marshal(sgnd)
	if err != nil {
		rb.repo.Snapshot = nil
		return nil, 0, err
	}

	// loadedNotChecksummed should currently contain the root awaiting checksumming,
	// since it has to have been loaded.  Since the snapshot was generated using
	// the root and targets data (there may not be any) that that have been loaded,
	// remove all of them from rb.loadedNotChecksummed
	for tgtName := range rb.repo.Targets {
		delete(rb.loadedNotChecksummed, data.RoleName(tgtName))
	}
	delete(rb.loadedNotChecksummed, data.CanonicalRootRole)

	// The timestamp can't have been loaded yet, so we want to cache the snapshot
	// bytes so we can validate the checksum when a timestamp gets generated or
	// loaded later.
	rb.loadedNotChecksummed[data.CanonicalSnapshotRole] = sgndJSON

	return sgndJSON, rb.repo.Snapshot.Signed.Version, nil
}

// GenerateTimestamp generates a new timestamp given a previous (optional) timestamp
// We can't just load the previous timestamp, because it may have been signed by a different
// timestamp key (maybe from a previous root version)
func (rb *repoBuilder) GenerateTimestamp(prev *data.SignedTimestamp) ([]byte, int, error) {
	switch {
	case rb.repo.cryptoService == nil:
		return nil, 0, ErrInvalidBuilderInput{msg: "cannot generate timestamp without a cryptoservice"}
	case rb.IsLoaded(data.CanonicalTimestampRole):
		return nil, 0, ErrInvalidBuilderInput{msg: "timestamp has already been loaded"}
	}

	// SignTimestamp always serializes the loaded snapshot and signs in the data, so we must always
	// have the snapshot loaded first
	if err := rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole, data.CanonicalSnapshotRole}); err != nil {
		return nil, 0, err
	}

	switch prev {
	case nil:
		if err := rb.repo.InitTimestamp(); err != nil {
			rb.repo.Timestamp = nil
			return nil, 0, err
		}
	default:
		if err := data.IsValidTimestampStructure(prev.Signed); err != nil {
			return nil, 0, err
		}
		rb.repo.Timestamp = prev
	}

	sgnd, err := rb.repo.SignTimestamp(data.DefaultExpires(data.CanonicalTimestampRole))
	if err != nil {
		rb.repo.Timestamp = nil
		return nil, 0, err
	}

	sgndJSON, err := json.Marshal(sgnd)
	if err != nil {
		rb.repo.Timestamp = nil
		return nil, 0, err
	}

	// The snapshot should have been loaded (and not checksummed, since a timestamp
	// cannot have been loaded), so it is awaiting checksumming. Since this
	// timestamp was generated using the snapshot awaiting checksumming, we can
	// remove it from rb.loadedNotChecksummed. There should be no other items
	// awaiting checksumming now since loading/generating a snapshot should have
	// cleared out everything else in `loadNotChecksummed`.
	delete(rb.loadedNotChecksummed, data.CanonicalSnapshotRole)

	return sgndJSON, rb.repo.Timestamp.Signed.Version, nil
}

// loadRoot loads a root if one has not been loaded
func (rb *repoBuilder) loadRoot(content []byte, minVersion int, allowExpired, skipChecksum bool) error {
	roleName := data.CanonicalRootRole

	signedObj, err := rb.bytesToSigned(content, data.CanonicalRootRole, skipChecksum)
	if err != nil {
		return err
	}
	// ValidateRoot validates against the previous root's role, as well as validates that the root
	// itself is self-consistent with its own signatures and thresholds.
	// This assumes that ValidateRoot calls data.RootFromSigned, which validates
	// the metadata, rather than just unmarshalling signedObject into a SignedRoot object itself.
	signedRoot, err := trustpinning.ValidateRoot(rb.prevRoot, signedObj, rb.gun, rb.trustpin)
	if err != nil {
		return err
	}

	if err := signed.VerifyVersion(&(signedRoot.Signed.SignedCommon), minVersion); err != nil {
		return err
	}

	if !allowExpired { // check must go at the end because all other validation should pass
		if err := signed.VerifyExpiry(&(signedRoot.Signed.SignedCommon), roleName); err != nil {
			return err
		}
	}

	rootRole, err := signedRoot.BuildBaseRole(data.CanonicalRootRole)
	if err != nil { // this should never happen since the root has been validated
		return err
	}
	rb.repo.Root = signedRoot
	rb.repo.originalRootRole = rootRole
	return nil
}

func (rb *repoBuilder) loadTimestamp(content []byte, minVersion int, allowExpired bool) error {
	roleName := data.CanonicalTimestampRole

	timestampRole, err := rb.repo.Root.BuildBaseRole(roleName)
	if err != nil { // this should never happen, since it's already been validated
		return err
	}

	signedObj, err := rb.bytesToSignedAndValidateSigs(timestampRole, content)
	if err != nil {
		return err
	}

	signedTimestamp, err := data.TimestampFromSigned(signedObj)
	if err != nil {
		return err
	}

	if err := signed.VerifyVersion(&(signedTimestamp.Signed.SignedCommon), minVersion); err != nil {
		return err
	}

	if !allowExpired { // check must go at the end because all other validation should pass
		if err := signed.VerifyExpiry(&(signedTimestamp.Signed.SignedCommon), roleName); err != nil {
			return err
		}
	}

	if err := rb.validateChecksumsFromTimestamp(signedTimestamp); err != nil {
		return err
	}

	rb.repo.Timestamp = signedTimestamp
	return nil
}

func (rb *repoBuilder) loadSnapshot(content []byte, minVersion int, allowExpired bool) error {
	roleName := data.CanonicalSnapshotRole

	snapshotRole, err := rb.repo.Root.BuildBaseRole(roleName)
	if err != nil { // this should never happen, since it's already been validated
		return err
	}

	signedObj, err := rb.bytesToSignedAndValidateSigs(snapshotRole, content)
	if err != nil {
		return err
	}

	signedSnapshot, err := data.SnapshotFromSigned(signedObj)
	if err != nil {
		return err
	}

	if err := signed.VerifyVersion(&(signedSnapshot.Signed.SignedCommon), minVersion); err != nil {
		return err
	}

	if !allowExpired { // check must go at the end because all other validation should pass
		if err := signed.VerifyExpiry(&(signedSnapshot.Signed.SignedCommon), roleName); err != nil {
			return err
		}
	}

	// at this point, the only thing left to validate is existing checksums - we can use
	// this snapshot to bootstrap the next builder if needed - and we don't need to do
	// the 2-value assignment since we've already validated the signedSnapshot, which MUST
	// have root metadata
	rootMeta := signedSnapshot.Signed.Meta[data.CanonicalRootRole.String()]
	rb.nextRootChecksum = &rootMeta

	if err := rb.validateChecksumsFromSnapshot(signedSnapshot); err != nil {
		return err
	}

	rb.repo.Snapshot = signedSnapshot
	return nil
}

func (rb *repoBuilder) loadTargets(content []byte, minVersion int, allowExpired bool) error {
	roleName := data.CanonicalTargetsRole

	targetsRole, err := rb.repo.Root.BuildBaseRole(roleName)
	if err != nil { // this should never happen, since it's already been validated
		return err
	}

	signedObj, err := rb.bytesToSignedAndValidateSigs(targetsRole, content)
	if err != nil {
		return err
	}

	signedTargets, err := data.TargetsFromSigned(signedObj, roleName)
	if err != nil {
		return err
	}

	if err := signed.VerifyVersion(&(signedTargets.Signed.SignedCommon), minVersion); err != nil {
		return err
	}

	if !allowExpired { // check must go at the end because all other validation should pass
		if err := signed.VerifyExpiry(&(signedTargets.Signed.SignedCommon), roleName); err != nil {
			return err
		}
	}

	signedTargets.Signatures = signedObj.Signatures
	rb.repo.Targets[roleName] = signedTargets
	return nil
}

func (rb *repoBuilder) loadDelegation(roleName data.RoleName, content []byte, minVersion int, allowExpired bool) error {
	delegationRole, err := rb.repo.GetDelegationRole(roleName)
	if err != nil {
		return err
	}

	// bytesToSigned checks checksum
	signedObj, err := rb.bytesToSigned(content, roleName, false)
	if err != nil {
		return err
	}

	signedTargets, err := data.TargetsFromSigned(signedObj, roleName)
	if err != nil {
		return err
	}

	if err := signed.VerifyVersion(&(signedTargets.Signed.SignedCommon), minVersion); err != nil {
		// don't capture in invalidRoles because the role we received is a rollback
		return err
	}

	// verify signature
	if err := signed.VerifySignatures(signedObj, delegationRole.BaseRole); err != nil {
		rb.invalidRoles.Targets[roleName] = signedTargets
		return err
	}

	if !allowExpired { // check must go at the end because all other validation should pass
		if err := signed.VerifyExpiry(&(signedTargets.Signed.SignedCommon), roleName); err != nil {
			rb.invalidRoles.Targets[roleName] = signedTargets
			return err
		}
	}

	signedTargets.Signatures = signedObj.Signatures
	rb.repo.Targets[roleName] = signedTargets
	return nil
}

func (rb *repoBuilder) validateChecksumsFromTimestamp(ts *data.SignedTimestamp) error {
	sn, ok := rb.loadedNotChecksummed[data.CanonicalSnapshotRole]
	if ok {
		// by this point, the SignedTimestamp has been validated so it must have a snapshot hash
		snMeta := ts.Signed.Meta[data.CanonicalSnapshotRole.String()].Hashes
		if err := data.CheckHashes(sn, data.CanonicalSnapshotRole.String(), snMeta); err != nil {
			return err
		}
		delete(rb.loadedNotChecksummed, data.CanonicalSnapshotRole)
	}
	return nil
}

func (rb *repoBuilder) validateChecksumsFromSnapshot(sn *data.SignedSnapshot) error {
	var goodRoles []data.RoleName
	for roleName, loadedBytes := range rb.loadedNotChecksummed {
		switch roleName {
		case data.CanonicalSnapshotRole, data.CanonicalTimestampRole:
			break
		default:
			if err := data.CheckHashes(loadedBytes, roleName.String(), sn.Signed.Meta[roleName.String()].Hashes); err != nil {
				return err
			}
			goodRoles = append(goodRoles, roleName)
		}
	}
	for _, roleName := range goodRoles {
		delete(rb.loadedNotChecksummed, roleName)
	}
	return nil
}

func (rb *repoBuilder) validateChecksumFor(content []byte, roleName data.RoleName) error {
	// validate the bootstrap checksum for root, if provided
	if roleName == data.CanonicalRootRole && rb.bootstrappedRootChecksum != nil {
		if err := data.CheckHashes(content, roleName.String(), rb.bootstrappedRootChecksum.Hashes); err != nil {
			return err
		}
	}

	// but we also want to cache the root content, so that when the snapshot is
	// loaded it is validated (to make sure everything in the repo is self-consistent)
	checksums := rb.getChecksumsFor(roleName)
	if checksums != nil { // as opposed to empty, in which case hash check should fail
		if err := data.CheckHashes(content, roleName.String(), *checksums); err != nil {
			return err
		}
	} else if roleName != data.CanonicalTimestampRole {
		// timestamp is the only role which does not need to be checksummed, but
		// for everything else, cache the contents in the list of roles that have
		// not been checksummed by the snapshot/timestamp yet
		rb.loadedNotChecksummed[roleName] = content
	}

	return nil
}

// Checksums the given bytes, and if they validate, convert to a data.Signed object.
// If a checksums are nil (as opposed to empty), adds the bytes to the list of roles that
// haven't been checksummed (unless it's a timestamp, which has no checksum reference).
func (rb *repoBuilder) bytesToSigned(content []byte, roleName data.RoleName, skipChecksum bool) (*data.Signed, error) {
	if !skipChecksum {
		if err := rb.validateChecksumFor(content, roleName); err != nil {
			return nil, err
		}
	}

	// unmarshal to signed
	signedObj := &data.Signed{}
	if err := json.Unmarshal(content, signedObj); err != nil {
		return nil, err
	}

	return signedObj, nil
}

func (rb *repoBuilder) bytesToSignedAndValidateSigs(role data.BaseRole, content []byte) (*data.Signed, error) {

	signedObj, err := rb.bytesToSigned(content, role.Name, false)
	if err != nil {
		return nil, err
	}

	// verify signature
	if err := signed.VerifySignatures(signedObj, role); err != nil {
		return nil, err
	}

	return signedObj, nil
}

// If the checksum reference (the loaded timestamp for the snapshot role, and
// the loaded snapshot for every other role except timestamp and snapshot) is nil,
// then return nil for the checksums, meaning that the checksum is not yet
// available.  If the checksum reference *is* loaded, then always returns the
// Hashes object for the given role - if it doesn't exist, returns an empty Hash
// object (against which any checksum validation would fail).
func (rb *repoBuilder) getChecksumsFor(role data.RoleName) *data.Hashes {
	var hashes data.Hashes
	switch role {
	case data.CanonicalTimestampRole:
		return nil
	case data.CanonicalSnapshotRole:
		if rb.repo.Timestamp == nil {
			return nil
		}
		hashes = rb.repo.Timestamp.Signed.Meta[data.CanonicalSnapshotRole.String()].Hashes
	default:
		if rb.repo.Snapshot == nil {
			return nil
		}
		hashes = rb.repo.Snapshot.Signed.Meta[role.String()].Hashes
	}
	return &hashes
}


//
//     Generated by class-dump 3.5 (64 bit).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <objc/NSObject.h>

@class NSDate;

@interface AKAbsintheSigner : NSObject
{
    NSDate *_contextCreationDate;
}

+ (id)sharedSigner;
- (void).cxx_destruct;
- (id)signatureForURLRequest:(id)arg1;

@end


/*! normalize.css v2.1.0 | MIT License | git.io/normalize */

// ==========================================================================
// HTML5 display definitions
// ==========================================================================

//
// Correct `block` display not defined in IE 8/9.
//

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
  display: block;
}

//
// Correct `inline-block` display not defined in IE 8/9.
//

audio,
canvas,
video {
  display: inline-block;
}

//
// Prevent modern browsers from displaying `audio` without controls.
// Remove excess height in iOS 5 devices.
//

audio:not([controls]) {
  display: none;
  height: 0;
}

//
// Address styling not present in IE 8/9.
//

[hidden] {
  display: none;
}

// ==========================================================================
// Base
// ==========================================================================

//
// 1. Set default font family to sans-serif.
// 2. Prevent iOS text size adjust after orientation change, without disabling
//    user zoom.
//

html {
  font-family: sans-serif; // 1
  -webkit-text-size-adjust: 100%; // 2
  -ms-text-size-adjust: 100%; // 2
}

//
// Remove default margin.
//

body {
  margin: 0;
}

// ==========================================================================
// Links
// ==========================================================================

//
// Address `outline` inconsistency between Chrome and other browsers.
//

a:focus {
  outline: thin dotted;
}

//
// Improve readability when focused and also mouse hovered in all browsers.
//

a:active,
a:hover {
  outline: 0;
}

// ==========================================================================
// Typography
// ==========================================================================

//
// Address variable `h1` font-size and margin within `section` and `article`
// contexts in Firefox 4+, Safari 5, and Chrome.
//

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

//
// Address styling not present in IE 8/9, Safari 5, and Chrome.
//

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

//
// Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.
//

b,
strong {
  font-weight: bold;
}

//
// Address styling not present in Safari 5 and Chrome.
//

dfn {
  font-style: italic;
}

//
// Address differences between Firefox and other browsers.
//

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

//
// Address styling not present in IE 8/9.
//

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

//
// Correct font family set oddly in Safari 5 and Chrome.
//

code,
kbd,
pre,
samp {
  font-family: monospace, serif;
  font-size: 1em;
}

//
// Improve readability of pre-formatted text in all browsers.
//

pre {
  white-space: pre-wrap;
}

//
// Set consistent quote types.
//

q {
  quotes: "\201C" "\201D" "\2018" "\2019";
}

//
// Address inconsistent and variable font size in all browsers.
//

small {
  font-size: 80%;
}

//
// Prevent `sub` and `sup` affecting `line-height` in all browsers.
//

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

sup {
  top: -0.5em;
}

sub {
  bottom: -0.25em;
}

// ==========================================================================
// Embedded content
// ==========================================================================

//
// Remove border when inside `a` element in IE 8/9.
//

img {
  border: 0;
}

//
// Correct overflow displayed oddly in IE 9.
//

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

// ==========================================================================
// Figures
// ==========================================================================

//
// Address margin not present in IE 8/9 and Safari 5.
//

figure {
  margin: 0;
}

// ==========================================================================
// Forms
// ==========================================================================

//
// Define consistent border, margin, and padding.
//

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

//
// 1. Correct `color` not being inherited in IE 8/9.
// 2. Remove padding so people aren't caught out if they zero out fieldsets.
//

legend {
  border: 0; // 1
  padding: 0; // 2
}

//
// 1. Correct font family not being inherited in all browsers.
// 2. Correct font size not being inherited in all browsers.
// 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.
//

button,
input,
select,
textarea {
  font-family: inherit; // 1
  font-size: 100%; // 2
  margin: 0; // 3
}

//
// Address Firefox 4+ setting `line-height` on `input` using `!important` in
// the UA stylesheet.
//

button,
input {
  line-height: normal;
}

//
// Address inconsistent `text-transform` inheritance for `button` and `select`.
// All other form control elements do not inherit `text-transform` values.
// Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+.
// Correct `select` style inheritance in Firefox 4+ and Opera.
//

button,
select {
  text-transform: none;
}

//
// 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
//    and `video` controls.
// 2. Correct inability to style clickable `input` types in iOS.
// 3. Improve usability and consistency of cursor style between image-type
//    `input` and others.
//

button,
html input[type="button"], // 1
input[type="reset"],
input[type="submit"] {
  -webkit-appearance: button; // 2
  cursor: pointer; // 3
}

//
// Re-set default cursor for disabled elements.
//

button[disabled],
html input[disabled] {
  cursor: default;
}

//
// 1. Address box sizing set to `content-box` in IE 8/9.
// 2. Remove excess padding in IE 8/9.
//

input[type="checkbox"],
input[type="radio"] {
  box-sizing: border-box; // 1
  padding: 0; // 2
}

//
// 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
// 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
//    (include `-moz` to future-proof).
//

input[type="search"] {
  -webkit-appearance: textfield; // 1
  -moz-box-sizing: content-box;
  -webkit-box-sizing: content-box; // 2
  box-sizing: content-box;
}

//
// Remove inner padding and search cancel button in Safari 5 and Chrome
// on OS X.
//

input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}

//
// Remove inner padding and border in Firefox 4+.
//

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

//
// 1. Remove default vertical scrollbar in IE 8/9.
// 2. Improve readability and alignment in all browsers.
//

textarea {
  overflow: auto; // 1
  vertical-align: top; // 2
}

// ==========================================================================
// Tables
// ==========================================================================

//
// Remove most spacing between table cells.
//

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


me.aflak.bluetooth
me.aflak.bluetooth.constants
me.aflak.bluetooth.interfaces
me.aflak.bluetooth.reader
me.aflak.bluetooth.utils
me.aflak.libraries


// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).

package nl.bzk.brp.model.data.kern;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import nl.bzk.brp.model.data.kern.Pers;
import nl.bzk.brp.model.data.kern.Persgeslnaamcomp;

privileged aspect Persgeslnaamcomp_Roo_Finder {

    public static TypedQuery<Persgeslnaamcomp> Persgeslnaamcomp.findPersgeslnaamcompsByPers(Pers pers) {
        if (pers == null) throw new IllegalArgumentException("The pers argument is required");
        EntityManager em = Persgeslnaamcomp.entityManager();
        TypedQuery<Persgeslnaamcomp> q = em.createQuery("SELECT o FROM Persgeslnaamcomp AS o WHERE o.pers = :pers", Persgeslnaamcomp.class);
        q.setParameter("pers", pers);
        return q;
    }

}


%% @author Bob Ippolito <bob@mochimedia.com>
%% @copyright 2007 Mochi Media, Inc.

%% @doc HTTP server.

-module(mochiweb_http).
-author('bob@mochimedia.com').
-export([start/0, start/1, stop/0, stop/1]).
-export([loop/2, default_body/1]).

-define(IDLE_TIMEOUT, 30000).

-define(DEFAULTS, [{name, ?MODULE},
                   {port, 8888}]).

set_default({Prop, Value}, PropList) ->
    case proplists:is_defined(Prop, PropList) of
        true ->
            PropList;
        false ->
            [{Prop, Value} | PropList]
    end.

set_defaults(Defaults, PropList) ->
    lists:foldl(fun set_default/2, PropList, Defaults).

parse_options(Options) ->
    {loop, HttpLoop} = proplists:lookup(loop, Options),
    Loop = fun (S) ->
                   ?MODULE:loop(S, HttpLoop)
           end,
    Options1 = [{loop, Loop} | proplists:delete(loop, Options)],
    set_defaults(?DEFAULTS, Options1).

stop() ->
    mochiweb_socket_server:stop(?MODULE).

stop(Name) ->
    mochiweb_socket_server:stop(Name).

start() ->
    start([{ip, "127.0.0.1"},
           {loop, {?MODULE, default_body}}]).

start(Options) ->
    mochiweb_socket_server:start(parse_options(Options)).

frm(Body) ->
    [""
     "<form method=\"POST\">"
     "<input type=\"hidden\" value=\"message\" name=\"hidden\"/>"
     "<input type=\"submit\" value=\"regular POST\">"
     "</form>"
     "
"
     "<form method=\"POST\" enctype=\"multipart/form-data\""
     " action=\"/multipart\">"
     "<input type=\"hidden\" value=\"multipart message\" name=\"hidden\"/>"
     "<input type=\"file\" name=\"file\"/>"
     "<input type=\"submit\" value=\"multipart POST\" />"
     "</form>"
     "
", Body, "
"
     ""].

default_body(Req, M, "/chunked") when M =:= 'GET'; M =:= 'HEAD' ->
    Res = Req:ok({"text/plain", [], chunked}),
    Res:write_chunk("First chunk\r\n"),
    timer:sleep(5000),
    Res:write_chunk("Last chunk\r\n"),
    Res:write_chunk("");
default_body(Req, M, _Path) when M =:= 'GET'; M =:= 'HEAD' ->
    Body = io_lib:format("~p~n", [[{parse_qs, Req:parse_qs()},
                                   {parse_cookie, Req:parse_cookie()},
                                   Req:dump()]]),
    Req:ok({"text/html",
            [mochiweb_cookies:cookie("mochiweb_http", "test_cookie")],
            frm(Body)});
default_body(Req, 'POST', "/multipart") ->
    Body = io_lib:format("~p~n", [[{parse_qs, Req:parse_qs()},
                                   {parse_cookie, Req:parse_cookie()},
                                   {body, Req:recv_body()},
                                   Req:dump()]]),
    Req:ok({"text/html", [], frm(Body)});
default_body(Req, 'POST', _Path) ->
    Body = io_lib:format("~p~n", [[{parse_qs, Req:parse_qs()},
                                   {parse_cookie, Req:parse_cookie()},
                                   {parse_post, Req:parse_post()},
                                   Req:dump()]]),
    Req:ok({"text/html", [], frm(Body)});
default_body(Req, _Method, _Path) ->
    Req:respond({501, [], []}).

default_body(Req) ->
    default_body(Req, Req:get(method), Req:get(path)).

loop(Socket, Body) ->
    inet:setopts(Socket, [{packet, http}]),
    request(Socket, Body).

request(Socket, Body) ->
    case gen_tcp:recv(Socket, 0, ?IDLE_TIMEOUT) of
        {ok, {http_request, Method, Path, Version}} ->
            headers(Socket, {Method, Path, Version}, [], Body);
        {error, {http_error, "\r\n"}} ->
            request(Socket, Body);
        {error, {http_error, "\n"}} ->
            request(Socket, Body);
        _Other ->
            gen_tcp:close(Socket),
            exit(normal)
    end.

headers(Socket, Request, Headers, Body) ->
    case gen_tcp:recv(Socket, 0, ?IDLE_TIMEOUT) of
        {ok, http_eoh} ->
            inet:setopts(Socket, [{packet, raw}]),
            Req = mochiweb:new_request({Socket, Request,
                                        lists:reverse(Headers)}),
            Body(Req),
            case Req:should_close() of
                true ->
                    gen_tcp:close(Socket),
                    exit(normal);
                false ->
                    Req:cleanup(),
                    ?MODULE:loop(Socket, Body)
            end;
        {ok, {http_header, _, Name, _, Value}} ->
            headers(Socket, Request, [{Name, Value} | Headers], Body);
        _Other ->
            gen_tcp:close(Socket),
            exit(normal)
    end.


version: 1.4.0
port: 7054
debug: false
crlsizelimit: 512000
tls:
  enabled: false
  certfile: null
  keyfile: null
  clientauth:
    type: noclientcert
    certfiles: null
ca:
  name: tlsca.org2.example.com
  keyfile: tlsca.org2.example.com_sk
  certfile: tlsca.org2.example.com-cert.pem
  chainfile: null
crl:
  expiry: 24h
registry:
  maxenrollments: -1
  identities:
  - name: boot-admin
    pass: boot-pass
    type: client
    affiliation: ""
    attrs:
      hf.Registrar.Roles: '*'
      hf.Registrar.DelegateRoles: '*'
      hf.Revoker: true
      hf.IntermediateCA: true
      hf.GenCRL: true
      hf.Registrar.Attributes: '*'
      hf.AffiliationMgr: true
db:
  type: sqlite3
  datasource: fabric-ca-server.db
  tls:
    enabled: false
    certfiles: null
    client:
      certfile: null
      keyfile: null
ldap:
  enabled: false
  url: ldap://<adminDN>:<adminPassword>@<host>:<port>/<base>
  tls:
    certfiles: null
    client:
      certfile: null
      keyfile: null
  attribute:
    names:
    - uid
    - member
    converters:
    - name: null
      value: null
    maps:
      groups:
      - name: null
        value: null
affiliations:
  org1:
  - department1
  - department2
  org2:
  - department1
signing:
  default:
    usage:
    - digital signature
    - cert sign
    - crl sign
    expiry: 87600h
  profiles:
    ca:
      usage:
      - cert sign
      - crl sign
      expiry: 43800h
      caconstraint:
        isca: true
        maxpathlen: 0
    tls:
      usage:
      - signing
      - key encipherment
      - server auth
      - client auth
      - key agreement
      expiry: 87600h
csr:
  cn: tlsca.org2.example.com
  keyrequest:
    algo: ecdsa
    size: 256
  names:
  - C: US
    ST: North Carolina
    L: null
    O: org2.example.com
    OU: tlsca
  hosts:
  - fabric-ca-server
  - localhost
  ca:
    expiry: 1314000h
    pathlength: 1
idemix:
  rhpoolsize: 1000
  nonceexpiration: 15s
  noncesweepinterval: 15m
bccsp:
  default: SW
  sw:
    hash: SHA2
    security: 256
    filekeystore:
      keystore: msp/keystore
cacount: null
cafiles: null
intermediate:
  parentserver:
    url: null
    caname: null
  enrollment:
    hosts: null
    profile: null
    label: null
  tls:
    certfiles: null
    client:
      certfile: null
      keyfile: null


  /**
   *  Records the timestamp for each value in an observable sequence.
   *
   * @example
   *  1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
   *  2 - res = source.timestamp(Rx.Scheduler.timeout);
   *
   * @param {Scheduler} [scheduler]  Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
   * @returns {Observable} An observable sequence with timestamp information on values.
   */
  observableProto.timestamp = function (scheduler) {
    isScheduler(scheduler) || (scheduler = timeoutScheduler);
    return this.map(function (x) {
      return { value: x, timestamp: scheduler.now() };
    });
  };


---
layout: threat-list
title: Mobile Device Technology Stack
---

Mobile Operating System: Operating system specifically designed for a mobile device and running mobile applications.

Device Drivers: Firmware running on a mobile device often used to interact with device hardware and other peripherals (e.g., camera)

Isolated Execution Environments: Hardware- or Firmware-based environment built into the mobile device that may provide many capabilities such as trusted key storage, code verification, code integrity, and trusted execution for security relevant
    processes.

Boot Firmware: The firmware necessary to boot the mobile OS (i.e., bootloader), and may verify additional device initialization code, device drivers used for peripherals, and portions of the mobile OS - all before a user can use the device.

Baseband Subsystem: The collection of hardware and firmware used to access the cellular network, and may run a real-time operating system (RTOS).

SIM Card: This removable hardware token is a System on a Chip (SoC) housing the subscriber identity (i.e., International Mobile Subscriber Identity), pre-shared cryptographic keys, and configuration information needed to obtain access to cellular
    networks.

Secure Digital (SD) Card: A removable peripheral supported by some models of mobile devices. SD cards come in many form factors and are most often used for data storage, and may contain app binaries, app data, or user data. SD System on a Chip (SoC) peripherals, such as a Wi-Fi adapter, also exist.

Threat List

Mobile Operating System

    {% assign sorted = site.stack-threats | sort:"rawID" %}
    {% for stack-threat in sorted %}
        {% if stack-threat.ThreatCategory == 'Mobile Operating System' %}

{{ stack-threat.Threat }}

        {% endif %}
    {% endfor %}

Device Drivers

    {% for stack-threat in sorted %}
        {% if stack-threat.ThreatCategory == 'Device Drivers' %}

{{ stack-threat.Threat }}

        {% endif %}
    {% endfor %}

Isolated Execution Environments

    {% for stack-threat in sorted %}
        {% if stack-threat.ThreatCategory == 'Isolated Execution Environments' %}

{{ stack-threat.Threat }}

        {% endif %}
    {% endfor %}

Boot Firmware

    {% for stack-threat in sorted %}
        {% if stack-threat.ThreatCategory == 'Boot firmware' %}

{{ stack-threat.Threat }}

        {% endif %}
    {% endfor %}

Baseband Subsystem

    {% for stack-threat in sorted %}
        {% if stack-threat.ThreatCategory == 'Baseband Subsystem' %}

{{ stack-threat.Threat }}

        {% endif %}
    {% endfor %}

SIM Card

    {% for stack-threat in sorted %}
        {% if stack-threat.ThreatCategory == 'USIM / SIM / UICC security' %}

{{ stack-threat.Threat }}

        {% endif %}
    {% endfor %}

SD Card

    {% for stack-threat in sorted %}
        {% if stack-threat.ThreatCategory == 'SD Card' %}

{{ stack-threat.Threat }}

        {% endif %}
    {% endfor %}


import passport from 'passport';
import {Strategy as LocalStrategy} from 'passport-local';
import session from 'express-session';
import sessionKnex from 'connect-session-knex';
import {Express, RequestHandler} from 'express';
import {Strategy as BearerStrategy} from 'passport-http-bearer';
import * as bcrypt from 'bcrypt';
import {Issuer as OIDCIssuer, Strategy as OIDCStrategy, TokenSet, UserinfoResponse} from 'openid-client';

import db from './db';
import {SettingsService} from "./settings/services/SettingsService";
import {SettingKeys} from "./settings/interfaces";
import urljoin from 'url-join';

export default (app: Express, settingsService: SettingsService, config: any): RequestHandler => {
    const SessionKnex = sessionKnex(session);
    const sessionConfig = Object.assign({
        resave: false,
        saveUninitialized: false,
        cookie: {httpOnly: true, secure: false},
        store: new SessionKnex({ knex: db, createTable: false, tablename: 'sessions' }),
    }, config.session);

    if (app.get('env') === 'production') {
        app.set('trust proxy', 1); // trust first proxy
        //sessionConfig.cookie.secure = true; // serve secure cookies
    }

    app.use(session(sessionConfig));

    passport.use(new LocalStrategy(async function(username, password, done) {
        try {
            const user = await getEntityWithCreds('local', username, password);
            if (!user) {
                return done(null, false);
            }

            return done(null, user);
        } catch (e) {
            return done(e);
        }
    }));
    passport.use(new BearerStrategy(async function(token, done) {
        try {
            const tokenParts = token.split(':');
            if (tokenParts.length !== 2) {
                return done(null, false);
            }

            const id = Buffer.from(tokenParts[0], 'base64').toString('utf8');
            const secret = Buffer.from(tokenParts[1], 'base64').toString('utf8');

            const user = await getEntityWithCreds('bearer', id, secret);
            if (!user) {
                return done(null, false);
            }

            return done(null, user);
        } catch (e) {
            return done(e);
        }
    }));

    // This can be used to keep a smaller payload
    passport.serializeUser(function(user, done) {
        done(null, user);
    });

    passport.deserializeUser(function(user, done) {
        done(null, user);
    });

    // ...
    app.use(passport.initialize());
    app.use(passport.session());

    // Accept the OpenID identifier and redirect the user to their OpenID
    // provider for authentication.  When complete, the provider will redirect
    // the user back to the application at:
    //     /auth/openid/return
    app.get('/auth/openid', async (req, res, next) => {
        if (await settingsService.get(SettingKeys.AuthOpenIdEnabled) === false) {
            return res.sendStatus(404);
        }
        if (req.user) {
            return res.redirect('/');
        }

        const callerId = 'auth';
        const keysToWatch = [
            SettingKeys.AuthOpenIdClientId,
            SettingKeys.AuthOpenIdClientSecret,
            SettingKeys.BaseUrl,
            SettingKeys.AuthOpenIdResponseMode,
            SettingKeys.AuthOpenIdIdentifierClaimName,
            SettingKeys.AuthOpenIdRequestedScopes,
        ];
        if (await settingsService.hasChanged(callerId, keysToWatch)) {
            console.log('Change of the OpenID authentication config detected. Reinitializing auth backend...');
            passport.unuse('openid');

            const issuer = await OIDCIssuer.discover(await settingsService.get(SettingKeys.AuthOpenIdDiscoveryUrl, callerId)); // => Promise

            //console.log('Discovered issuer %s %O', issuer.issuer, issuer.metadata);
            const client = new issuer.Client({
                client_id: await settingsService.get(SettingKeys.AuthOpenIdClientId, callerId),
                client_secret: await settingsService.get(SettingKeys.AuthOpenIdClientSecret, callerId),
                redirect_uris: [urljoin(await settingsService.get(SettingKeys.BaseUrl, callerId), '/auth/openid/return')],
                response_types: ['code'],
            });

            passport.use('openid', new OIDCStrategy(
                {
                    client,
                    params: {
                        scope: await settingsService.get(SettingKeys.AuthOpenIdRequestedScopes, callerId),
                        response_mode: await settingsService.get(SettingKeys.AuthOpenIdResponseMode, callerId),
                    }
                },
                async function(tokenSet: TokenSet/*, userinfo: UserinfoResponse*/, done: any) {
                    try {
                        if (tokenSet.expired()) {
                            return done(null, false, { message: 'Expired OpenID token' });
                        }

                        const claims = tokenSet.claims();
                        const idClaimName = await settingsService.get(SettingKeys.AuthOpenIdIdentifierClaimName, callerId);

                        let identifiers: string[] = claims[idClaimName] as any;
                        if (!identifiers) {
                            return done(null, false, { message: 'Can\'t find user identifier using IdentityClaimName' });
                        } else if (!Array.isArray(identifiers)) {
                            identifiers = [identifiers];
                        }

                        let user: any;
                        for (let id of identifiers) {
                            user = await getEntityWithCreds('openid', id, null);
                            if (user) {
                                break;
                            }
                        }

                        if (!user) {
                            return done(null, false, { message: `Can\'t find presented identifiers "${identifiers.toString()}" in auth entities list` });
                        }

                        return done(null, user);
                    } catch (e) {
                        return done(e);
                    }
                })
            );
        }

        next();
    }, passport.authenticate('openid'));

    const openidReturnHandlers: RequestHandler[] = [
        async (req, res, next) => {
            if (await settingsService.get(SettingKeys.AuthOpenIdEnabled) === true) {
                return next();
            }

            res.sendStatus(404);
        },
        (req, res, next) => {
            passport.authenticate('openid', function(err, user, info) {
                if (err) {
                    return next(err);
                }
                if (!user) {
                    res.status(401);
                    res.header('Content-type', 'text/html');
                    return res.end(`<pre>${info.message}</pre><br><a href="/">Go to main page</a>`);
                }
                req.logIn(user, function(err) {
                    if (err) {
                        return next(err);
                    }

                    res.cookie('ilc:userInfo', JSON.stringify(user));
                    return res.redirect('/');
                });
            })(req, res, next);
        }
    ];
    // The OpenID provider has redirected the user back to the application.
    // Finish the authentication process by verifying the assertion.  If valid,
    // the user will be logged in.  Otherwise, authentication has failed.
    app.get('/auth/openid/return', openidReturnHandlers); //Regular flow
    app.post('/auth/openid/return', openidReturnHandlers); //response_mode: 'form_post' flow

    // Accept passed username/password pair & perform an attempt to authenticate against local DB
    app.post('/auth/local', passport.authenticate(['local']), (req, res) => {
        res.cookie('ilc:userInfo', JSON.stringify(req.user));
        res.send('ok');
    });

    app.get('/auth/logout', (req, res) => {
        req.logout();
        res.clearCookie('ilc:userInfo');
        res.redirect('/');
    });

    app.get('/auth/available-methods', async (req, res) => {
        const availableMethods = ['local'];

        if (await settingsService.get(SettingKeys.AuthOpenIdEnabled) === true) {
            availableMethods.push('openid');
        }

        res.json(availableMethods);
    });

    return (req: any, res: any, next: any) => {
        if (!req.user) {
            return passport.authenticate('bearer', { session: false })(req, res, next);
        }

        return next();
    };
}

async function getEntityWithCreds(provider: string, identifier: string, secret: string|null):Promise<object|null> {
    const user = await db.select().from('auth_entities')
        .first('identifier', 'role', 'secret')
        .where({
            provider,
            identifier
        });
    if (!user) {
        return null;
    }

    if (secret !== null || user.secret !== null) { //Support of the password less auth methods, like OpenID Connect
        if (!await bcrypt.compare(secret, user.secret)) {
            return null;
        }
    }

    delete user.secret;

    return user;
}


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<typeInfoHistroy/>


/* -*- c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Assert;

// var SECTION = "6.3.7";
// var VERSION = "AS3";
// var TITLE   = "The logical not ! operator";

var flt:float = new float(3.1413119f);
AddStrictTestCase("logical not on float", !3, !flt);

flt = float(+0.0);
AddStrictTestCase("!float(+0.0)", Boolean(true), !flt);

flt = +0.0f;
Assert.expectEq("!(+0.0f) FloatLiteral", true, !flt);

flt = float(-0.0);
Assert.expectEq("!float(-0.0)", true, !flt);

flt = -0.0f;
Assert.expectEq("!(-0.0f) FloatLiteral", true, !flt);

flt = float.NaN;
Assert.expectEq("!float.NaN", true, !flt);

flt = float.MIN_VALUE;
Assert.expectEq("!float.MIN_VALUE", false, !flt);

flt = -float.MIN_VALUE;
Assert.expectEq("!-float.MIN_VALUE", false, !flt);

flt = float(-0.23);
Assert.expectEq("!float(-0.23)", false, !flt);

flt = -0.23f;
Assert.expectEq("!(-0.23f) FloatLiteral", false, !flt);


//
//     Generated by class-dump 3.5 (64 bit).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <UIKit/UIStatusBarItemView.h>

__attribute__((visibility("hidden")))
@interface UIStatusBarLocationItemView : UIStatusBarItemView
{
    int _iconType;
}

- (id)contentsImage;
- (_Bool)updateForNewData:(id)arg1 actions:(int)arg2;

@end


把NQueen board想象成一个1D array。
index就是col number
值就是row number.

validate n queue的时候 target row#
1. array 里面不能有 target row#
2. diagnal. 记得公式：
 row1 - row2 == col1 - col2. Diagnal elelment.fail
 row1 - row2 == -(col1 - col2). Diagnal element. fail

```
/*
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that
no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement,
where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Hide Tags Backtracking

*/

/*
  Recap: 12.08.2015
  NQueen: turns into a 1D array of row#'s. What are all of the possible combinations?
  Validate the board:
    With 1 potential canddate, a row# to put in the array
    1. the 1D array cannot have duplicate of the candidate
    2. check diagnals:
      row1 - row2 == col1 - col2. Diagnal elelment.fail
      row1 - row2 == -(col1 - col2). Diagnal element. fail
      That is:  delta_row = Q1 row - Q2 row
                delta_col = Q1 col - Q2 col
      Let delta_row = the difference in rows between the two queens, and delta_col = the difference in columns.
      The two queens will be on the same diagonal if delta_row == delta_col or delta_row == -delta_col

  Create the board:
    carete 2d arraylist based on the 1-D array of row#'s

    corner case: if n<=2, no solution
*/

class Solution {

    public ArrayList<ArrayList<String>> solveNQueens(int n) {
      ArrayList<ArrayList<String>> rst = new ArrayList<ArrayList<String>>();
      if (n <= 0) {
        return rst;
      }
      ArrayList<Integer> list = new ArrayList<Integer>(); //1D array
      helper(rst, list, n);

      return rst;
    }

    /*
      Validate the board with given input.
    */
    public boolean validate(ArrayList<Integer> list, int rowNum) {
      int colNum = list.size(); // the column that rowNum is going to be put on
      for (int col = 0; col < list.size(); col++) {
        //check row
        if (list.get(col) == rowNum) {
          return false;
        }
        //check diagnal
        //q1 col - newQ col == q1 row - newQ row
        if (col - colNum == list.get(col) - rowNum) {
          return false;
        }
        //q1 col - newQ col == -(q1 row - newQ row)
        if (col - colNum == -(list.get(col) - rowNum)) {
          return false;
        }
      }
      return true;
    }

    public ArrayList<String> createBoard(ArrayList<Integer> list){
      ArrayList<String> board = new ArrayList<String>();
      for (int row = 0; row < list.size(); row++) {
        StringBuffer sb = new StringBuffer();
        for (int col : list) {
          if (row == col) {
            sb.append("Q");
          } else {
            sb.append(".");
          }
        }
        board.add(sb.toString());
      }
      return board;
    }

    public void helper(ArrayList<ArrayList<String>> rst, ArrayList<Integer> list, int n){
      if (list.size() == n) {
        rst.add(createBoard(list));
        return;
      }
      //For next Queen, which row to put? Now do recursive:
      for (int i = 0; i < n; i++) {
        if (validate(list, i)) {
          list.add(i);
          helper(rst, list, n);
          list.remove(list.size() - 1);
        }
      }
    }
};

//Older version: the naming in validate() is confusing
/*
Thinking process:
1. Choose / Not choose concept.
2. N-Queue facts:
  Each column has 1 Q. Each row has 1 Q.
  That is: each column has 1 Q, which can be present as a row number.
  Use a 1-D array: index is column number, value is row number
3. When adding a new row Number into the 1-D array, validate it.
4. Use same procedure in 'permutaions' problem.
  The 1-D array 'cols' will be filled with all kinds of combination from 1 ~ n.
  Only when cols.size() == n, return a solution
5. When returnning the solution, return the format as a board. ArrayList<String[]>
*/
import java.util.*;
class NQueens {
    /**
     * Get all distinct N-Queen solutions
     * @param n: The number of queens
     * @return: All distinct solutions
     * For example, A string '...Q' shows a queen on forth position
     */
    ArrayList<ArrayList<String>> solveNQueens(int n) {
      ArrayList<ArrayList<String>> rst = new ArrayList<ArrayList<String>>();
      if (n <= 0) {
        return rst;
      }
      search(n, new ArrayList<Integer>(), rst);
      return rst;
    }

    ArrayList<String> createBoard(ArrayList<Integer> cols) {
      ArrayList<String> solution = new ArrayList<String>();
      for (int i = 0; i < cols.size(); i++) {
            StringBuffer sb = new StringBuffer();
        for (int j = 0; j < cols.size(); j++){
          if (j == cols.get(i)) {
            sb.append( "Q");
          } else {
            sb.append( ".");
          }
        }
        solution.add(sb.toString());
      }
      return solution;
    }

    boolean isValid (ArrayList<Integer> cols, int col) {
      int row = cols.size();
      for (int i = 0; i < row; i++) {
      if (cols.get(i) == col ) {
        return false;
      }
      //Check diagnal: Q1_row - Q2_row == Q1_col - Q2_col
      //In this case:
      //col: the target queen's column#
      //cols.get(i): the target queen's row#
      //We compare them with (row: current max_column#) and (i: current row#), to check if valid
      if (i - cols.get(i) == row - col) {
        return false;
      }
      if (i + cols.get(i) == row + col) {
        return false;
      }
      }
      return true;
    }

    void search(int n, ArrayList<Integer> cols, ArrayList<ArrayList<String>> rst) {
      if (cols.size() == n) {
        rst.add(createBoard(cols));
        return;
      }
      for (int i = 0; i < n; i++) {
        if (!isValid(cols, i)) {
          continue;
        }
        cols.add(i);
        search(n, cols, rst);
        cols.remove(cols.size() - 1);
      }
    }

    public static void main(String[] args){
      NQueens test = new NQueens();
      test.solveNQueens(4);
    }

};
```


class BackfillClaimantType < ActiveRecord::Migration[5.2]
  disable_ddl_transaction!

  def change
    Claimant.unscoped.in_batches do |relation|
      relation.update_all type: "Claimant"
      sleep(0.1)
    end
  end
end


<source>
  @type  forward
  @id    input1
  @label @mainstream
  port  24224
</source>

<filter **>
  @type stdout
</filter>

<label @mainstream>
  <match docker.**>
    @type file
    @id   output_docker1
    path         /fluentd/log/docker.*.log
    symlink_path /fluentd/log/docker.log
    append       true
    time_slice_format %Y%m%d
    time_slice_wait   1m
    time_format       %Y%m%dT%H%M%S%z
  </match>
  <match **>
    @type file
    @id   output1
    path         /fluentd/log/data.*.log
    symlink_path /fluentd/log/data.log
    append       true
    time_slice_format %Y%m%d
    time_slice_wait   10m
    time_format       %Y%m%dT%H%M%S%z
  </match>
</label>


# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================

"""Tests for models.tutorials.rnn.ptb.reader."""

import os.path

import tensorflow as tf

from . import ptb_reader as reader

class PtbReaderTest(tf.test.TestCase):

  def setUp(self):
    self._string_data = "\n".join(
        [" hello there i am",
         " rain as day",
         " want some cheesy puffs ?"])

  def testPtbRawData(self):
    tmpdir = tf.test.get_temp_dir()
    for suffix in "train", "valid", "test":
      filename = os.path.join(tmpdir, "ptb.%s.txt" % suffix)
      with tf.gfile.GFile(filename, "w") as fh:
        fh.write(self._string_data)
    # Smoke test
    output = reader.ptb_raw_data(tmpdir)
    self.assertEqual(len(output), 4)

  def testPtbProducer(self):
    raw_data = [4, 3, 2, 1, 0, 5, 6, 1, 1, 1, 1, 0, 3, 4, 1]
    batch_size = 3
    num_steps = 2
    x, y = reader.ptb_producer(raw_data, batch_size, num_steps)
    with self.test_session() as session:
      coord = tf.train.Coordinator()
      tf.train.start_queue_runners(session, coord=coord)
      try:
        xval, yval = session.run([x, y], )
        self.assertAllEqual(xval, [[4, 3], [5, 6], [1, 0]])
        self.assertAllEqual(yval, [[3, 2], [6, 1], [0, 3]])
        xval, yval = session.run([x, y], )
        self.assertAllEqual(xval, [[2, 1], [1, 1], [3, 4]])
        self.assertAllEqual(yval, [[1, 0], [1, 1], [4, 1]])
      finally:
        coord.request_stop()
        coord.join()

if __name__ == "__main__":
  tf.test.main()