text:
#region copyright
// -----------------------------------------------------------------------
//  <copyright file="ImmutableCollectionsSerializerFactory.cs" company="Akka.NET Team">
//      Copyright (C) 2015-2016 AsynkronIT <https://github.com/AsynkronIT>
//      Copyright (C) 2016-2016 Akka.NET Team <https://github.com/akkadotnet>
//  </copyright>
// -----------------------------------------------------------------------
#endregion

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Hyperion.Extensions;
using Hyperion.ValueSerializers;

namespace Hyperion.SerializerFactories
{
    internal sealed class ImmutableCollectionsSerializerFactory : ValueSerializerFactory
    {
        private const string ImmutableCollectionsNamespace = "System.Collections.Immutable";
        private const string ImmutableCollectionsAssembly = "System.Collections.Immutable";

        public override bool CanSerialize(Serializer serializer, Type type)
        {
            if (type.Namespace == null || !type.Namespace.Equals(ImmutableCollectionsNamespace)) return false;
            var isGenericEnumerable = GetEnumerableType(type) != null;
            if (isGenericEnumerable)
                return true;

            return false;
        }

        public override bool CanDeserialize(Serializer serializer, Type type) => CanSerialize(serializer, type);

        private static Type GetEnumerableType(Type type)
        {
            return type
                .GetTypeInfo()
                .GetInterfaces()
                .Where(intType => intType.GetTypeInfo().IsGenericType && intType.GetTypeInfo().GetGenericTypeDefinition() == typeof (IEnumerable<>))
                .Select(intType => intType.GetTypeInfo().GetGenericArguments()[0])
                .FirstOrDefault();
        }

        public override ValueSerializer BuildSerializer(Serializer serializer, Type type,
            ConcurrentDictionary<Type, ValueSerializer> typeMapping)
        {
            var x = new ObjectSerializer(type);
            if (serializer.Options.KnownTypesDict.TryGetValue(type, out var index))
            {
                var wrapper = new KnownTypeObjectSerializer(x, index);
                typeMapping.TryAdd(type, wrapper);
            }
            else
                typeMapping.TryAdd(type, x);
            var preserveObjectReferences = serializer.Options.PreserveObjectReferences;

            var elementType = GetEnumerableType(type) ?? typeof (object);
            var elementSerializer = serializer.GetSerializerByType(elementType);

            var typeName = type.Name;
            var genericSufixIdx = typeName.IndexOf('`');
            typeName = genericSufixIdx != -1 ? typeName.Substring(0, genericSufixIdx) : typeName;
            var creatorType =
                Type.GetType(ImmutableCollectionsNamespace + "." + typeName + ", " + ImmutableCollectionsAssembly);

            var createRangeMethodInfo = creatorType != null
                ? creatorType.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Static)
                    .First(methodInfo => methodInfo.Name == "CreateRange" && methodInfo.GetParameters().Length == 1)
                : null;

            // If the element type is a generic type and the method located to create the collection instance requires more than one generic type parameter
            // we need to obtain the generic arguments of the element type.
            var genericTypes = elementType.GetTypeInfo().IsGenericType && createRangeMethodInfo != null && createRangeMethodInfo.GetGenericArguments().Length > 1
                ? elementType.GetTypeInfo().GetGenericArguments()
                : new[] { elementType };

            // if creatorType == null it means that type is probably an interface
            // we propagate null to create mock serializer - it won't be used anyway

            var stackTypeDef = Type.GetType(ImmutableCollectionsNamespace + ".IImmutableStack`1, " + ImmutableCollectionsAssembly, true);
            var stackInterface = stackTypeDef.MakeGenericType(genericTypes[0]);

            var isStack = stackInterface.IsAssignableFrom(type);

            var createRange = createRangeMethodInfo != null
                ? createRangeMethodInfo.MakeGenericMethod(genericTypes)
                : null;

            ObjectWriter writer = (stream, o, session) =>
            {
                var enumerable = o as ICollection;
                if (enumerable == null)
                {
                    // object can be IEnumerable but not ICollection i.e. ImmutableQueue
                    var e = (IEnumerable) o;
                    var list = e.Cast<object>().ToList();//

                    enumerable = list;
                }
                Int32Serializer.WriteValueImpl(stream,enumerable.Count,session);
                foreach (var value in enumerable)
                {
                    stream.WriteObject(value, elementType, elementSerializer, preserveObjectReferences, session);
                }
                if (preserveObjectReferences)
                {
                    session.TrackSerializedObject(o);
                }
            };
            ObjectReader reader;

            if (isStack)
            {
                // if we are dealing with stack, we need to apply arguments in reverse order
                reader = (stream, session) =>
                {
                    var count = stream.ReadInt32(session);
                    var items = Array.CreateInstance(elementType, count);
                    for (var i = 0; i < count; i++)
                    {
                        var value = stream.ReadObject(session);
                        items.SetValue(value, count - i - 1);
                    }

                    var instance = createRange.Invoke(null, new object[] { items });
                    if (preserveObjectReferences)
                    {
                        session.TrackDeserializedObject(instance);
                    }
                    return instance;
                };
            }
            else
            {
                reader = (stream, session) =>
                {
                    var count = stream.ReadInt32(session);
                    var items = Array.CreateInstance(elementType, count);
                    for (var i = 0; i < count; i++)
                    {
                        var value = stream.ReadObject(session);
                        items.SetValue(value, i);
                    }

                    var instance = createRange.Invoke(null, new object[] { items });
                    if (preserveObjectReferences)
                    {
                        session.TrackDeserializedObject(instance);
                    }
                    return instance;
                };
            }
            x.Initialize(reader, writer);
            return x;
        }
    }
}


text:
Article 22-2
----
Les dispositions de l'article précédent ne sont pas applicables à l'enfant
marié.

redpajama_set_name: RedPajamaGithub


text:
package org.opensaml.xml.security.keyinfo;

import java.math.BigInteger;
import java.security.KeyException;
import java.security.PublicKey;
import java.security.cert.CRLException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import java.util.List;

import javax.security.auth.x500.X500Principal;

import org.opensaml.xml.XMLObjectBaseTestCase;
import org.opensaml.xml.security.SecurityTestHelper;
import org.opensaml.xml.security.keyinfo.KeyInfoHelper;
import org.opensaml.xml.signature.DSAKeyValue;
import org.opensaml.xml.signature.Exponent;
import org.opensaml.xml.signature.G;
import org.opensaml.xml.signature.KeyInfo;
import org.opensaml.xml.signature.KeyValue;
import org.opensaml.xml.signature.Modulus;
import org.opensaml.xml.signature.P;
import org.opensaml.xml.signature.Q;
import org.opensaml.xml.signature.RSAKeyValue;
import org.opensaml.xml.signature.X509CRL;
import org.opensaml.xml.signature.X509Certificate;
import org.opensaml.xml.signature.X509Data;
import org.opensaml.xml.signature.X509IssuerSerial;
import org.opensaml.xml.signature.X509SKI;
import org.opensaml.xml.signature.X509SubjectName;
import org.opensaml.xml.signature.Y;
import org.opensaml.xml.util.Base64;
import org.opensaml.xml.util.DatatypeHelper;

/**
 * Test to exercise the KeyInfoHelper methods to convert
 * between XMLObject's contained within KeyInfo and
 * Java security native types.
 */
public class KeyInfoHelperTest extends XMLObjectBaseTestCase {

    /** No-extensions test cert subject name. */
    private final String certNoExtensionSubjectDN = "CN=noextensions.example.org";
    /** Cert which contains no X.509 v3 extensions. */
    private final String certNoExtensions =
        "MIIBwjCCASugAwIBAgIJAMrW6QSeKNBJMA0GCSqGSIb3DQEBBAUAMCMxITAfBgNV" +
        "BAMTGG5vZXh0ZW5zaW9ucy5leGFtcGxlLm9yZzAeFw0wNzA1MTkxNzU2NTVaFw0w" +
        "NzA2MTgxNzU2NTVaMCMxITAfBgNVBAMTGG5vZXh0ZW5zaW9ucy5leGFtcGxlLm9y" +
        "ZzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw8xxu6TLqEdmnyXVZjiUoRHN" +
        "6yHyobZaRK+tBEmWkD4nTlOVmTKWBCO/F4OnugaJbSTH+7Jk37l8/XYYBSIkW0+L" +
        "2BglzQ2JCux/uoRu146QDIk9f5PIFs+Fxy7VRVUUZiOsonB/PNVqA7OVbPxzr1SK" +
        "PSE0s9CHaDjCaEs2BnMCAwEAATANBgkqhkiG9w0BAQQFAAOBgQAuI/l80wb8K6RT" +
        "1EKrAcfr9JAlJR4jmVnCK7j3Ulx++U98ze2G6/cluLxrbnqwXmxJNC3nt6xkQVJU" +
        "X1UFg+zkmRrst2Nv8TTrR7S30az068BHfrZLRSUConG9jXXj+hJq+w/ojmrq8Mzv" +
        "JSczkA2BvsEUBARYo53na7RMgk+xWg==";

    /* These test examples are from the NIST PKI path processing test suite:
     * http://csrc.nist.gov/pki/testing/x509paths.html
     * Data file:
     * http://csrc.nist.gov/pki/testing/PKITS_data.zip
     */

    /* certs/BasicSelfIssuedNewKeyCACert.crt */
    /** Test cert subject DN 1. */
    private final String cert1SubjectDN = "CN=Basic Self-Issued New Key CA,O=Test Certificates,C=US";
    /**
     * Test cert 1 SKI value.
     * Base64 encoded version of cert's plain (non-DER encoded) subject key identifier, which is:
     * AF:B9:F9:1D:C2:45:18:CC:B8:21:E2:A7:47:BC:49:BD:19:B5:78:28
     */
    private final String cert1SKIPlainBase64 = "r7n5HcJFGMy4IeKnR7xJvRm1eCg=";
    /** Test cert 1. */
    private final String cert1 =
        "MIICgjCCAeugAwIBAgIBEzANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJVUzEa" +
        "MBgGA1UEChMRVGVzdCBDZXJ0aWZpY2F0ZXMxFTATBgNVBAMTDFRydXN0IEFuY2hv" +
        "cjAeFw0wMTA0MTkxNDU3MjBaFw0xMTA0MTkxNDU3MjBaMFAxCzAJBgNVBAYTAlVT" +
        "MRowGAYDVQQKExFUZXN0IENlcnRpZmljYXRlczElMCMGA1UEAxMcQmFzaWMgU2Vs" +
        "Zi1Jc3N1ZWQgTmV3IEtleSBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA" +
        "tCkygqcMEOy3i8p6ZV3685us1lOugSU4pUMRJNRH/lV2ykesk+JRcQy1s7WS12j9" +
        "GCnSJ919/TgeKLmV3ps1fC1B8HziC0mzBAr+7f5LkJqSf0kS0kfpyLOoO8VSJCip" +
        "/8uENkSkpvX+Lak96OKzhtyvi4KpUdQKfwpg6xUqakECAwEAAaN8MHowHwYDVR0j" +
        "BBgwFoAU+2zULYGeyid6ng2wPOqavIf/SeowHQYDVR0OBBYEFK+5+R3CRRjMuCHi" +
        "p0e8Sb0ZtXgoMA4GA1UdDwEB/wQEAwIBBjAXBgNVHSAEEDAOMAwGCmCGSAFlAwIB" +
        "MAEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQCuRBfDy2gSPp2k" +
        "ZR7OAvt+xDx4toJ9ImImUvJ94AOLd6Uxsi2dvQT5HLrIBrTYsSfQj1pA50XY2F7k" +
        "3eM/+JhYCcyZD9XtAslpOkjwACPJnODFAY8PWC00CcOxGb6q+S/VkrCwvlBeMjev" +
        "IH4bHvAymWsZndBZhcG8gBmDrZMwhQ==";

    /* certs/GoodCACert.crt */
    /** Test cert subject DN 2. */
    private final String cert2SubjectDN = "CN=Good CA,O=Test Certificates,C=US";
    /** Test cert 2. */
    private final String cert2 =
        "MIICbTCCAdagAwIBAgIBAjANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJVUzEa" +
        "MBgGA1UEChMRVGVzdCBDZXJ0aWZpY2F0ZXMxFTATBgNVBAMTDFRydXN0IEFuY2hv" +
        "cjAeFw0wMTA0MTkxNDU3MjBaFw0xMTA0MTkxNDU3MjBaMDsxCzAJBgNVBAYTAlVT" +
        "MRowGAYDVQQKExFUZXN0IENlcnRpZmljYXRlczEQMA4GA1UEAxMHR29vZCBDQTCB" +
        "nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArsI1lQuXKwOxSkOVRaPwlhMQtgp0" +
        "p7HT4rKLGqojfY0twvMDc4rC9uj97wlh98kkraMx3r0wlllYSQ+Cp9mCCNu/C/Y2" +
        "IbZCyG+io4A3Um3q/QGvbHlclmrJb0j0MQi3o88GhE8Q6Vy6SGwFXGpKDJMpLSFp" +
        "Pxz8lh7M6J56Ex8CAwEAAaN8MHowHwYDVR0jBBgwFoAU+2zULYGeyid6ng2wPOqa" +
        "vIf/SeowHQYDVR0OBBYEFLcupoLLwsi8qHsnRNc1M9+aFZTHMA4GA1UdDwEB/wQE" +
        "AwIBBjAXBgNVHSAEEDAOMAwGCmCGSAFlAwIBMAEwDwYDVR0TAQH/BAUwAwEB/zAN" +
        "BgkqhkiG9w0BAQUFAAOBgQCOls9+0kEUS71w+KoQhfkVLdAKANXUmGCVZHL1zsya" +
        "cPP/Q8IsCNvwjefZpgc0cuhtnHt2uDd0/zYLRmgcvJwfx5vwOfmDN13mMB8Za+cg" +
        "3sZ/NI8MqQseKvS3fWqXaK6FJoKLzxId0iUGntbF4c5+rPFArzqM6IE7f9cMD5Fq" +
        "rA==";

    /* crls/BasicSelfIssuedCRLSigningKeyCACRL.crl */
    /** Test cert issuer DN 1. */
    private final String crl1IssuerDN = "CN=Basic Self-Issued CRL Signing Key CA,O=Test Certificates,C=US";
    /** Test CRL 1. */
    private final String crl1 =
        "MIIBdTCB3wIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJVUzEaMBgGA1UE" +
        "ChMRVGVzdCBDZXJ0aWZpY2F0ZXMxLTArBgNVBAMTJEJhc2ljIFNlbGYtSXNzdWVk" +
        "IENSTCBTaWduaW5nIEtleSBDQRcNMDEwNDE5MTQ1NzIwWhcNMTEwNDE5MTQ1NzIw" +
        "WjAiMCACAQMXDTAxMDQxOTE0NTcyMFowDDAKBgNVHRUEAwoBAaAvMC0wHwYDVR0j" +
        "BBgwFoAUD3LKM0OpxBFRq2PaRIcPYaT0vkcwCgYDVR0UBAMCAQEwDQYJKoZIhvcN" +
        "AQEFBQADgYEAXM2Poz2eZPdkc5wsOeLn1w64HD6bHRTcmMKOWh/lRzH9fqfVn1Ix" +
        "yBD30KKEP3fH8bp+JGKtBa4ce//w4s5V9SfTzCR/yB2muM5CBeEG7B+HTNVpjXhZ" +
        "0jOUHDsnaIA9bz2mx58rOZ/Xw4Prd73Mf5azrSRomdEavwUcjD4qAvg=";

    /* These are just randomly generated RSA and DSA public keys using OpenSSL. */

    /** Test RSA key 1. */
    private final String rsaPubKey1 =
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw/WnsbA8frhQ+8EoPgMr" +
        "QjpINjt20U/MvsvmoAgQnAgEF4OYt9Vj9/2YvMO4NvX1fNDFzoYRyOMrypF7skAP" +
        "cITUhdcPSEpI4nsf5yFZLziK/tQ26RsccE7WhpGB8eHu9tfseelgyioorvmt+JCo" +
        "P15c5rYUuIfVC+eEsYolw344q6N61OACHETuySL0a1+GFu3WoISXte1pQIst7HKv" +
        "BbHH41HEWAxT6e0hlD5PyKL4lBJadGHXg8Zz4r2jV2n6+Ox7raEWmtVCGFxsAoCR" +
        "alu6nvs2++5Nnb4C1SE640esfYhfeMd5JYfsTNMaQ8sZLpsWdglAGpa/Q87K19LI" +
        "wwIDAQAB";

    /** Test DSA key 1. */
    private final String dsaPubKey1 =
        "MIIDOjCCAi0GByqGSM44BAEwggIgAoIBAQCWV7IK073aK2C3yggy69qXkxCw30j5" +
        "Ig0s1/GHgq5jEZf8FTGVpehX5qaYlRC3TBMSN4WAgkG+nFnsjHb6kIYkayV8ZVvI" +
        "IgEBCeaZg016f90G+Rre5C38G3OwsODKjPsVZCV5YQ9rm6lWMOfMRSUzJuFA0fdx" +
        "RLssAfKLI5JmzupliO2iH5FU3+dQr0UvcPwPjjRDA9JIi3ShKdmq9f/SzRM9AJPs" +
        "sjc0v4lRVMKWkTHLjbRH2XiOxsok/oL7NVTJ9hvd3xqi1/O3MM2pNhYaQoA0kLqq" +
        "sr006dNftgo8n/zrBFMC6iP7tmxhuRxgXXkNo5xiQCvAX7HsGno4y9ilAhUAjKlv" +
        "CQhbGeQo3fWbwVJMdokSK5ECggEAfERqa+S8UwjuvNxGlisuBGzR7IqqHSQ0cjFI" +
        "BD61CkYh0k0Y9am6ZL2jiAkRICdkW6f9lmGy0HidCwC56WeAYpLyfJslBAjC4r0t" +
        "6U8a822fECVcbsPNLDULoQG0KjVRtYfFH5GedNQ8LRkG8b+XIe4G74+vXOatVu8L" +
        "9QXQKYx9diOAHx8ghpt1pC0UAqPzAgVGNWIPQ+VO7WEYOYuVw+/uFoHiaU1OZOTF" +
        "C4VXk2+33AasT4i6It7DIESp+ye9lPnNU6nLEBNSnXdnBgaH27m8QnFRTfrjimiG" +
        "BwBTQvbjequRvM5dExfUqyCd2BUOK1lbaQmjZnCMH6k3ZFiAYgOCAQUAAoIBAGnD" +
        "wMuRoRGJHUhjjeePKwP9BgCc7dtKlB7QMnIHGPv03hdVPo9ezaQ5mFxdzQdXoLR2" +
        "BFucDtSj1je3e5L9KEnHZ5fHnislBnzSvYR5V8LwTa5mbNS4VHkAv8Eh3WG9tp1S" +
        "/f9ymefKHB7ISlskT7kODCIbr5HHU/n1zXtMRjoslY1A+nFlWiAaIvjnj/C8x0BW" +
        "BkhuSKX/2PbljnmIdGV7mJK9/XUHnyKgZBxXEul2mlvGkrgUvyv+qYsCFsKSSrkB" +
        "1Mj2Ql5xmTMaePMEmvOr6fDAP0OH8cvADEZjx0s/5vvoBFPGGmPrHJluEVS0Fu8I" +
        "9sROg9YjyuhRV0b8xHo=";

    private X509Certificate xmlCert1, xmlCert2;
    private X509CRL xmlCRL1;
    private X509Data xmlX509Data;
    private KeyInfo keyInfo;
    private KeyValue keyValue;
    private DSAKeyValue xmlDSAKeyValue1, xmlDSAKeyValue1NoParams;
    private RSAKeyValue xmlRSAKeyValue1;
    private int numExpectedCerts;
    private int numExpectedCRLs;

    private java.security.cert.X509Certificate javaCert1;
    private java.security.cert.X509Certificate javaCert2;
    private java.security.cert.X509CRL javaCRL1;
    private RSAPublicKey javaRSAPubKey1;
    private DSAPublicKey javaDSAPubKey1;
    private DSAParams javaDSAParams1;

    /**
     * Constructor.
     *
     */
    public KeyInfoHelperTest() {
        super();
    }

    /** {@inheritDoc} */
    protected void setUp() throws Exception {
        super.setUp();

        xmlCert1 = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        xmlCert1.setValue(cert1);

        xmlCert2 = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        xmlCert2.setValue(cert2);

        xmlCRL1 = (X509CRL) buildXMLObject(X509CRL.DEFAULT_ELEMENT_NAME);
        xmlCRL1.setValue(crl1);

        xmlX509Data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        xmlX509Data.getX509Certificates().add(xmlCert1);
        xmlX509Data.getX509Certificates().add(xmlCert2);
        xmlX509Data.getX509CRLs().add(xmlCRL1);

        keyValue = (KeyValue) buildXMLObject(KeyValue.DEFAULT_ELEMENT_NAME);

        keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        keyInfo.getX509Datas().add(xmlX509Data);

        numExpectedCerts = 2;
        numExpectedCRLs = 1;

        javaCert1 = SecurityTestHelper.buildJavaX509Cert(cert1);
        javaCert2 = SecurityTestHelper.buildJavaX509Cert(cert2);
        javaCRL1 = SecurityTestHelper.buildJavaX509CRL(crl1);

        javaDSAPubKey1 = SecurityTestHelper.buildJavaDSAPublicKey(dsaPubKey1);
        javaRSAPubKey1 = SecurityTestHelper.buildJavaRSAPublicKey(rsaPubKey1);

        xmlRSAKeyValue1 = (RSAKeyValue) buildXMLObject(RSAKeyValue.DEFAULT_ELEMENT_NAME);
        Modulus modulus = (Modulus) buildXMLObject(Modulus.DEFAULT_ELEMENT_NAME);
        Exponent exponent = (Exponent) buildXMLObject(Exponent.DEFAULT_ELEMENT_NAME);
        modulus.setValueBigInt(javaRSAPubKey1.getModulus());
        exponent.setValueBigInt(javaRSAPubKey1.getPublicExponent());
        xmlRSAKeyValue1.setModulus(modulus);
        xmlRSAKeyValue1.setExponent(exponent);

        xmlDSAKeyValue1 = (DSAKeyValue) buildXMLObject(DSAKeyValue.DEFAULT_ELEMENT_NAME);
        P p = (P) buildXMLObject(P.DEFAULT_ELEMENT_NAME);
        Q q = (Q) buildXMLObject(Q.DEFAULT_ELEMENT_NAME);
        G g = (G) buildXMLObject(G.DEFAULT_ELEMENT_NAME);
        Y y1 = (Y) buildXMLObject(Y.DEFAULT_ELEMENT_NAME);
        p.setValueBigInt(javaDSAPubKey1.getParams().getP());
        q.setValueBigInt(javaDSAPubKey1.getParams().getQ());
        g.setValueBigInt(javaDSAPubKey1.getParams().getG());
        y1.setValueBigInt(javaDSAPubKey1.getY());
        xmlDSAKeyValue1.setP(p);
        xmlDSAKeyValue1.setQ(q);
        xmlDSAKeyValue1.setG(g);
        xmlDSAKeyValue1.setY(y1);

        xmlDSAKeyValue1NoParams = (DSAKeyValue) buildXMLObject(DSAKeyValue.DEFAULT_ELEMENT_NAME);
        Y y2 = (Y) buildXMLObject(Y.DEFAULT_ELEMENT_NAME);
        y2.setValueBigInt(javaDSAPubKey1.getY());
        xmlDSAKeyValue1NoParams.setY(y2);
        javaDSAParams1 = javaDSAPubKey1.getParams();
    }

    /** Test converting XML X509Certificate to java.security.cert.X509Certificte.
     * @throws CertificateException */
    public void testCertConversionXMLtoJava() throws CertificateException {
        java.security.cert.X509Certificate javaCert = null;
        try {
            javaCert = KeyInfoHelper.getCertificate(xmlCert1);
        } catch (CertificateException e) {
            fail("Conversion from XML X509Certificate format to java.security.cert.X509Certificate failed: " + e);
        }
        assertNotNull("Cert1 was null, failed to convert from XML to Java representation", javaCert);
        assertEquals("Cert1 SubjectDN", cert1SubjectDN,
                javaCert.getSubjectX500Principal().getName(X500Principal.RFC2253));
        assertEquals("Java cert was not the expected value",
                SecurityTestHelper.buildJavaX509Cert(xmlCert1.getValue()), javaCert);

        List<java.security.cert.X509Certificate> javaCertList = null;

        try {
            javaCertList = KeyInfoHelper.getCertificates(xmlX509Data);
        } catch (CertificateException e) {
            fail("Obtaining certs from X509Data failed: " + e);
        }
        assertEquals("# of certs returned", numExpectedCerts, javaCertList.size());
        assertEquals("Cert1 SubjectDN", cert1SubjectDN,
                javaCertList.get(0).getSubjectX500Principal().getName(X500Principal.RFC2253));
        assertEquals("Cert2 SubjectDN", cert2SubjectDN,
                javaCertList.get(1).getSubjectX500Principal().getName(X500Principal.RFC2253));

        try {
            javaCertList = KeyInfoHelper.getCertificates(keyInfo);
        } catch (CertificateException e) {
            fail("Obtaining certs from KeyInfo failed: " + e);
        }
        assertEquals("# of certs returned", numExpectedCerts, javaCertList.size());
        assertEquals("Cert1 SubjectDN", cert1SubjectDN,
                javaCertList.get(0).getSubjectX500Principal().getName(X500Principal.RFC2253));
        assertEquals("Cert2 SubjectDN", cert2SubjectDN,
                javaCertList.get(1).getSubjectX500Principal().getName(X500Principal.RFC2253));
    }

    /** Test converting XML X509CRL to java.security.cert.X509CRL.
     * @throws CRLException
     * @throws CertificateException */
    public void testCRLConversionXMLtoJava() throws CertificateException, CRLException {
        java.security.cert.X509CRL javaCRL = null;
        try {
            javaCRL = KeyInfoHelper.getCRL(xmlCRL1);
        } catch (CRLException e) {
            fail("Conversion from XML X509CRL format to java.security.cert.X509CRL failed: " + e);
        }
        assertNotNull("CRL was null, failed to convert from XML to Java representation", javaCRL);
        assertEquals("CRL IssuerDN", crl1IssuerDN, javaCRL.getIssuerX500Principal().getName(X500Principal.RFC2253));
        assertEquals("Java CRL was not the expected value",
                SecurityTestHelper.buildJavaX509CRL(xmlCRL1.getValue()), javaCRL);

        List<java.security.cert.X509CRL> javaCRLList = null;

        try {
            javaCRLList = KeyInfoHelper.getCRLs(xmlX509Data);
        } catch (CRLException e) {
            fail("Obtaining CRLs from X509Data failed: " + e);
        }
        assertEquals("# of CRLs returned", numExpectedCRLs, javaCRLList.size());
        assertEquals("CRL IssuerDN", crl1IssuerDN,
                javaCRLList.get(0).getIssuerX500Principal().getName(X500Principal.RFC2253));

        try {
            javaCRLList = KeyInfoHelper.getCRLs(keyInfo);
        } catch (CRLException e) {
            fail("Obtaining CRLs from KeInfo failed: " + e);
        }
        assertEquals("# of CRLs returned", numExpectedCRLs, javaCRLList.size());
        assertEquals("CRL IssuerDN", crl1IssuerDN,
                javaCRLList.get(0).getIssuerX500Principal().getName(X500Principal.RFC2253));

    }

    /** Test converting java.security.cert.X509Certificate to XML X509Certificate.
     * @throws CertificateException */
    public void testCertConversionJavaToXML() throws CertificateException {
        X509Certificate xmlCert = null;
        try {
            xmlCert = KeyInfoHelper.buildX509Certificate(javaCert1);
        } catch (CertificateEncodingException e) {
            fail("Conversion from Java X509Certificate to XMLObject failed: " + e);
        }

        assertEquals("Java X509Certificate encoding to XMLObject failed",
                javaCert1, SecurityTestHelper.buildJavaX509Cert(xmlCert.getValue()));
    }

    /** Test converting java.security.cert.X509CRL to XML X509CRL.
     * @throws CRLException
     * @throws CertificateException */
    public void testCRLConversionJavaToXML() throws CertificateException, CRLException {
        X509CRL xmlCRL = null;
        try {
            xmlCRL = KeyInfoHelper.buildX509CRL(javaCRL1);
        } catch (CRLException e) {
            fail("Conversion from Java X509CRL to XMLObject failed: " + e);
        }

        assertEquals("Java X509CRL encoding to XMLObject failed", javaCRL1,
                SecurityTestHelper.buildJavaX509CRL(xmlCRL.getValue()));
    }

    /** Test conversion of DSA public keys from XML to Java security native type. */
    public void testDSAConversionXMLToJava() {
        PublicKey key = null;
        DSAPublicKey dsaKey = null;

        try {
            key = KeyInfoHelper.getDSAKey(xmlDSAKeyValue1);
        } catch (KeyException e) {
            fail("DSA key conversion XML to Java failed: " + e);
        }
        dsaKey = (DSAPublicKey) key;
        assertNotNull("Generated key was not an instance of DSAPublicKey", dsaKey);
        assertEquals("Generated key was not the expected value", javaDSAPubKey1, dsaKey);

        try {
            key = KeyInfoHelper.getDSAKey(xmlDSAKeyValue1NoParams, javaDSAParams1);
        } catch (KeyException e) {
            fail("DSA key conversion XML to Java failed: " + e);
        }
        dsaKey = (DSAPublicKey) key;
        assertNotNull("Generated key was not an instance of DSAPublicKey", dsaKey);
        assertEquals("Generated key was not the expected value", javaDSAPubKey1, dsaKey);

        try {
            key = KeyInfoHelper.getDSAKey(xmlDSAKeyValue1NoParams);
            fail("DSA key conversion XML to Java failed should have thrown an exception but didn't");
        } catch (KeyException e) {
            // do nothing, we expect to fail b/c not complete set of DSAParams
        }
    }

    /** Test conversion of RSA public keys from XML to Java security native type. */
    public void testRSAConversionXMLToJava() {
        PublicKey key = null;
        RSAPublicKey rsaKey = null;

        try {
            key = KeyInfoHelper.getRSAKey(xmlRSAKeyValue1);
        } catch (KeyException e) {
            fail("RSA key conversion XML to Java failed: " + e);
        }
        rsaKey = (RSAPublicKey) key;
        assertNotNull("Generated key was not an instance of RSAPublicKey", rsaKey);
        assertEquals("Generated key was not the expected value", javaRSAPubKey1, rsaKey);
    }

    /** Test conversion of DSA public keys from Java security native type to XML. */
    public void testDSAConversionJavaToXML() {
        DSAKeyValue dsaKeyValue = KeyInfoHelper.buildDSAKeyValue(javaDSAPubKey1);
        assertNotNull("Generated DSAKeyValue was null");
        assertEquals("Generated DSAKeyValue Y component was not the expected value",
                javaDSAPubKey1.getY(), dsaKeyValue.getY().getValueBigInt());
        assertEquals("Generated DSAKeyValue P component was not the expected value",
                javaDSAPubKey1.getParams().getP(), dsaKeyValue.getP().getValueBigInt());
        assertEquals("Generated DSAKeyValue Q component was not the expected value",
                javaDSAPubKey1.getParams().getQ(), dsaKeyValue.getQ().getValueBigInt());
        assertEquals("Generated DSAKeyValue G component was not the expected value",
                javaDSAPubKey1.getParams().getG(), dsaKeyValue.getG().getValueBigInt());
    }

    /** Test conversion of RSA public keys from Java security native type to XML. */
    public void testRSAConversionJavaToXML() {
        RSAKeyValue rsaKeyValue = KeyInfoHelper.buildRSAKeyValue(javaRSAPubKey1);
        assertNotNull("Generated RSAKeyValue was null");
        assertEquals("Generated RSAKeyValue modulus component was not the expected value",
                javaRSAPubKey1.getModulus(), rsaKeyValue.getModulus().getValueBigInt());
        assertEquals("Generated RSAKeyValue exponent component was not the expected value",
                javaRSAPubKey1.getPublicExponent(), rsaKeyValue.getExponent().getValueBigInt());
    }

    /** Tests extracting a DSA public key from a KeyValue. */
    public void testGetDSAKey() {
        keyValue.setRSAKeyValue(null);
        keyValue.setDSAKeyValue(xmlDSAKeyValue1);

        PublicKey pk = null;
        DSAPublicKey dsaKey = null;
        try {
            pk = KeyInfoHelper.getKey(keyValue);
        } catch (KeyException e) {
            fail("Extraction of key from KeyValue failed: " + e);
        }
        assertTrue("Generated key was not an instance of DSAPublicKey", pk instanceof DSAPublicKey);
        dsaKey = (DSAPublicKey) pk;
        assertEquals("Generated key was not the expected value", javaDSAPubKey1, dsaKey);

        keyValue.setDSAKeyValue(null);
    }

    /** Tests extracting a RSA public key from a KeyValue. */
    public void testGetRSAKey() {
        keyValue.setDSAKeyValue(null);
        keyValue.setRSAKeyValue(xmlRSAKeyValue1);

        PublicKey pk = null;
        RSAPublicKey rsaKey = null;
        try {
            pk = KeyInfoHelper.getKey(keyValue);
        } catch (KeyException e) {
            fail("Extraction of key from KeyValue failed: " + e);
        }
        assertTrue("Generated key was not an instance of RSAPublicKey", pk instanceof RSAPublicKey);
        rsaKey = (RSAPublicKey) pk;
        assertEquals("Generated key was not the expected value", javaRSAPubKey1, rsaKey);

        keyValue.setRSAKeyValue(null);
    }

    /** Tests adding a public key as a KeyValue to KeyInfo. */
    public void testAddDSAPublicKey() {
        keyInfo.getKeyValues().clear();

        KeyInfoHelper.addPublicKey(keyInfo, javaDSAPubKey1);
        KeyValue kv = keyInfo.getKeyValues().get(0);
        assertNotNull("KeyValue was null", kv);
        DSAKeyValue dsaKeyValue = kv.getDSAKeyValue();
        assertNotNull("DSAKeyValue was null", dsaKeyValue);

        DSAPublicKey javaKey = null;
        try {
            javaKey = (DSAPublicKey) KeyInfoHelper.getDSAKey(dsaKeyValue);
        } catch (KeyException e) {
            fail("Extraction of Java key failed: " + e);
        }

        assertEquals("Inserted DSA public key was not the expected value", javaDSAPubKey1, javaKey);

        keyInfo.getKeyValues().clear();
    }

    /** Tests adding a public key as a KeyValue to KeyInfo. */
    public void testAddRSAPublicKey() {
       keyInfo.getKeyValues().clear();

        KeyInfoHelper.addPublicKey(keyInfo, javaRSAPubKey1);
        KeyValue kv = keyInfo.getKeyValues().get(0);
        assertNotNull("KeyValue was null", kv);
        RSAKeyValue rsaKeyValue = kv.getRSAKeyValue();
        assertNotNull("RSAKeyValue was null", rsaKeyValue);

        RSAPublicKey javaKey = null;
        try {
            javaKey = (RSAPublicKey) KeyInfoHelper.getRSAKey(rsaKeyValue);
        } catch (KeyException e) {
            fail("Extraction of Java key failed: " + e);
        }

        assertEquals("Inserted RSA public key was not the expected value", javaRSAPubKey1, javaKey);

        keyInfo.getKeyValues().clear();
    }

    /** Tests adding a certificate as a X509Data/X509Certificate to KeyInfo.
     * @throws CertificateException */
    public void testAddX509Certificate() throws CertificateException {
       keyInfo.getX509Datas().clear();

        KeyInfoHelper.addCertificate(keyInfo, javaCert1);
        X509Data x509Data = keyInfo.getX509Datas().get(0);
        assertNotNull("X509Data was null", x509Data);
        X509Certificate x509Cert = x509Data.getX509Certificates().get(0);
        assertNotNull("X509Certificate was null", x509Cert);

        java.security.cert.X509Certificate javaCert = null;
        javaCert = (java.security.cert.X509Certificate) KeyInfoHelper.getCertificate(x509Cert);

        assertEquals("Inserted X509Certificate was not the expected value", javaCert1, javaCert);

        keyInfo.getX509Datas().clear();
    }

    /** Tests adding a CRL as a X509Data/X509CRL to KeyInfo.
     * @throws CRLException */
    public void testAddX509CRL() throws CRLException {
       keyInfo.getX509Datas().clear();

        KeyInfoHelper.addCRL(keyInfo, javaCRL1);
        X509Data x509Data = keyInfo.getX509Datas().get(0);
        assertNotNull("X509Data was null", x509Data);
        X509CRL x509CRL = x509Data.getX509CRLs().get(0);
        assertNotNull("X509CRL was null", x509CRL);

        java.security.cert.X509CRL javaCRL = null;
        javaCRL = (java.security.cert.X509CRL) KeyInfoHelper.getCRL(x509CRL);

        assertEquals("Inserted X509CRL was not the expected value", javaCRL1, javaCRL);

        keyInfo.getX509Datas().clear();
    }

    /** Tests building a new X509SubjectName.*/
    public void testBuildSubjectName() {
        String name = "cn=foobar.example.org, o=Internet2";
        X509SubjectName xmlSubjectName = KeyInfoHelper.buildX509SubjectName(name);
        assertNotNull("Constructed X509SubjectName was null", xmlSubjectName);
        assertEquals("Unexpected subject name value", name, xmlSubjectName.getValue());
    }

    /** Tests building a new X509IssuerSerial.*/
    public void testBuildIssuerSerial() {
        String name = "cn=CA.example.org, o=Internet2";
        BigInteger serialNumber = new BigInteger("42");
        X509IssuerSerial xmlIssuerSerial = KeyInfoHelper.buildX509IssuerSerial(name, serialNumber);
        assertNotNull("Constructed X509IssuerSerial was null", xmlIssuerSerial);

        assertNotNull("Constructed X509IssuerName was null", xmlIssuerSerial.getX509IssuerName());
        assertEquals("Unexpected issuer name value", name, xmlIssuerSerial.getX509IssuerName().getValue());

        assertNotNull("Constructed X509SerialNumber was null", xmlIssuerSerial.getX509SerialNumber());
        assertEquals("Unexpected serial number", serialNumber, xmlIssuerSerial.getX509SerialNumber().getValue());
    }

    /** Tests building a new X509SKI from a certificate containing an SKI value.
     * @throws CertificateException */
    public void testBuildSubjectKeyIdentifier() throws CertificateException {
        byte[] skiValue = Base64.decode(cert1SKIPlainBase64);
        X509SKI xmlSKI = KeyInfoHelper.buildX509SKI(javaCert1);
        assertNotNull("Constructed X509SKI was null", xmlSKI);
        assertFalse("SKI value was empty", DatatypeHelper.isEmpty(xmlSKI.getValue()));
        byte[] xmlValue = Base64.decode(xmlSKI.getValue());
        assertNotNull("Decoded XML SKI value was null", xmlValue);
        assertTrue("Incorrect SKI value", Arrays.equals(skiValue, xmlValue) );

        //Test that a cert with no SKI produces null
        java.security.cert.X509Certificate noExtCert = SecurityTestHelper.buildJavaX509Cert(certNoExtensions);
        assertNotNull(noExtCert);
        X509SKI noExtXMLSKI = KeyInfoHelper.buildX509SKI(noExtCert);
        assertNull("Building X509SKI from cert without SKI should have generated null", noExtXMLSKI);
    }
}


text:
<?php

namespace PHPUnit\Util;

use PHPUnit\Framework\Exception;

class Json
{
    /**
     * Prettify json string
     *
     * @param string $json
     *
     * @return string
     *
     * @throws \PHPUnit\Framework\Exception
     */
    public static function prettify(string $json)
    {
        $decodedJson = \json_decode($json, true);

        if (\json_last_error()) {
            throw new Exception(
                'Cannot prettify invalid json'
            );
        }

        return \json_encode($decodedJson, JSON_PRETTY_PRINT);
    }

    /*
     * To allow comparison of JSON strings, first process them into a consistent
     * format so that they can be compared as strings.
     * @return array ($error, $canonicalized_json)  The $error parameter is used
     * to indicate an error decoding the json.  This is used to avoid ambiguity
     * with JSON strings consisting entirely of 'null' or 'false'.
     */
    public static function canonicalize(string $json)
    {
        $decodedJson = \json_decode($json, true);

        if (\json_last_error()) {
            return [true, null];
        }

        self::recursiveSort($decodedJson);

        $reencodedJson = \json_encode($decodedJson);

        return [false, $reencodedJson];
    }

    /*
     * JSON object keys are unordered while PHP array keys are ordered.
     * Sort all array keys to ensure both the expected and actual values have
     * their keys in the same order.
     */
    private static function recursiveSort(&$json)
    {
        if (false === \is_array($json)) {
            return;
        }

        \ksort($json);

        foreach ($json as $key => &$value) {
            self::recursiveSort($value);
        }
    }
}


text:
//
// © 2016 Max the Cat Studios Ltd.
//
// https://maxthecatstudios.com
// @maxthecatstudio
//
// Created By Desmond Fernando 2016 06 30 11:44 AM
//
//
//

using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle( "UnityTC" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "Max the Cat Studios Ltd." )]
[assembly: AssemblyProduct( "UnityTC" )]
[assembly: AssemblyCopyright( "© Max the Cat Studios Ltd. 2016" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible( false )]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid( "767a600e-eaff-401d-b165-7e624c1f815e" )]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion( "1.0.0.0" )]
[assembly: AssemblyFileVersion( "1.0.0.0" )]


text:
import {Guid} from './Guid';
import {RouteEvent} from "./RouteEvent";

export class PerformanceObject {
  angularVersion:string = '';
  customProperties:Object = {};
  downloadSpeed:number = 0;
  downloadSpeedUnit:string = 'mb/s';
  guid:Guid = new Guid();
  location:Object = {};
  marks:Array<Object> = [];
  measures:Array<Object> = [];
  memory:Object = {};
  navigation:Object = {};
  resources:Array<Object> = [];
  routeEvents:Array<RouteEvent> = [];
  time:Date;
  userAgent:string = '';
  watcherCount:number = 0;

  constructor() {
    this.time = new Date(Date.now());
    return this;
  }
}


text:
"""
Copyright 2012 Pontiflex, Inc.

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.
"""

class HTML(object):
	def __init__(self, html):
		self.html = html
	def __html__(self):
		return self.html
	def __repr__(self):
		return 'Safe HTML: %s' % self.html


text:
Qui se cache derriere Angular ?

Initié en 2009 par Misko Hevery
    et Adam Abrons chez Brat Tech LLC

Le site getangular.com est enregistré

Publié en OpenSource après la faillite de Brat Tech LLC

angular/angular

Misko rejoint Google et commence à travailler sur Google Feedback

Google Feedback devient de plus en plus difficile à maintenir...

Misko parie alors qu'il est capable de réécrire l'application en

2 semaines

tout en améliorant la maintenabilité

Il mettra 3 semaines

A partir de ce moment, Google investit sur Angular

Angular en chiffres

6,465 commits

131 releases

450 contributeurs

Community

14,219 forks

3,343 watch

35,146 stars


text:
<?php

namespace Store\Bundle\BackendBundle\Controller;

use Store\Bundle\BackendBundle\Entity\BankInfo;
use Store\Bundle\BackendBundle\Form\BankInfoType;
use Symfony\Component\HttpFoundation\Request;

class BankController extends CoreController
{
    public function indexAction(Request $request)
    {
        $bank = $this->get('bank.repo')->findAll();
        if(isset($bank[0]))
        {
            $bank = $bank[0];
        }
        else
        {
            $bank = new BankInfo();
        }

        $em = $this->getDoctrine()->getManager();

        $form = $this->createNewForm($request,new BankInfoType(),$bank);
        if($form->isValid())
        {
            $em->persist($bank);
            $em->flush();
            $this->addFlashMessage('success' , '银行汇款信息更新成功');
            return $this->redirect($this->generateUrl('bankinfo'));
        }

        return $this->render('StoreBackendBundle:Bank:index.html.twig' , ['form'=>$form->createView()]);
    }
}


text:
package com.viesis.viescraft.client;

import com.viesis.viescraft.api.BlocksVC;

import net.minecraft.block.Block;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;

public final class InitBlocksVCRender extends BlocksVC {

	public static void registerBlockRender()
	{
		registerRender(airship_workbench);
		//registerRender(battery_charger);
	}

	public static void registerBlockRenderTEMP()
	{

	}

	public static void registerRender(Block block)
	{
		Item item = Item.getItemFromBlock(block);
		ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(item.getRegistryName().toString(), "inventory"));
	}

	public static void registerRender(Block block, int meta, String file)
	{
		Item item = Item.getItemFromBlock(block);
		ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(item.getRegistryName().toString(), "inventory"));
	}
}


text:
"""This program examines success/fail history for Chrome/ium OS builds and
checks in a LKGM version for Chrome OS for other consumers.
"""

import distutils.version
import logging
import os
import shutil
import tempfile
from chromite.buildbot import cbuildbot_config
from chromite.buildbot import constants
from chromite.buildbot import manifest_version
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import gclient
from chromite.lib import gs
from chromite.lib import osutils

class LKGMNotFound(Exception):
  """Raised if a newer valid LKGM could not be found."""

class LKGMNotCommitted(Exception):
  """Raised if we could not submit a new LKGM."""

class ChromeCommitter(object):
  """Committer object responsible for obtaining a new LKGM and committing it."""

  _COMMIT_MSG = ('Automated Commit: Committing new LKGM version %(version)s '
                 'for chromeos.')
  _CANDIDATES_TO_CONSIDER = 10

  _SLEEP_TIMEOUT = 30
  _TREE_TIMEOUT = 7200

  def __init__(self, checkout_dir, dryrun):
    self._checkout_dir = checkout_dir
    self._dryrun = dryrun
    self._lkgm = None
    self._old_lkgm = None

  def CheckoutChromeLKGM(self):
    """Checkout chromeos LKGM file for chrome into tmp checkout dir."""
    # We function only on an empty directory.
    lkgm_dir = '/'.join([gclient.CHROME_COMMITTER_URL,
                         os.path.dirname(constants.SVN_CHROME_LKGM)])

    # We checkout the bare necessities to get the .svn/file needed to commit.
    cros_build_lib.RunCommand(['svn', 'checkout', '--depth=empty', lkgm_dir,
                               self._checkout_dir])
    cros_build_lib.RunCommand(['svn', 'update', constants.CHROME_LKGM_FILE],
                              cwd=self._checkout_dir)

    self._old_lkgm = osutils.ReadFile(
        os.path.join(self._checkout_dir, constants.CHROME_LKGM_FILE))

  def _GetLatestCanaryVersions(self):
    """Returns the latest CANDIDATES_TO_CONSIDER canary versions."""
    gs_handle = gs.GSContext()
    version_paths = gs_handle.LS(
        manifest_version.BUILD_STATUS_URL).output.splitlines()

    # Strip gs://<path> prefix and trailing /'s.
    versions = [os.path.basename(v.rstrip('/')) for v in version_paths]

    lv = distutils.version.LooseVersion
    # We only care about canary versions which always end in 0.0.
    canary_versions = [v for v in versions if v.endswith('.0.0')]
    new_canary_versions = [v for v in canary_versions
                           if lv(v) > lv(self._old_lkgm)]
    return sorted(new_canary_versions, key=lv,
                  reverse=True)[0:self._CANDIDATES_TO_CONSIDER]

  def FindNewLKGM(self):
    """Finds a new LKGM for chrome from previous chromeos releases."""
    versions = self._GetLatestCanaryVersions()
    if not versions:
      raise LKGMNotFound('No valid LKGM found newer than the old LKGM.')

    canaries = cbuildbot_config.GetCanariesForChromeLKGM()
    logging.info('Considering the following versions: %s', ' '.join(versions))
    logging.info('Using scores from the following canaries: %s',
                 ' '.join(canaries))

    # Scores are based on passing builders.
    version_scores = {}
    for version in versions:
      for builder in canaries:
        status = manifest_version.BuildSpecsManager.GetBuildStatus(
            builder, version, retries=0)
        if status:
          if status.Passed():
            version_scores[version] = version_scores.get(version, 0) + 1
          elif status.Failed():
            # We don't consider builds with any reporting failures.
            version_scores[version] = 0
            break

      logging.info('Version %s had score %d', version,
                   version_scores.get(version, 0))

    # We want to get the version with the highest score. In case of a tie, we
    # want to choose the highest version.
    lkgm = max((v, k) for k, v in version_scores.iteritems())[1]
    if not version_scores[lkgm] > 0:
      raise LKGMNotFound('No valid LKGM found. Scores are too low.')

    self._lkgm = lkgm

  def CommitNewLKGM(self):
    """Commits the new LKGM file using our template commit message."""
    lv = distutils.version.LooseVersion
    if not self._lkgm and not lv(self._lkgm) < lv(self._old_lkgm):
      raise LKGMNotFound('No valid LKGM found. Did you run FindNewLKGM?')

    # Add the new versioned file.
    osutils.WriteFile(
        os.path.join(self._checkout_dir, constants.CHROME_LKGM_FILE),
        self._lkgm)

    add_cmd = ['svn', 'add', constants.CHROME_LKGM_FILE]
    cros_build_lib.RunCommand(add_cmd, cwd=self._checkout_dir)

    # Commit it!
    commit_cmd = ['svn', 'commit', '--message',
                  self. _COMMIT_MSG % dict(version=self._lkgm)]

    if not cros_build_lib.TreeOpen(gclient.STATUS_URL, self._SLEEP_TIMEOUT,
                                   max_timeout=self._TREE_TIMEOUT):
      raise LKGMNotCommitted('Chromium Tree is closed')

    # Sadly svn commit does not have a dryrun option.
    if not self._dryrun:
      try:
        cros_build_lib.RunCommand(commit_cmd, cwd=self._checkout_dir)
      except cros_build_lib.RunCommandError as e:
        raise LKGMNotCommitted('Could not submit LKGM: %r' % e)
    else:
      logging.info('Would have run: %s', ' '.join(commit_cmd))

def _GetParser():
  """Returns the parser to use for this module."""
  parser = commandline.ArgumentParser(usage=__doc__)
  parser.add_argument('--dryrun', action='store_true', default=False,
                      help="Find the next LKGM but don't commit it.")
  return parser

def main(argv):
  parser = _GetParser()
  args = parser.parse_args(argv)

  checkout_dir = tempfile.mkdtemp(prefix='cbr_chrome_checkout')
  try:
    committer = ChromeCommitter(checkout_dir, dryrun=args.dryrun)
    committer.CheckoutChromeLKGM()
    committer.FindNewLKGM()
    committer.CommitNewLKGM()
    return 0
  finally:
    shutil.rmtree(checkout_dir)


text:
//---------------------------------------------------------------------------//

//---------------------------------------------------------------------------//
/*!
 * \brief DTK_ClassicMeshElementLocalMap_impl.hpp
 * \author Stuart R. Slattery
 * \brief Forward and reverse local mappings for entities.
 */
//---------------------------------------------------------------------------//

#ifndef DTK_CLASSICMESHELEMENTLOCALMAP_IMPL_HPP
#define DTK_CLASSICMESHELEMENTLOCALMAP_IMPL_HPP

#include "DTK_ClassicMeshElementExtraData.hpp"
#include "DTK_DBC.hpp"
#include "DTK_IntrepidCellLocalMap.hpp"

#include <Shards_CellTopology.hpp>

#include <Intrepid_FieldContainer.hpp>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Constructor.
template <class Mesh>
ClassicMeshElementLocalMap<Mesh>::ClassicMeshElementLocalMap(
    const Teuchos::RCP<ClassicMesh<Mesh>> &mesh )
    : d_mesh( mesh )
    , d_inclusion_tol( 1.0e-6 )
{ /* ... */
}

//---------------------------------------------------------------------------//
// Set parameters for mapping.
template <class Mesh>
void ClassicMeshElementLocalMap<Mesh>::setParameters(
    const Teuchos::ParameterList &parameters )
{
    if ( parameters.isParameter( "Point Inclusion Tolerance" ) )
    {
        d_inclusion_tol = parameters.get<double>( "Point Inclusion Tolerance" );
    }
}

//---------------------------------------------------------------------------//
// Return the entity measure with respect to the parameteric dimension (volume
// for a 3D entity, area for 2D, and length for 1D).
template <class Mesh>
double ClassicMeshElementLocalMap<Mesh>::measure( const Entity &entity ) const
{
    // Get the block id and topology.
    int block_id = Teuchos::rcp_dynamic_cast<ClassicMeshElementExtraData>(
                       entity.extraData() )
                       ->d_block_id;
    shards::CellTopology entity_topo = d_mesh->getBlockTopology( block_id );

    // Get the entity coordinates.
    Intrepid::FieldContainer<double> entity_coords =
        d_mesh->getElementNodeCoordinates( entity.id(), block_id );

    // Compute the measure.
    return IntrepidCellLocalMap::measure( entity_topo, entity_coords );
}

//---------------------------------------------------------------------------//
// Return the centroid of the entity.
template <class Mesh>
void ClassicMeshElementLocalMap<Mesh>::centroid(
    const Entity &entity, const Teuchos::ArrayView<double> &centroid ) const
{
    // Get the block id and topology.
    int block_id = Teuchos::rcp_dynamic_cast<ClassicMeshElementExtraData>(
                       entity.extraData() )
                       ->d_block_id;
    shards::CellTopology entity_topo = d_mesh->getBlockTopology( block_id );

    // Get the entity coordinates.
    Intrepid::FieldContainer<double> entity_coords =
        d_mesh->getElementNodeCoordinates( entity.id(), block_id );

    // Compute the centroid of the element.
    IntrepidCellLocalMap::centroid( entity_topo, entity_coords, centroid );
}

//---------------------------------------------------------------------------//
// Perform a safeguard check for mapping a point to the reference space
// of an entity using the given tolerance.
template <class Mesh>
bool ClassicMeshElementLocalMap<Mesh>::isSafeToMapToReferenceFrame(
    const Entity &entity,
    const Teuchos::ArrayView<const double> &physical_point ) const
{
    return EntityLocalMap::isSafeToMapToReferenceFrame( entity,
                                                        physical_point );
}

//---------------------------------------------------------------------------//
// Map a point to the reference space of an entity. Return the parameterized
// point.
template <class Mesh>
bool ClassicMeshElementLocalMap<Mesh>::mapToReferenceFrame(
    const Entity &entity,
    const Teuchos::ArrayView<const double> &physical_point,
    const Teuchos::ArrayView<double> &reference_point ) const
{
    // Get the block id and topology.
    int block_id = Teuchos::rcp_dynamic_cast<ClassicMeshElementExtraData>(
                       entity.extraData() )
                       ->d_block_id;
    shards::CellTopology entity_topo = d_mesh->getBlockTopology( block_id );

    // Get the entity coordinates.
    Intrepid::FieldContainer<double> entity_coords =
        d_mesh->getElementNodeCoordinates( entity.id(), block_id );

    // Use the cell to perform the element mapping.
    return IntrepidCellLocalMap::mapToReferenceFrame(
        entity_topo, entity_coords, physical_point, reference_point );
}

//---------------------------------------------------------------------------//
// Determine if a reference point is in the parameterized space of an entity.
template <class Mesh>
bool ClassicMeshElementLocalMap<Mesh>::checkPointInclusion(
    const Entity &entity,
    const Teuchos::ArrayView<const double> &reference_point ) const
{
    // Get the block id and topology.
    int block_id = Teuchos::rcp_dynamic_cast<ClassicMeshElementExtraData>(
                       entity.extraData() )
                       ->d_block_id;
    shards::CellTopology entity_topo = d_mesh->getBlockTopology( block_id );

    // Get the entity coordinates.
    Intrepid::FieldContainer<double> entity_coords =
        d_mesh->getElementNodeCoordinates( entity.id(), block_id );

    // Check point inclusion in the element.
    return IntrepidCellLocalMap::checkPointInclusion(
        entity_topo, reference_point, d_inclusion_tol );
}

//---------------------------------------------------------------------------//
// Map a reference point to the physical space of an entity.
template <class Mesh>
void ClassicMeshElementLocalMap<Mesh>::mapToPhysicalFrame(
    const Entity &entity,
    const Teuchos::ArrayView<const double> &reference_point,
    const Teuchos::ArrayView<double> &physical_point ) const
{
    // Get the block id and topology.
    int block_id = Teuchos::rcp_dynamic_cast<ClassicMeshElementExtraData>(
                       entity.extraData() )
                       ->d_block_id;
    shards::CellTopology entity_topo = d_mesh->getBlockTopology( block_id );

    // Get the entity coordinates.
    Intrepid::FieldContainer<double> entity_coords =
        d_mesh->getElementNodeCoordinates( entity.id(), block_id );

    // Map from the element.
    IntrepidCellLocalMap::mapToPhysicalFrame( entity_topo, entity_coords,
                                              reference_point, physical_point );
}

//---------------------------------------------------------------------------//
// Compute the normal on a face (3D) or edge (2D) at a given reference point.
template <class Mesh>
void ClassicMeshElementLocalMap<Mesh>::normalAtReferencePoint(
    const Entity &entity, const Entity &parent_entity,
    const Teuchos::ArrayView<const double> &reference_point,
    const Teuchos::ArrayView<double> &normal ) const
{
    bool not_implemented = true;
    DTK_INSIST( !not_implemented );
}

//---------------------------------------------------------------------------//

} // end namespace DataTransferKit

#endif // end  DTK_CLASSICMESHELEMENTLOCALMAP_IMPL_HPP

//---------------------------------------------------------------------------//
// end DTK_ClassicMeshElementLocalMap_impl.hpp
//---------------------------------------------------------------------------//


text:
import * as paper from 'paper';

export function sizeToPoint(size: paper.Size): paper.Point {
	return <any>size
}

export function degreesToRadians(angle: number): number {
	return 2 * Math.PI * angle / 360
}

export function createArc(center: paper.Point, radius: number, angleDegrees: number){
	let angleRadians = degreesToRadians(angleDegrees)
    return {
        from: {
            x: center.x + radius,
            y: center.y
        },
        through: {
            x: center.x + Math.cos(-angleRadians / 2) * radius,
            y: center.y + Math.sin(-angleRadians / 2) * radius
        },
        to: {
            x: center.x + Math.cos(-angleRadians) * radius,
            y: center.y + Math.sin(-angleRadians) * radius
        }
    }
}


text:
package main

// The available subcommand searches the repo for packages using the filter provided. The default
// filter is an empty string and will return all packages.

import (
	"context"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strings"

	"github.com/google/googet/client"
	"github.com/google/googet/goolib"
	"github.com/google/logger"
	"github.com/google/subcommands"
)

type availableCmd struct {
	info    bool
	sources string
}

func (*availableCmd) Name() string     { return "available" }
func (*availableCmd) Synopsis() string { return "list available packages" }
func (*availableCmd) Usage() string {
	return fmt.Sprintf(`%s available [-sources repo1,repo2...] [-info] [<initial>]:
	List available packages beginning with an initial string,
	if no initial string is provided all available packages will be listed.
`, filepath.Base(os.Args[0]))
}

func (cmd *availableCmd) SetFlags(f *flag.FlagSet) {
	f.BoolVar(&cmd.info, "info", false, "display package info")
	f.StringVar(&cmd.sources, "sources", "", "comma separated list of sources, setting this overrides local .repo files")
}

func (cmd *availableCmd) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	exitCode := subcommands.ExitFailure

	var filter string
	switch f.NArg() {
	case 0:
		filter = ""
	case 1:
		filter = f.Arg(0)
	default:
		fmt.Fprintln(os.Stderr, "Excessive arguments")
		f.Usage()
		return subcommands.ExitUsageError
	}

	repos, err := buildSources(cmd.sources)
	if err != nil {
		logger.Fatal(err)
	}
	if repos == nil {
		logger.Fatal("No repos defined, create a .repo file or pass using the -sources flag.")
	}

	m := make(map[string][]string)
	rm := client.AvailableVersions(ctx, repos, filepath.Join(rootDir, cacheDir), cacheLife, proxyServer)
	for r, pl := range rm {
		for _, p := range pl {
			m[r] = append(m[r], p.PackageSpec.Name+"."+p.PackageSpec.Arch+"."+p.PackageSpec.Version)
		}
	}

	for r, pl := range m {
		logger.Infof("Searching %q for packages matching filter %q.", r, filter)
		sort.Strings(pl)
		i := sort.SearchStrings(pl, filter)
		if i >= len(pl) || !strings.Contains(pl[i], filter) {
			continue
		}
		if !cmd.info {
			fmt.Println(r)
		}
		for _, p := range pl {
			if strings.Contains(p, filter) {
				exitCode = subcommands.ExitSuccess
				pi := goolib.PkgNameSplit(p)
				if cmd.info {
					repo(pi, rm)
					continue
				}
				fmt.Println(" ", pi.Name+"."+pi.Arch+" "+pi.Ver)
			}
		}
	}

	if exitCode != subcommands.ExitSuccess {
		fmt.Fprintf(os.Stderr, "No package matching filter %q available in any repo.\n", filter)
	}
	return exitCode
}

func repo(pi goolib.PackageInfo, rm client.RepoMap) {
	for r, pl := range rm {
		for _, p := range pl {
			if p.PackageSpec.Name == pi.Name && p.PackageSpec.Arch == pi.Arch && p.PackageSpec.Version == pi.Ver {
				info(p.PackageSpec, r)
				return
			}
		}
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>wyrzyk.archetypes</groupId>
    <artifactId>atlassian-connect-plugin</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>atlassian-connect-plugin</name>
    <description>Plugin description</description>
    <organization>
        <name>Example, Inc.</name>
        <url>http://example.com</url>
    </organization>
    <build>
        <finalName>atlassian-connect-plugin</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <compilerId>javac-with-errorprone</compilerId>
                    <forceJavacCompilerUse>true</forceJavacCompilerUse>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.plexus</groupId>
                        <artifactId>plexus-compiler-javac-errorprone</artifactId>
                        <version>2.7</version>
                    </dependency>
                    <dependency>
                        <groupId>com.google.errorprone</groupId>
                        <artifactId>error_prone_core</artifactId>
                        <version>2.0.9</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <id>generate</id>
                        <phase>generate-sources</phase>
                        <configuration>
                            <tasks>
                                <echo message="Updating atlassian-connect.json ..."/>
                                <tstamp>
                                    <format property="BUILD_TIME" pattern="yyyy-MM-dd HH:mm:ss"/>
                                </tstamp>
                                <copy file="atlassian-connect.json" tofile="src/main/webapp/atlassian-connect.json" overwrite="true"/>
                                <replace file="src/main/webapp/atlassian-connect.json">
                                    <replacefilter token="@name@" value="${project.name}"/>
                                    <replacefilter token="@description@" value="${project.description}"/>
                                    <replacefilter token="@pluginKey@" value="${project.groupId}.${project.artifactId}"/>
                                    <replacefilter token="@vendorName@" value="${project.organization.name}"/>
                                    <replacefilter token="@vendorUrl@" value="${project.organization.url}"/>
                                </replace>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.eluder.coveralls</groupId>
                <artifactId>coveralls-maven-plugin</artifactId>
                <version>4.1.0</version>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.6.201602180812</version>
                <executions>
                    <execution>
                        <id>prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.3.7.v20160115</version>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>io.leansoft</groupId>
            <artifactId>atlassian-connect-java-authentication</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--Spring Core dependencies-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--MVC/Rest dependencies -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Data dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${spring-data.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${entitymanager.version}</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.185</version>
        </dependency>

        <!-- logs-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
        </dependency>

        <!-- Test dependencies-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>spring-mock-mvc</artifactId>
            <version>${rest-assured.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.4.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jooq</groupId>
            <artifactId>joor</artifactId>
            <version>0.9.5</version>
            <scope>test</scope>
        </dependency>
        <!-- Jwt and dependencies -->
        <dependency>
            <groupId>com.atlassian.jwt</groupId>
            <artifactId>jwt-core</artifactId>
            <version>${jwt.version}</version>
        </dependency>
        <dependency>
            <groupId>com.atlassian.jwt</groupId>
            <artifactId>jwt-api</artifactId>
            <version>${jwt.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- Util dependencies-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.8</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>atlassian-public</id>
            <url>https://maven.atlassian.com/repository/public</url>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
                <checksumPolicy>warn</checksumPolicy>
            </snapshots>
            <releases>
                <enabled>true</enabled>
                <checksumPolicy>warn</checksumPolicy>
            </releases>
        </repository>
        <repository>
            <id>sonatype-snapshots</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
                <checksumPolicy>warn</checksumPolicy>
            </snapshots>
        </repository>
    </repositories>

    <properties>
        <jersey.version>2.22.2</jersey.version>
        <spring.version>4.2.5.RELEASE</spring.version>
        <entitymanager.version>5.1.0.Final</entitymanager.version>
        <spring-data.version>1.10.1.RELEASE</spring-data.version>
        <rest-assured.version>2.9.0</rest-assured.version>
        <jwt.version>1.6.0-0005</jwt.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Learn how the browser constructs the DOM and CSSOM trees.

{# wf_updated_on: 2014-09-11 #}
{# wf_published_on: 2014-03-31 #}

# Constructing the Object Model {: .page-title }

{% include "web/_shared/contributors/ilyagrigorik.html" %}

Before the browser can render the page, it needs to construct the DOM and CSSOM trees. As a result, we need to ensure that we deliver both the HTML and CSS to the browser as quickly as possible.

### TL;DR {: .hide-from-toc }
- Bytes → characters → tokens → nodes → object model.
- HTML markup is transformed into a Document Object Model (DOM); CSS markup is transformed into a CSS Object Model (CSSOM).
- DOM and CSSOM are independent data structures.
- Chrome DevTools Timeline allows us to capture and inspect the construction and processing costs of DOM and CSSOM.

## Document Object Model (DOM)

{% includecode content_path="web/fundamentals/performance/critical-rendering-path/_code/basic_dom.html" region_tag="full" adjust_indentation="auto" %}

[Try it](https://googlesamples.github.io/web-fundamentals/fundamentals/performance/critical-rendering-path/basic_dom.html){: target="_blank" .external }

Let's start with the simplest possible case: a plain HTML page with some text and a single image. How does the browser process this page?

1. **Conversion:** The browser reads the raw bytes of HTML off the disk or network, and translates them to individual characters based on specified encoding of the file (for example, UTF-8).
1. **Tokenizing:** The browser converts strings of characters into distinct tokens—as specified by the [W3C HTML5 standard](http://www.w3.org/TR/html5/){: .external }; for example, "<html>", "<body>"—and other strings within angle brackets. Each token has a special meaning and its own set of rules.
1. **Lexing:** The emitted tokens are converted into "objects," which define their properties and rules.
1. **DOM construction:** Finally, because the HTML markup defines relationships between different tags (some tags are contained within other tags) the created objects are linked in a tree data structure that also captures the parent-child relationships defined in the original markup: the _HTML_ object is a parent of the _body_ object, the _body_ is a parent of the _paragraph_ object, and so on.

**The final output of this entire process is the Document Object Model (DOM) of our simple page, which the browser uses for all further processing of the page.**

Every time the browser processes HTML markup, it goes through all of the steps above: convert bytes to characters, identify tokens, convert tokens to nodes, and build the DOM tree. This entire process can take some time, especially if we have a large amount of HTML to process.

Note: We're assuming that you have basic familiarity with Chrome DevTools - that is, you know how to capture a network waterfall or record a timeline. If you need a quick refresher, check out the Chrome DevTools documentation; if you're new to DevTools, we recommend that you take the Codeschool Discover DevTools course.

If you open up Chrome DevTools and record a timeline while the page is loaded, you can see the actual time taken to perform this step—in the example above, it took us ~5ms to convert a chunk of HTML into a DOM tree. For a larger page, this process could take significantly longer. When creating smooth animations, this can easily become a bottleneck if the browser has to process large amounts of HTML.

The DOM tree captures the properties and relationships of the document markup, but it doesn't tell us how the element will look when rendered. That's the responsibility of the CSSOM.

## CSS Object Model (CSSOM)

While the browser was constructing the DOM of our simple page, it encountered a link tag in the head section of the document referencing an external CSS stylesheet: style.css. Anticipating that it needs this resource to render the page, it immediately dispatches a request for this resource, which comes back with the following content:

{% includecode content_path="web/fundamentals/performance/critical-rendering-path/_code/style.css" region_tag="full" adjust_indentation="auto" %}

We could have declared our styles directly within the HTML markup (inline), but keeping our CSS independent of HTML allows us to treat content and design as separate concerns: designers can work on CSS, developers can focus on HTML, and so on.

As with HTML, we need to convert the received CSS rules into something that the browser can understand and work with. Hence, we repeat the HTML process, but for CSS instead of HTML:

The CSS bytes are converted into characters, then tokens, then nodes, and finally they are linked into a tree structure known as the "CSS Object Model" (CSSOM):

Why does the CSSOM have a tree structure? When computing the final set of styles for any object on the page, the browser starts with the most general rule applicable to that node (for example, if it is a child of a body element, then all body styles apply) and then recursively refines the computed styles by applying more specific rules; that is, the rules "cascade down."

To make it more concrete, consider the CSSOM tree above. Any text contained within the _span_ tag that is placed within the body element, has a font size of 16 pixels and has red text—the font-size directive cascades down from the body to the span. However, if a span tag is child of a paragraph (p) tag, then its contents are not displayed.

Also, note that the above tree is not the complete CSSOM tree and only shows the styles we decided to override in our stylesheet. Every browser provides a default set of styles also known as "user agent styles"—that's what we see when we don't provide any of our own—and our styles simply override these defaults (for example, [default IE styles](http://www.iecss.com/){: .external }).

To find out how long the CSS processing takes you can record a timeline in DevTools and look for "Recalculate Style" event: unlike DOM parsing, the timeline doesn't show a separate "Parse CSS" entry, and instead captures parsing and CSSOM tree construction, plus the recursive calculation of computed styles under this one event.

Our trivial stylesheet takes ~0.6ms to process and affects eight elements on the page—not much, but once again, not free. However, where did the eight elements come from? The CSSOM and DOM are independent data structures! Turns out, the browser is hiding an important step. Next, lets talk about the [render tree](/web/fundamentals/performance/critical-rendering-path/render-tree-construction) that links the DOM and CSSOM together.


text:
package com.qaprosoft.carina.demo;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;

import org.apache.ibatis.session.SqlSession;
import org.testng.annotations.Test;

import com.qaprosoft.carina.core.foundation.IAbstractTest;
import com.zebrunner.agent.core.annotation.TestLabel;

import com.qaprosoft.carina.demo.db.mappers.UserMapper;
import com.qaprosoft.carina.demo.db.mappers.UserPreferenceMapper;
import com.qaprosoft.carina.demo.db.models.User;
import com.qaprosoft.carina.demo.db.models.User.Status;
import com.qaprosoft.carina.demo.utils.ConnectionFactory;
import com.qaprosoft.carina.demo.db.models.UserPreference;

/**
 * This sample shows how create DB test.
 *
 * @author qpsdemo
 */
public class DBSampleTest implements IAbstractTest {

	private static User USER = new User() {
		{
			setUsername("bmarley");
			setFirstName("Bob");
			setLastName("Marley");
			setStatus(Status.ACTIVE);
		}
	};

	private static UserPreference USER_PREFERENCE = new UserPreference() {
		{
			setName(Name.DEFAULT_DASHBOARD);
			setValue("Default");
		}
	};

	@Test
	@TestLabel(name = "feature", value = "database")
	public void createUser() {
		try (SqlSession session = ConnectionFactory.getSqlSessionFactory().openSession(true)) {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			userMapper.create(USER);
			checkUser(userMapper.findById(USER.getId()));
		}
	}

	@Test(dependsOnMethods = "createUser")
	@TestLabel(name = "feature", value = "database")
	public void createUserPreference() {
		try (SqlSession session = ConnectionFactory.getSqlSessionFactory().openSession(true)) {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			UserPreferenceMapper userPreferenceMapper = session.getMapper(UserPreferenceMapper.class);
			USER_PREFERENCE.setUserId(USER.getId());
			userPreferenceMapper.create(USER_PREFERENCE);
			checkUserPreference(userMapper.findById(USER.getId()).getPreferences().get(0));
		}
	}

	@Test(dependsOnMethods = "createUserPreference")
	@TestLabel(name = "feature", value = "database")
	public void updateUser() {
		try (SqlSession session = ConnectionFactory.getSqlSessionFactory().openSession(true)) {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			USER.setUsername("rjohns");
			USER.setFirstName("Roy");
			USER.setLastName("Johns");
			USER.setStatus(Status.INACTIVE);
			userMapper.update(USER);
			checkUser(userMapper.findById(USER.getId()));
		}
	}

	@Test(dependsOnMethods = "updateUser")
	@TestLabel(name = "feature", value = "database")
	public void deleteUser() {
		try (SqlSession session = ConnectionFactory.getSqlSessionFactory().openSession(true)) {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			userMapper.delete(USER);
			assertNull(userMapper.findById(USER.getId()));
		}
	}

	private void checkUser(User user) {
		assertEquals(user.getUsername(), USER.getUsername(), "User name must match");
		assertEquals(user.getFirstName(), USER.getFirstName(), "First name must match");
		assertEquals(user.getLastName(), USER.getLastName(), "Last name must match");
		assertEquals(user.getEmail(), USER.getEmail(), "Email must match");
	}

	private void checkUserPreference(UserPreference userPreference) {
		assertEquals(userPreference.getName(), USER_PREFERENCE.getName(), "Preference name must match");
		assertEquals(userPreference.getValue(), USER_PREFERENCE.getValue(), "Preference value must match");
		assertEquals(userPreference.getUserId(), USER_PREFERENCE.getUserId(), "Preference user id must match");
	}
}


text:
// This config file is intended to configure artificially fast uPy build for
// synthetic benchmarking, at the expense of features supported and memory
// usage. This config is not intended to be used in production.

#define MICROPY_PY___FILE__ (0)
// 91 is a magic number proposed by @dpgeorge, which make pystone run ~ at tie
// with CPython 3.4.
#define MICROPY_MODULE_DICT_SIZE (91)


text:
package org.apache.falcon.regression;

import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.entity.v0.Frequency.TimeUnit;
import org.apache.falcon.regression.core.bundle.Bundle;
import org.apache.falcon.regression.core.helpers.ColoHelper;
import org.apache.falcon.regression.core.util.OozieUtil;
import org.apache.falcon.regression.core.util.AssertUtil;
import org.apache.falcon.regression.core.util.TimeUtil;
import org.apache.falcon.regression.core.util.BundleUtil;
import org.apache.falcon.regression.core.util.InstanceUtil;
import org.apache.falcon.regression.core.util.OSUtil;
import org.apache.falcon.regression.testHelper.BaseTestClass;
import org.apache.log4j.Logger;
import org.apache.oozie.client.CoordinatorAction;
import org.apache.oozie.client.Job;
import org.apache.oozie.client.OozieClient;
import org.apache.oozie.client.OozieClientException;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * EL Expression Current and last week test.
 */

@Test(groups = { "distributed", "embedded" })
public class ELExpCurrentAndLastWeekTest extends BaseTestClass {

    private ColoHelper cluster = servers.get(0);
    private OozieClient clusterOC = serverOC.get(0);
    private String baseTestDir = cleanAndGetTestDir();
    private String aggregateWorkflowDir = baseTestDir + "/aggregator";
    private static final Logger LOGGER = Logger.getLogger(ELExpCurrentAndLastWeekTest.class);

    @BeforeClass(alwaysRun = true)
    public void createTestData() throws Exception {
        LOGGER.info("in @BeforeClass");
        uploadDirToClusters(aggregateWorkflowDir, OSUtil.RESOURCES_OOZIE);

        Bundle bundle = BundleUtil.readELBundle();
        bundle.generateUniqueBundle(this);
        bundle = new Bundle(bundle, cluster);

        bundle.setInputFeedDataPath(baseTestDir + "/testData" + MINUTE_DATE_PATTERN);
        bundle.setProcessWorkflow(aggregateWorkflowDir);

    }

    @BeforeMethod(alwaysRun = true)
    public void setUp() throws Exception {
        String processStart = "2015-02-17T10:30Z";
        String processEnd = "2015-02-17T10:50Z";
        bundles[0] = BundleUtil.readELBundle();
        bundles[0] = new Bundle(bundles[0], cluster);
        bundles[0].generateUniqueBundle(this);
        bundles[0].setInputFeedDataPath(baseTestDir + "/testData" + MINUTE_DATE_PATTERN);
        bundles[0].setOutputFeedLocationData(baseTestDir + "/output" + MINUTE_DATE_PATTERN);
        bundles[0].setInputFeedPeriodicity(5, TimeUnit.minutes);
        bundles[0].setInputFeedValidity("2010-04-01T00:00Z", "2099-04-01T00:00Z");
        LOGGER.info("processStart: " + processStart + " processEnd: " + processEnd);
        bundles[0].setProcessValidity(processStart, processEnd);
        bundles[0].setProcessPeriodicity(5, TimeUnit.minutes);
        bundles[0].setProcessWorkflow(aggregateWorkflowDir);
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown() {
        removeTestClassEntities();
    }

    /* Test cases to check currentWeek and lastWeek EL-Expressions.
    * Finding the missing dependencies of coordiantor based on
    * given el definition in entity and creating them.
    * These should match with the expected missing dependencies.
    * In case they dont match, the test should fail.
    *
    * */
    @Test(groups = {"singleCluster"}, dataProvider = "EL-DP-Cases")
    public void currentAndLastWeekTest(String startInstance, String endInstance,
            String firstDep, String endDep) throws Exception {
        bundles[0].setDatasetInstances(startInstance, endInstance);
        bundles[0].submitFeedsScheduleProcess(prism);
        AssertUtil.checkStatus(clusterOC, EntityType.PROCESS, bundles[0], Job.Status.RUNNING);

        InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0);
        List<String> missingDependencies = getMissingDependencies(clusterOC, bundles[0].getProcessName());
        OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, bundles[0].getProcessName(), 0);
        InstanceUtil.waitTillInstanceReachState(clusterOC, bundles[0].getProcessName(), 1,
                CoordinatorAction.Status.SUCCEEDED, EntityType.PROCESS);
        List<String> qaDependencies = getQADepedencyList(bundles[0], firstDep, endDep);
        Assert.assertTrue(matchDependencies(missingDependencies, qaDependencies));
    }

    @DataProvider(name = "EL-DP-Cases")
    public Object[][] getELData() {
        return new Object[][]{
            {"currentWeek('WED',2,15)", "currentWeek('WED',2,25)", "2015-02-11T02:15Z", "2015-02-11T02:25Z"},
            {"currentWeek('WED',21,60)", "currentWeek('WED',22,10)", "2015-02-11T22:00Z", "2015-02-11T22:10Z"},
            {"currentWeek('WED',24,60)", "currentWeek('THU',01,10)", "2015-02-12T01:00Z", "2015-02-12T01:10Z"},
            {"currentWeek('WED',04,-60)", "currentWeek('WED',04,10)", "2015-02-11T03:00Z", "2015-02-11T04:10Z"},
            {"currentWeek('SAT',-04,-60)", "currentWeek('SAT',-04,-40)", "2015-02-13T19:00Z", "2015-02-13T19:20Z"},
            {"currentWeek('SAT',-24,-60)", "currentWeek('SAT',-24,-40)", "2015-02-12T23:00Z", "2015-02-12T23:20Z"},
            {"lastWeek('THU',-24,-20)", "lastWeek('THU',-24,-05)", "2015-02-03T23:40Z", "2015-02-03T23:55Z"},
            {"lastWeek('WED',2,15)", "lastWeek('WED',2,25)", "2015-02-04T02:15Z", "2015-02-04T02:25Z"},
            {"lastWeek('WED',21,60)", "lastWeek('WED',22,10)", "2015-02-04T22:00Z", "2015-02-04T22:10Z"},
            {"lastWeek('WED',24,60)", "lastWeek('THU',01,10)", "2015-02-05T01:00Z", "2015-02-05T01:10Z"},
            {"lastWeek('WED',04,-60)", "lastWeek('WED',04,10)", "2015-02-04T03:00Z", "2015-02-04T04:10Z"},
            {"lastWeek('FRI',01,05)", "lastWeek('FRI',01,20)", "2015-02-06T01:05Z", "2015-02-06T01:20Z"},
            {"lastWeek('FRI',01,60)", "lastWeek('FRI',02,20)", "2015-02-06T02:00Z", "2015-02-06T02:20Z"},
            {"lastWeek('FRI',24,00)", "lastWeek('SAT',00,20)", "2015-02-07T00:00Z", "2015-02-07T00:20Z"},
            {"lastWeek('THU',-04,-20)", "lastWeek('THU',-04,-05)", "2015-02-04T19:40Z", "2015-02-04T19:55Z"},
        };
    }

    private boolean matchDependencies(List<String> fromJob, List<String> qaList) {
        Collections.sort(fromJob);
        Collections.sort(qaList);
        if (fromJob.size() != qaList.size()) {
            return false;
        }
        for (int index = 0; index < fromJob.size(); index++) {
            if (!fromJob.get(index).contains(qaList.get(index))) {
                return false;
            }
        }
        return true;
    }

    public List<String> getMissingDependencies(OozieClient oozieClient,
                                              String processName) throws OozieClientException {
        List<String> bundles = OozieUtil.getBundles(oozieClient, processName, EntityType.PROCESS);
        String coordID = bundles.get(0);
        List<String> missingDependencies = OozieUtil.getMissingDependencies(oozieClient, coordID);
        for (int i = 0; i < 10 && missingDependencies == null; ++i) {
            TimeUtil.sleepSeconds(30);
            missingDependencies = OozieUtil.getMissingDependencies(oozieClient, coordID);
        }
        Assert.assertNotNull(missingDependencies, "Missing dependencies not found.");
        return missingDependencies;
    }

    private List<String> getQADepedencyList(Bundle bundle, String firstDep, String endDep) {
        String path = baseTestDir + "/testData/";
        List<String> returnList = new ArrayList<>();
        List<String> dataSets = TimeUtil.getMinuteDatesOnEitherSide(firstDep,
                endDep, bundle.getInitialDatasetFrequency());
        for (String str : dataSets) {
            returnList.add(path + str);
        }
        return returnList;
    }

}


text:
<ion-view view-title="app.individualStatus" class="overflow-scroll">
  <ion-nav-title>Status: {{name}}

        Call

  </ion-nav-title>

  <ion-content class="moveDown">
    <ion-refresher
      pulling-text="Pull to refresh Carebank data ..."
      on-refresh="doRefresh()">
    </ion-refresher>

presence

meals

meds

12am

12pm

      <div ng-if="$index < 12 && $index != 0" class="col blackFont">{{ $index }}

 12" class="col blackFont">{{ $index - 12}}

      <div ng-if="$index <= currentHour" class="col" ng-class="data.presence.value[$index]">

 currentHour" class="col">

      <div ng-if="$index <= currentHour" class="col" ng-class="data.meals.value[$index]">{{data.meals.hits[$index]}}

 currentHour" class="col">

      <div ng-if="$index <= currentHour" class="col" ng-class="data.meds.value[$index]">{{data.meds.hits[$index]}}

 currentHour" class="col">

  </ion-content>
</ion-view>


text:
class StatDatum < ActiveRecord::Base
  validates_presence_of :user_id, :start_time, :value
end


text:
package com.loadburn.heron.webapp.web;

import com.google.common.collect.Lists;
import com.google.inject.Provider;
import com.loadburn.heron.storage.EntityStorage;
import com.loadburn.heron.storage.annotations.Transactional;
import com.loadburn.heron.storage.convertion.handler.BeanListHandler;
import com.loadburn.heron.storage.sql.Query;

import javax.inject.Inject;
import java.sql.SQLException;
import java.util.List;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-11-4
 */
public class HelloServiceImpl implements HelloService {

    private final Provider<EntityStorage> es;

    @Inject
    public HelloServiceImpl(Provider<EntityStorage> es) {
        this.es = es;
    }

    @Override
    @Transactional
    public List<Person> say() {
        List<Person> persons = null;
        try {
            persons = es.get().find(Person.class, new BeanListHandler<Person>(Person.class));
//            persons = sql.get().with(Person.class, "select_person").as(new BeanListHandler<Person>(Person.class)).params(null).list();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (persons != null && !persons.isEmpty()) {
            return persons;
        }
        return Lists.newArrayList();
    }

    @Transactional
    public void createTable() {
        try {
            Query query = es.get().createNamedQuery(Person.class, "create_person");
            if (!query.tableExists("person")) {
                query.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public void make() {
        Person person = new Person();
        person.setName("lin12");
        try {
            es.get().save(Person.class, person);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


text:
using Cofoundry.Core.ResourceFiles;

namespace Cofoundry.Domain.MailTemplates.Registration;

/// <summary>
/// Registers this assembly so that embedded resources (e.g. views/css/js) can be picked up.
/// </summary>
public class AssemblyResourceRegistration : IAssemblyResourceRegistration
{
}