text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="6nixkXIM5ylUCwywZVJagI6OO2HZDmb0BG_s5Bu2wVs" />
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="description" content="关于Android开发AND探索发现世界的美好">
    <meta name="keywords"  content="钟强,newstrong,钟小强,xiaoqiang">
    <meta name="theme-color" content="#000000">

    <meta property="og:title" content="404 - 钟小强的博客 | Newstrong Blog">

    <meta property="og:type" content="website">
    <meta property="og:description" content="你来到了没有知识的荒原 :(">

    <meta property="og:image" content="http://localhost:4000/img/InkedT1qxtaXopXXXXXXXXX_LI.jpg">
    <meta property="og:url" content="http://localhost:4000/404.html">
    <meta property="og:site_name" content="钟小强的博客 | Newstrong Blog">

    <title>404 - 钟小强的博客 | Newstrong Blog</title>

    <link rel="manifest" href="/pwa/manifest.json">

    <link rel="shortcut icon" href="/img/favicon.ico">

    <link rel="canonical" href="http://localhost:4000/404.html">

    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <link rel="stylesheet" href="/css/hux-blog.min.css">

    <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">

            <button type="button" class="navbar-toggle">
                Toggle navigation

            </button>
            Newstrong's blog

                        Home

                        About

                        Archive

                        ParseToMarkDown

                        程序员老黄历

404

          你来到了没有知识的荒原 :(

        知

                    Copyright © Newstrong's blog 2020

                    Powered by Hux Blog |


text:
package sun.security.ssl;

import java.net.Socket;

import java.io.*;
import java.util.*;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;

import javax.net.ssl.*;

import sun.security.provider.certpath.AlgorithmChecker;

public abstract class SSLContextImpl extends SSLContextSpi {

    private static final Debug debug = Debug.getInstance("ssl");

    private final EphemeralKeyManager ephemeralKeyManager;
    private final SSLSessionContextImpl clientCache;
    private final SSLSessionContextImpl serverCache;

    private boolean isInitialized;

    private X509ExtendedKeyManager keyManager;
    private X509TrustManager trustManager;
    private SecureRandom secureRandom;

    // The default algrithm constraints
    private AlgorithmConstraints defaultAlgorithmConstraints =
                                 new SSLAlgorithmConstraints(null);

    // supported and default protocols
    private ProtocolList defaultServerProtocolList;
    private ProtocolList defaultClientProtocolList;
    private ProtocolList supportedProtocolList;

    // supported and default cipher suites
    private CipherSuiteList defaultServerCipherSuiteList;
    private CipherSuiteList defaultClientCipherSuiteList;
    private CipherSuiteList supportedCipherSuiteList;

    SSLContextImpl() {
        ephemeralKeyManager = new EphemeralKeyManager();
        clientCache = new SSLSessionContextImpl();
        serverCache = new SSLSessionContextImpl();
    }

    protected void engineInit(KeyManager[] km, TrustManager[] tm,
                                SecureRandom sr) throws KeyManagementException {
        isInitialized = false;
        keyManager = chooseKeyManager(km);

        if (tm == null) {
            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                        TrustManagerFactory.getDefaultAlgorithm());
                tmf.init((KeyStore)null);
                tm = tmf.getTrustManagers();
            } catch (Exception e) {
                // eat
            }
        }
        trustManager = chooseTrustManager(tm);

        if (sr == null) {
            secureRandom = JsseJce.getSecureRandom();
        } else {
            if (SunJSSE.isFIPS() &&
                        (sr.getProvider() != SunJSSE.cryptoProvider)) {
                throw new KeyManagementException
                    ("FIPS mode: SecureRandom must be from provider "
                    + SunJSSE.cryptoProvider.getName());
            }
            secureRandom = sr;
        }

        /*
         * The initial delay of seeding the random number generator
         * could be long enough to cause the initial handshake on our
         * first connection to timeout and fail. Make sure it is
         * primed and ready by getting some initial output from it.
         */
        if (debug != null && Debug.isOn("sslctx")) {
            System.out.println("trigger seeding of SecureRandom");
        }
        secureRandom.nextInt();
        if (debug != null && Debug.isOn("sslctx")) {
            System.out.println("done seeding SecureRandom");
        }
        isInitialized = true;
    }

    private X509TrustManager chooseTrustManager(TrustManager[] tm)
            throws KeyManagementException {
        // We only use the first instance of X509TrustManager passed to us.
        for (int i = 0; tm != null && i < tm.length; i++) {
            if (tm[i] instanceof X509TrustManager) {
                if (SunJSSE.isFIPS() &&
                        !(tm[i] instanceof X509TrustManagerImpl)) {
                    throw new KeyManagementException
                        ("FIPS mode: only SunJSSE TrustManagers may be used");
                }

                if (tm[i] instanceof X509ExtendedTrustManager) {
                    return (X509TrustManager)tm[i];
                } else {
                    return new AbstractTrustManagerWrapper(
                                        (X509TrustManager)tm[i]);
                }
            }
        }

        // nothing found, return a dummy X509TrustManager.
        return DummyX509TrustManager.INSTANCE;
    }

    private X509ExtendedKeyManager chooseKeyManager(KeyManager[] kms)
            throws KeyManagementException {
        for (int i = 0; kms != null && i < kms.length; i++) {
            KeyManager km = kms[i];
            if (km instanceof X509KeyManager == false) {
                continue;
            }
            if (SunJSSE.isFIPS()) {
                // In FIPS mode, require that one of SunJSSE's own keymanagers
                // is used. Otherwise, we cannot be sure that only keys from
                // the FIPS token are used.
                if ((km instanceof X509KeyManagerImpl)
                            || (km instanceof SunX509KeyManagerImpl)) {
                    return (X509ExtendedKeyManager)km;
                } else {
                    // throw exception, we don't want to silently use the
                    // dummy keymanager without telling the user.
                    throw new KeyManagementException
                        ("FIPS mode: only SunJSSE KeyManagers may be used");
                }
            }
            if (km instanceof X509ExtendedKeyManager) {
                return (X509ExtendedKeyManager)km;
            }
            if (debug != null && Debug.isOn("sslctx")) {
                System.out.println(
                    "X509KeyManager passed to " +
                    "SSLContext.init():  need an " +
                    "X509ExtendedKeyManager for SSLEngine use");
            }
            return new AbstractKeyManagerWrapper((X509KeyManager)km);
        }

        // nothing found, return a dummy X509ExtendedKeyManager
        return DummyX509KeyManager.INSTANCE;
    }

    protected SSLSocketFactory engineGetSocketFactory() {
        if (!isInitialized) {
            throw new IllegalStateException(
                "SSLContextImpl is not initialized");
        }
       return new SSLSocketFactoryImpl(this);
    }

    protected SSLServerSocketFactory engineGetServerSocketFactory() {
        if (!isInitialized) {
            throw new IllegalStateException("SSLContext is not initialized");
        }
        return new SSLServerSocketFactoryImpl(this);
    }

    protected SSLEngine engineCreateSSLEngine() {
        if (!isInitialized) {
            throw new IllegalStateException(
                "SSLContextImpl is not initialized");
        }
        return new SSLEngineImpl(this);
    }

    protected SSLEngine engineCreateSSLEngine(String host, int port) {
        if (!isInitialized) {
            throw new IllegalStateException(
                "SSLContextImpl is not initialized");
        }
        return new SSLEngineImpl(this, host, port);
    }

    protected SSLSessionContext engineGetClientSessionContext() {
        return clientCache;
    }

    protected SSLSessionContext engineGetServerSessionContext() {
        return serverCache;
    }

    SecureRandom getSecureRandom() {
        return secureRandom;
    }

    X509ExtendedKeyManager getX509KeyManager() {
        return keyManager;
    }

    X509TrustManager getX509TrustManager() {
        return trustManager;
    }

    EphemeralKeyManager getEphemeralKeyManager() {
        return ephemeralKeyManager;
    }

    abstract SSLParameters getDefaultServerSSLParams();
    abstract SSLParameters getDefaultClientSSLParams();
    abstract SSLParameters getSupportedSSLParams();

    // Get suported ProtoclList.
    ProtocolList getSuportedProtocolList() {
        if (supportedProtocolList == null) {
            supportedProtocolList =
                new ProtocolList(getSupportedSSLParams().getProtocols());
        }

        return supportedProtocolList;
    }

    // Get default ProtoclList.
    ProtocolList getDefaultProtocolList(boolean roleIsServer) {
        if (roleIsServer) {
            if (defaultServerProtocolList == null) {
                defaultServerProtocolList = new ProtocolList(
                        getDefaultServerSSLParams().getProtocols());
            }

            return defaultServerProtocolList;
        } else {
            if (defaultClientProtocolList == null) {
                defaultClientProtocolList = new ProtocolList(
                        getDefaultClientSSLParams().getProtocols());
            }

            return defaultClientProtocolList;
        }
    }

    // Get suported CipherSuiteList.
    CipherSuiteList getSuportedCipherSuiteList() {
        // Clear cache of available ciphersuites.
        clearAvailableCache();

        if (supportedCipherSuiteList == null) {
            supportedCipherSuiteList =
                getApplicableCipherSuiteList(getSuportedProtocolList(), false);
        }

        return supportedCipherSuiteList;
    }

    // Get default CipherSuiteList.
    CipherSuiteList getDefaultCipherSuiteList(boolean roleIsServer) {
        // Clear cache of available ciphersuites.
        clearAvailableCache();

        if (roleIsServer) {
            if (defaultServerCipherSuiteList == null) {
                defaultServerCipherSuiteList = getApplicableCipherSuiteList(
                        getDefaultProtocolList(true), true);
            }

            return defaultServerCipherSuiteList;
        } else {
            if (defaultClientCipherSuiteList == null) {
                defaultClientCipherSuiteList = getApplicableCipherSuiteList(
                        getDefaultProtocolList(false), true);
            }

            return defaultClientCipherSuiteList;
        }
    }

    /**
     * Return whether a protocol list is the original default enabled
     * protocols.  See: SSLSocket/SSLEngine.setEnabledProtocols()
     */
    boolean isDefaultProtocolList(ProtocolList protocols) {
        return (protocols == defaultServerProtocolList) ||
               (protocols == defaultClientProtocolList);
    }

    /*
     * Return the list of all available CipherSuites with a priority of
     * minPriority or above.
     */
    private CipherSuiteList getApplicableCipherSuiteList(
            ProtocolList protocols, boolean onlyEnabled) {

        int minPriority = CipherSuite.SUPPORTED_SUITES_PRIORITY;
        if (onlyEnabled) {
            minPriority = CipherSuite.DEFAULT_SUITES_PRIORITY;
        }

        Collection<CipherSuite> allowedCipherSuites =
                                    CipherSuite.allowedCipherSuites();

        ArrayList<CipherSuite> suites = new ArrayList<>();
        if (!(protocols.collection().isEmpty()) &&
                protocols.min.v != ProtocolVersion.NONE.v) {
            for (CipherSuite suite : allowedCipherSuites) {
                if (suite.allowed == false || suite.priority < minPriority) {
                    continue;
                }

                if (suite.isAvailable() &&
                        suite.obsoleted > protocols.min.v &&
                        suite.supported <= protocols.max.v) {
                    if (defaultAlgorithmConstraints.permits(
                            EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
                            suite.name, null)) {
                        suites.add(suite);
                    }
                } else if (debug != null &&
                        Debug.isOn("sslctx") && Debug.isOn("verbose")) {
                    if (suite.obsoleted <= protocols.min.v) {
                        System.out.println(
                            "Ignoring obsoleted cipher suite: " + suite);
                    } else if (suite.supported > protocols.max.v) {
                        System.out.println(
                            "Ignoring unsupported cipher suite: " + suite);
                    } else {
                        System.out.println(
                            "Ignoring unavailable cipher suite: " + suite);
                    }
                }
            }
        }

        return new CipherSuiteList(suites);
    }

    /**
     * Clear cache of available ciphersuites. If we support all ciphers
     * internally, there is no need to clear the cache and calling this
     * method has no effect.
     */
    synchronized void clearAvailableCache() {
        if (CipherSuite.DYNAMIC_AVAILABILITY) {
            supportedCipherSuiteList = null;
            defaultServerCipherSuiteList = null;
            defaultClientCipherSuiteList = null;
            CipherSuite.BulkCipher.clearAvailableCache();
            JsseJce.clearEcAvailable();
        }
    }

    /*
     * The SSLContext implementation for TLS/SSL algorithm
     *
     * SSL/TLS protocols specify the forward compatibility and version
     * roll-back attack protections, however, a number of SSL/TLS server
     * vendors did not implement these aspects properly, and some current
     * SSL/TLS servers may refuse to talk to a TLS 1.1 or later client.
     *
     * Considering above interoperability issues, SunJSSE will not set
     * TLS 1.1 and TLS 1.2 as the enabled protocols for client by default.
     *
     * For SSL/TLS servers, there is no such interoperability issues as
     * SSL/TLS clients. In SunJSSE, TLS 1.1 or later version will be the
     * enabled protocols for server by default.
     *
     * We may change the behavior when popular TLS/SSL vendors support TLS
     * forward compatibility properly.
     *
     * SSLv2Hello is no longer necessary.  This interoperability option was
     * put in place in the late 90's when SSLv3/TLS1.0 were relatively new
     * and there were a fair number of SSLv2-only servers deployed.  Because
     * of the security issues in SSLv2, it is rarely (if ever) used, as
     * deployments should now be using SSLv3 and TLSv1.
     *
     * Considering the issues of SSLv2Hello, we should not enable SSLv2Hello
     * by default. Applications still can use it by enabling SSLv2Hello with
     * the series of setEnabledProtocols APIs.
     */

    /*
     * The conservative SSLContext implementation for TLS, SSL, SSLv3 and
     * TLS10 algorithm.
     *
     * This is a super class of DefaultSSLContext and TLS10Context.
     *
     * @see SSLContext
     */
    private static class ConservativeSSLContext extends SSLContextImpl {
        // parameters
        private static SSLParameters defaultServerSSLParams;
        private static SSLParameters defaultClientSSLParams;
        private static SSLParameters supportedSSLParams;

        static {
            if (SunJSSE.isFIPS()) {
                supportedSSLParams = new SSLParameters();
                supportedSSLParams.setProtocols(new String[] {
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });

                defaultServerSSLParams = supportedSSLParams;

                defaultClientSSLParams = new SSLParameters();
                defaultClientSSLParams.setProtocols(new String[] {
                    ProtocolVersion.TLS10.name
                });

            } else {
                supportedSSLParams = new SSLParameters();
                supportedSSLParams.setProtocols(new String[] {
                    ProtocolVersion.SSL20Hello.name,
                    ProtocolVersion.SSL30.name,
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });

                defaultServerSSLParams = supportedSSLParams;

                defaultClientSSLParams = new SSLParameters();
                defaultClientSSLParams.setProtocols(new String[] {
                    ProtocolVersion.SSL30.name,
                    ProtocolVersion.TLS10.name
                });
            }
        }

        SSLParameters getDefaultServerSSLParams() {
            return defaultServerSSLParams;
        }

        SSLParameters getDefaultClientSSLParams() {
            return defaultClientSSLParams;
        }

        SSLParameters getSupportedSSLParams() {
            return supportedSSLParams;
        }
    }

    /*
     * The SSLContext implementation for default algorithm
     *
     * @see SSLContext
     */
    public static final class DefaultSSLContext extends ConservativeSSLContext {
        private static final String NONE = "NONE";
        private static final String P11KEYSTORE = "PKCS11";

        private static volatile SSLContextImpl defaultImpl;

        private static TrustManager[] defaultTrustManagers;
        private static KeyManager[] defaultKeyManagers;

        public DefaultSSLContext() throws Exception {
            try {
                super.engineInit(getDefaultKeyManager(),
                        getDefaultTrustManager(), null);
            } catch (Exception e) {
                if (debug != null && Debug.isOn("defaultctx")) {
                    System.out.println("default context init failed: " + e);
                }
                throw e;
            }

            if (defaultImpl == null) {
                defaultImpl = this;
            }
        }

        protected void engineInit(KeyManager[] km, TrustManager[] tm,
            SecureRandom sr) throws KeyManagementException {
            throw new KeyManagementException
                ("Default SSLContext is initialized automatically");
        }

        static synchronized SSLContextImpl getDefaultImpl() throws Exception {
            if (defaultImpl == null) {
                new DefaultSSLContext();
            }
            return defaultImpl;
        }

        private static synchronized TrustManager[] getDefaultTrustManager()
                throws Exception {
            if (defaultTrustManagers != null) {
                return defaultTrustManagers;
            }

            KeyStore ks =
                TrustManagerFactoryImpl.getCacertsKeyStore("defaultctx");

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ks);
            defaultTrustManagers = tmf.getTrustManagers();
            return defaultTrustManagers;
        }

        private static synchronized KeyManager[] getDefaultKeyManager()
                throws Exception {
            if (defaultKeyManagers != null) {
                return defaultKeyManagers;
            }

            final Map<String,String> props = new HashMap<>();
            AccessController.doPrivileged(
                        new PrivilegedExceptionAction<Object>() {
                public Object run() throws Exception {
                    props.put("keyStore",  System.getProperty(
                                "javax.net.ssl.keyStore", ""));
                    props.put("keyStoreType", System.getProperty(
                                "javax.net.ssl.keyStoreType",
                                KeyStore.getDefaultType()));
                    props.put("keyStoreProvider", System.getProperty(
                                "javax.net.ssl.keyStoreProvider", ""));
                    props.put("keyStorePasswd", System.getProperty(
                                "javax.net.ssl.keyStorePassword", ""));
                    return null;
                }
            });

            final String defaultKeyStore = props.get("keyStore");
            String defaultKeyStoreType = props.get("keyStoreType");
            String defaultKeyStoreProvider = props.get("keyStoreProvider");
            if (debug != null && Debug.isOn("defaultctx")) {
                System.out.println("keyStore is : " + defaultKeyStore);
                System.out.println("keyStore type is : " +
                                        defaultKeyStoreType);
                System.out.println("keyStore provider is : " +
                                        defaultKeyStoreProvider);
            }

            if (P11KEYSTORE.equals(defaultKeyStoreType) &&
                    !NONE.equals(defaultKeyStore)) {
                throw new IllegalArgumentException("if keyStoreType is "
                    + P11KEYSTORE + ", then keyStore must be " + NONE);
            }

            FileInputStream fs = null;
            if (defaultKeyStore.length() != 0 && !NONE.equals(defaultKeyStore)) {
                fs = AccessController.doPrivileged(
                        new PrivilegedExceptionAction<FileInputStream>() {
                    public FileInputStream run() throws Exception {
                        return new FileInputStream(defaultKeyStore);
                    }
                });
            }

            String defaultKeyStorePassword = props.get("keyStorePasswd");
            char[] passwd = null;
            if (defaultKeyStorePassword.length() != 0) {
                passwd = defaultKeyStorePassword.toCharArray();
            }

            /**
             * Try to initialize key store.
             */
            KeyStore ks = null;
            if ((defaultKeyStoreType.length()) != 0) {
                if (debug != null && Debug.isOn("defaultctx")) {
                    System.out.println("init keystore");
                }
                if (defaultKeyStoreProvider.length() == 0) {
                    ks = KeyStore.getInstance(defaultKeyStoreType);
                } else {
                    ks = KeyStore.getInstance(defaultKeyStoreType,
                                        defaultKeyStoreProvider);
                }

                // if defaultKeyStore is NONE, fs will be null
                ks.load(fs, passwd);
            }
            if (fs != null) {
                fs.close();
                fs = null;
            }

            /*
             * Try to initialize key manager.
             */
            if (debug != null && Debug.isOn("defaultctx")) {
                System.out.println("init keymanager of type " +
                    KeyManagerFactory.getDefaultAlgorithm());
            }
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());

            if (P11KEYSTORE.equals(defaultKeyStoreType)) {
                kmf.init(ks, null); // do not pass key passwd if using token
            } else {
                kmf.init(ks, passwd);
            }

            defaultKeyManagers = kmf.getKeyManagers();
            return defaultKeyManagers;
        }
    }

    /*
     * The SSLContext implementation for TLS, SSL, SSLv3 and TLS10 algorithm
     *
     * @see SSLContext
     */
    public static final class TLS10Context extends ConservativeSSLContext {
        // use the default constructor and methods
    }

    /*
     * The SSLContext implementation for TLS11 algorithm
     *
     * @see SSLContext
     */
    public static final class TLS11Context extends SSLContextImpl {
        // parameters
        private static SSLParameters defaultServerSSLParams;
        private static SSLParameters defaultClientSSLParams;
        private static SSLParameters supportedSSLParams;

        static {
            if (SunJSSE.isFIPS()) {
                supportedSSLParams = new SSLParameters();
                supportedSSLParams.setProtocols(new String[] {
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });

                defaultServerSSLParams = supportedSSLParams;

                defaultClientSSLParams = new SSLParameters();
                defaultClientSSLParams.setProtocols(new String[] {
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name
                });

            } else {
                supportedSSLParams = new SSLParameters();
                supportedSSLParams.setProtocols(new String[] {
                    ProtocolVersion.SSL20Hello.name,
                    ProtocolVersion.SSL30.name,
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });

                defaultServerSSLParams = supportedSSLParams;

                defaultClientSSLParams = new SSLParameters();
                defaultClientSSLParams.setProtocols(new String[] {
                    ProtocolVersion.SSL30.name,
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name
                });
            }
        }

        SSLParameters getDefaultServerSSLParams() {
            return defaultServerSSLParams;
        }

        SSLParameters getDefaultClientSSLParams() {
            return defaultClientSSLParams;
        }

        SSLParameters getSupportedSSLParams() {
            return supportedSSLParams;
        }
    }

    /*
     * The SSLContext implementation for TLS12 algorithm
     *
     * @see SSLContext
     */
    public static final class TLS12Context extends SSLContextImpl {
        // parameters
        private static SSLParameters defaultServerSSLParams;
        private static SSLParameters defaultClientSSLParams;
        private static SSLParameters supportedSSLParams;

        static {
            if (SunJSSE.isFIPS()) {
                supportedSSLParams = new SSLParameters();
                supportedSSLParams.setProtocols(new String[] {
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });

                defaultServerSSLParams = supportedSSLParams;

                defaultClientSSLParams = new SSLParameters();
                defaultClientSSLParams.setProtocols(new String[] {
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });

            } else {
                supportedSSLParams = new SSLParameters();
                supportedSSLParams.setProtocols(new String[] {
                    ProtocolVersion.SSL20Hello.name,
                    ProtocolVersion.SSL30.name,
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });

                defaultServerSSLParams = supportedSSLParams;

                defaultClientSSLParams = new SSLParameters();
                defaultClientSSLParams.setProtocols(new String[] {
                    ProtocolVersion.SSL30.name,
                    ProtocolVersion.TLS10.name,
                    ProtocolVersion.TLS11.name,
                    ProtocolVersion.TLS12.name
                });
            }
        }

        SSLParameters getDefaultServerSSLParams() {
            return defaultServerSSLParams;
        }

        SSLParameters getDefaultClientSSLParams() {
            return defaultClientSSLParams;
        }

        SSLParameters getSupportedSSLParams() {
            return supportedSSLParams;
        }
    }

}

final class AbstractTrustManagerWrapper extends X509ExtendedTrustManager
            implements X509TrustManager {

    private final X509TrustManager tm;

    AbstractTrustManagerWrapper(X509TrustManager tm) {
        this.tm = tm;
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        tm.checkClientTrusted(chain, authType);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        tm.checkServerTrusted(chain, authType);
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return tm.getAcceptedIssuers();
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
                Socket socket) throws CertificateException {
        tm.checkClientTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, socket, true);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            Socket socket) throws CertificateException {
        tm.checkServerTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, socket, false);
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        tm.checkClientTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, engine, true);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        tm.checkServerTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, engine, false);
    }

    private void checkAdditionalTrust(X509Certificate[] chain, String authType,
                Socket socket, boolean isClient) throws CertificateException {
        if (socket != null && socket.isConnected() &&
                                    socket instanceof SSLSocket) {

            SSLSocket sslSocket = (SSLSocket)socket;
            SSLSession session = sslSocket.getHandshakeSession();
            if (session == null) {
                throw new CertificateException("No handshake session");
            }

            // check endpoint identity
            String identityAlg = sslSocket.getSSLParameters().
                                        getEndpointIdentificationAlgorithm();
            if (identityAlg != null && identityAlg.length() != 0) {
                String hostname = session.getPeerHost();
                X509TrustManagerImpl.checkIdentity(
                                    hostname, chain[0], identityAlg);
            }

            // try the best to check the algorithm constraints
            ProtocolVersion protocolVersion =
                ProtocolVersion.valueOf(session.getProtocol());
            AlgorithmConstraints constraints = null;
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                if (session instanceof ExtendedSSLSession) {
                    ExtendedSSLSession extSession =
                                    (ExtendedSSLSession)session;
                    String[] peerSupportedSignAlgs =
                            extSession.getLocalSupportedSignatureAlgorithms();

                    constraints = new SSLAlgorithmConstraints(
                                    sslSocket, peerSupportedSignAlgs, true);
                } else {
                    constraints =
                            new SSLAlgorithmConstraints(sslSocket, true);
                }
            } else {
                constraints = new SSLAlgorithmConstraints(sslSocket, true);
            }

            AlgorithmChecker checker = new AlgorithmChecker(constraints);
            try {
                checker.init(false);

                // a forward checker, need to check from trust to target
                for (int i = chain.length - 1; i >= 0; i--) {
                    Certificate cert = chain[i];
                    // We don't care about the unresolved critical extensions.
                    checker.check(cert, Collections.<String>emptySet());
                }
            } catch (CertPathValidatorException cpve) {
                throw new CertificateException(
                    "Certificates does not conform to algorithm constraints");
            }
        }
    }

    private void checkAdditionalTrust(X509Certificate[] chain, String authType,
            SSLEngine engine, boolean isClient) throws CertificateException {
        if (engine != null) {
            SSLSession session = engine.getHandshakeSession();
            if (session == null) {
                throw new CertificateException("No handshake session");
            }

            // check endpoint identity
            String identityAlg = engine.getSSLParameters().
                                        getEndpointIdentificationAlgorithm();
            if (identityAlg != null && identityAlg.length() != 0) {
                String hostname = session.getPeerHost();
                X509TrustManagerImpl.checkIdentity(
                                    hostname, chain[0], identityAlg);
            }

            // try the best to check the algorithm constraints
            ProtocolVersion protocolVersion =
                ProtocolVersion.valueOf(session.getProtocol());
            AlgorithmConstraints constraints = null;
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                if (session instanceof ExtendedSSLSession) {
                    ExtendedSSLSession extSession =
                                    (ExtendedSSLSession)session;
                    String[] peerSupportedSignAlgs =
                            extSession.getLocalSupportedSignatureAlgorithms();

                    constraints = new SSLAlgorithmConstraints(
                                    engine, peerSupportedSignAlgs, true);
                } else {
                    constraints =
                            new SSLAlgorithmConstraints(engine, true);
                }
            } else {
                constraints = new SSLAlgorithmConstraints(engine, true);
            }

            AlgorithmChecker checker = new AlgorithmChecker(constraints);
            try {
                checker.init(false);

                // A forward checker, need to check from trust to target
                for (int i = chain.length - 1; i >= 0; i--) {
                    Certificate cert = chain[i];
                    // We don't care about the unresolved critical extensions.
                    checker.check(cert, Collections.<String>emptySet());
                }
            } catch (CertPathValidatorException cpve) {
                throw new CertificateException(
                    "Certificates does not conform to algorithm constraints");
            }
        }
    }
}

// Dummy X509TrustManager implementation, rejects all peer certificates.
// Used if the application did not specify a proper X509TrustManager.
final class DummyX509TrustManager extends X509ExtendedTrustManager
            implements X509TrustManager {

    static final X509TrustManager INSTANCE = new DummyX509TrustManager();

    private DummyX509TrustManager() {
        // empty
    }

    /*
     * Given the partial or complete certificate chain
     * provided by the peer, build a certificate path
     * to a trusted root and return if it can be
     * validated and is trusted for client SSL authentication.
     * If not, it throws an exception.
     */
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation avaiable");
    }

    /*
     * Given the partial or complete certificate chain
     * provided by the peer, build a certificate path
     * to a trusted root and return if it can be
     * validated and is trusted for server SSL authentication.
     * If not, it throws an exception.
     */
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    /*
     * Return an array of issuer certificates which are trusted
     * for authenticating peers.
     */
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
                Socket socket) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            Socket socket) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }
}

/*
 * A wrapper class to turn a X509KeyManager into an X509ExtendedKeyManager
 */
final class AbstractKeyManagerWrapper extends X509ExtendedKeyManager {

    private final X509KeyManager km;

    AbstractKeyManagerWrapper(X509KeyManager km) {
        this.km = km;
    }

    public String[] getClientAliases(String keyType, Principal[] issuers) {
        return km.getClientAliases(keyType, issuers);
    }

    public String chooseClientAlias(String[] keyType, Principal[] issuers,
            Socket socket) {
        return km.chooseClientAlias(keyType, issuers, socket);
    }

    public String[] getServerAliases(String keyType, Principal[] issuers) {
        return km.getServerAliases(keyType, issuers);
    }

    public String chooseServerAlias(String keyType, Principal[] issuers,
            Socket socket) {
        return km.chooseServerAlias(keyType, issuers, socket);
    }

    public X509Certificate[] getCertificateChain(String alias) {
        return km.getCertificateChain(alias);
    }

    public PrivateKey getPrivateKey(String alias) {
        return km.getPrivateKey(alias);
    }

    // Inherit chooseEngineClientAlias() and chooseEngineServerAlias() from
    // X509ExtendedKeymanager. It defines them to return null;
}

// Dummy X509KeyManager implementation, never returns any certificates/keys.
// Used if the application did not specify a proper X509TrustManager.
final class DummyX509KeyManager extends X509ExtendedKeyManager {

    static final X509ExtendedKeyManager INSTANCE = new DummyX509KeyManager();

    private DummyX509KeyManager() {
        // empty
    }

    /*
     * Get the matching aliases for authenticating the client side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    public String[] getClientAliases(String keyType, Principal[] issuers) {
        return null;
    }

    /*
     * Choose an alias to authenticate the client side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    public String chooseClientAlias(String[] keyTypes, Principal[] issuers,
            Socket socket) {
        return null;
    }

    /*
     * Choose an alias to authenticate the client side of an
     * engine given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    public String chooseEngineClientAlias(
            String[] keyTypes, Principal[] issuers, SSLEngine engine) {
        return null;
    }

    /*
     * Get the matching aliases for authenticating the server side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    public String[] getServerAliases(String keyType, Principal[] issuers) {
        return null;
    }

    /*
     * Choose an alias to authenticate the server side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    public String chooseServerAlias(String keyType, Principal[] issuers,
            Socket socket) {
        return null;
    }

    /*
     * Choose an alias to authenticate the server side of an engine
     * given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    public String chooseEngineServerAlias(
            String keyType, Principal[] issuers, SSLEngine engine) {
        return null;
    }

    /**
     * Returns the certificate chain associated with the given alias.
     *
     * @param alias the alias name
     *
     * @return the certificate chain (ordered with the user's certificate first
     * and the root certificate authority last)
     */
    public X509Certificate[] getCertificateChain(String alias) {
        return null;
    }

    /*
     * Returns the key associated with the given alias, using the given
     * password to recover it.
     *
     * @param alias the alias name
     *
     * @return the requested key
     */
    public PrivateKey getPrivateKey(String alias) {
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 *  Document and Window states
 */

$(document).ready(function(){

	wrapVideo();
  checkboxInit();

  $( 'select' ).each(function( index ) {
    recolorSelect( $(this) );
  });

}); // End of $(document).ready()

// Resize or orientationchange of window
$(window).bind('ready load resize orientationchange', function(){
  $('.modal:visible').each(centerModal);
  recalculateSidebar();
});

// Whenever an Ajax request completes, jQuery triggers the ajaxComplete event
$(document).ajaxComplete(function() {
  $('.hastooltip').tooltip();
  checkboxInit();
});

/**
 *  Functions
 */

function recalculateSidebar(){
  var alltheway = $('.dashboard-menu.alltheway');
  $(alltheway).removeAttr("style");
  var windowHeight = $(document).height();
  var headerHeight = $('header[role=banner]').outerHeight();
  var allthewayHeight = windowHeight - headerHeight;
  var dashboardContentHeight = $('.dashboard-content').height();
  if ( $(window).width() >= 992 ) {
    if ( dashboardContentHeight >= allthewayHeight ) {
      $(alltheway).css('min-height', dashboardContentHeight);
    } else {
      $(alltheway).css('min-height', allthewayHeight);
    }
  } else {
    $(alltheway).css('min-height', '1px');
  }
}

function centerModal() {
    $(this).css('display', 'block');
    var $dialog = $(this).find(".modal-dialog");
    var offset = ($(window).height() - $dialog.height()) / 2;
    // Center modal vertically in window with fix for modals with height greater than window, native behavior (with scroll) occurs
    if (offset > 30) {
        $dialog.css("margin-top", offset);
    } else {
        setTimeout(function(){
            $dialog.parents('.modal').css('padding-left', '16px');
            $dialog.css("margin-top", 30);
        }, 500);
    }
}

function wrapVideo() {
  $('iframe').each(function() {
    var pad = Math.floor($(this).height()/$(this).width()*100) + '%';
    $(this).wrap("
");
    // Variant 1 is with padding-bottom given through css (always the same), and variant 2 is using dynamic value from this function
    //$(this).parent('.video-wrapper').css('padding-bottom', pad);

    //add wmode, so videos position below floating elements
    var url = $(this).attr("src")
    // just adding new attr wmode should be sufficient... altering url is a for nay case
    $(this).attr('src',url+'?wmode=opaque').attr('wmode', 'opaque');
  });
}

// When coming from article, we need to make table responsive
function wrapTable() {
  $('.table-rework table').each(function() {
    $(this).wrap("
");
  });
}

function checkboxCalculate($drop) {
  sel = $drop.find('select');
  opt = $drop.find('select > option');
  len = $drop.find('.chck:checked').length;
  if ( len > 0 ) {
    opt.html(len + ' selected');
    sel.removeClass('color-placeholder');
  } else {
    opt.html(sel.data('wording'));
    sel.addClass('color-placeholder');
  }
}

function checkboxInit(){
  $('.dropdown.keep-open').each(function() {
    checkboxCalculate($(this));
  });
}

// Color-placeholder and select elements
function recolorSelect( $this ) {
  var val = $this.val();
  $('#result').append('
value=' + val + '
');
  if ( val != '' ) {
    $this.removeClass('color-placeholder');
  } else {
    $this.addClass('color-placeholder');
  }
}

/**
 *  Custom actions
 */

 // Global toggle
$(document).on('click', '.js-toggler', function(e){
  e.preventDefault();
  $(this).toggleClass('on');
  $(this).parent().find('.toggled').slideToggle();
});

// Dropdown Keep-open toggle
// Close dropdown menu open after click outside
$(document).on('click', function (e) {
  var toggler = $('.dropdown-toggler');
  var toggled = $('.dropdown-toggled');
  if ( toggler.is(e.target) ) {
    toggled.toggleClass('hidden');
  } else if (!toggled.is(e.target) && toggled.has(e.target).length === 0) { // if the target of the click isn't the toggled, nor a descendant of the toggled
    toggled.addClass('hidden');
  }
});

// Count checked checkoxes and present the number
$(document).on('change', 'input[type=checkbox]',function(){
  drop = $(this).parents('.dropdown');
  checkboxCalculate(drop);
});

// Resize left sidebar after textarea for article content was manually resized
$(document).on('mouseleave', '.mce-resizehandle', function() {
  recalculateSidebar();
});
$(document).on('mouseenter', '.mce-container', function() {
  recalculateSidebar();
});

$(document).on('change', 'select', function() {
  recolorSelect( $(this) );
});

// placeholder for IE
if( $().placeholder ) {
  $('input, textarea').placeholder();
}

// tooltip (bootstrap)
$('.hastooltip').tooltip();

// Modal
$('.modal').on('show.bs.modal', centerModal);

// Dashboard Navigation toggle
$('.toggle--dashboard-menu').on('click',function(e){
  e.preventDefault();
  $(this).toggleClass('on');
  $('.dashboard-menu nav').slideToggle();
});


text:
<?php
namespace Models;

use Core\Model;

class Monsters extends Model
{
	public function __construct()
	{
		parent::__construct();
	}

	private static $monsters = array(
		array('key' => 1, 'title' => 'Butcher'),
		array('key' => 2, 'title' => 'King\'s Man'),
		array('key' => 3, 'title' => 'The Hand'),
		array('key' => 4, 'title' => 'White Lion'),
		array('key' => 5, 'title' => 'Screaming Antelope'),
		array('key' => 6, 'title' => 'Phoenix')
	);

	public static function getMonster($monsterKey)
	{
		foreach(Monsters::$monsters as $monster)
		{
			if($monsterKey == $monster['key'])
			{
				return $monster;
			}
		}
		return null;
	}
}


text:
$(document).ready(function () {
    // Placeholder for search form
    var search = document.getElementById('search-top');
    if (search && search.elements.length) {
        var input = search.elements.q;
        if (input != undefined) {
            var hint = input.getAttribute('data-hint');

            input.onfocus = function(e) {
                if (this.value == hint) {
                    this.value = '';
                }
            };

            input.onblur = function(e) {
                if (this.value == '') {
                    this.value = hint;
                }
            };
        }
    }

    // Placeholder for promo page
    var question = document.getElementById('question-promo');
    if (question && question.elements.length) {
        var textArea = question.elements.q;
        if (textArea != undefined) {
            var hintArea = textArea.getAttribute('data-hint');

            textArea.onfocus = function(e) {
                if (this.value == hintArea) {
                    this.value = '';
                }
            };

            textArea.onblur = function(e) {
                if (this.value == '') {
                    this.value = hintArea;
                }
            };
        }
    }
});


text:
<?php

declare(strict_types=1);

namespace KKirsz\Photos\Test;

use KKirsz\Photos\Module;
use PHPUnit\Framework\TestCase;

/**
 * @author Korneliusz Kirsz <kornel.kirsz@gmail.com>
 */
class ModuleTest extends TestCase
{
    /**
     *
     * @var Module
     */
    private $module;

    /**
     *
     */
    protected function setUp()
    {
        $this->module = new Module();
    }

    /**
     *
     */
    public function testConfigIsReturned()
    {
        $config = $this->module->getConfig();
        $this->assertInternalType('array', $config);
        $this->assertArrayHasKey('doctrine', $config);
    }
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;

namespace DieFledermaus.Tests
{
    internal static class Program
    {
        const int bigBufferLength = 70000;
        [STAThread]
        static void Main()
        {
            byte[] bigBuffer = new byte[bigBufferLength];
            for (int i = 0; i < bigBufferLength; i++)
                bigBuffer[i] = (byte)(i + 1);

            using (MemoryStream ms = new MemoryStream())
            {
                RsaKeyParameters publicKeySig, privateKeySig, publicKeyEnc, privateKeyEnc;
                {
                    var keyPair = GetKeyPair(Keys.Signature);
                    publicKeySig = (RsaKeyParameters)keyPair.Public;
                    privateKeySig = (RsaKeyParameters)keyPair.Private;
                }
                {
                    var keyPair = GetKeyPair(Keys.Encryption);
                    publicKeyEnc = (RsaKeyParameters)keyPair.Public;
                    privateKeyEnc = (RsaKeyParameters)keyPair.Private;
                }
                ECKeyParameters publicKeyECDSA, privateKeyECDSA;
                {
                    var keyPair = GetKeyPair(Keys.ECDSA);
                    publicKeyECDSA = (ECKeyParameters)keyPair.Public;
                    privateKeyECDSA = (ECKeyParameters)keyPair.Private;
                }

                Console.WriteLine("Creating archive ...");
                Stopwatch sw;
                using (DieFledermauZArchive archive = new DieFledermauZArchive(ms, MauZArchiveMode.Create, true))
                {
                    archive.RSASignParameters = archive.DefaultRSASignParameters = privateKeySig;
                    archive.RSASignId = archive.DefaultRSASignId = "RSA";
                    archive.ECDSASignParameters = archive.DefaultECDSASignParameters = privateKeyECDSA;
                    archive.ECDSASignId = archive.DefaultECDSASignId = "ECDSA";
                    SetEntry(archive, bigBuffer, MausCompressionFormat.Deflate, MausEncryptionFormat.None, publicKeyEnc);
                    SetEntry(archive, bigBuffer, MausCompressionFormat.Lzma, MausEncryptionFormat.Aes, publicKeyEnc);
                    SetEntry(archive, bigBuffer, MausCompressionFormat.None, MausEncryptionFormat.Threefish, publicKeyEnc);
                    Console.WriteLine(" - Building empty directory: EmptyDir/");
                    var emptyDir = archive.AddEmptyDirectory("EmptyDir/", MausEncryptionFormat.Twofish);
                    SetPasswd(emptyDir);
                    Console.WriteLine("Compressing archive ...");
                    sw = Stopwatch.StartNew();
                }

                sw.Stop();
                Console.WriteLine("Completed compression in {0}ms", sw.Elapsed.TotalMilliseconds);
                Console.WriteLine();
                Console.WriteLine("Decoding archive ...");

                using (DieFledermauZArchive archive = new DieFledermauZArchive(ms, MauZArchiveMode.Read, true))
                {
                    archive.RSASignParameters = publicKeySig;
                    if (archive.VerifyRSASignature())
                        Console.WriteLine("RSA signature verified for the archive.");
                    else
                        Console.WriteLine("RSA signature NOT verified for the archive!");
                    archive.ECDSASignParameters = publicKeyECDSA;
                    if (archive.VerifyECDSASignature())
                        Console.WriteLine("ECDSA signature verified for the archive.");
                    else
                        Console.WriteLine("ECDSA signature NOT verified for the archive!");

                    Console.WriteLine("Completed reading and signature-verification in {0}ms", sw.Elapsed.TotalMilliseconds);

                    foreach (DieFledermauZItem item in archive.Entries.ToArray().Where(i => i.EncryptionFormat != MausEncryptionFormat.None))
                    {
                        Console.WriteLine(" - Decrypting archive entry ...");
                        if (item.IsRSAEncrypted)
                            item.RSAEncryptParameters = privateKeyEnc;
                        else
                            SetPasswd(item);

                        sw = Stopwatch.StartNew();
                        var dItem = item.Decrypt();
                        sw.Stop();
                        Console.WriteLine("Successfully decrypted {0} in {1}ms", dItem.Path, sw.Elapsed.TotalMilliseconds);
                    }

                    foreach (DieFledermauZArchiveEntry entry in archive.Entries.OfType<DieFledermauZArchiveEntry>())
                    {
                        entry.RSASignParameters = publicKeySig;
                        entry.ECDSASignParameters = publicKeyECDSA;

                        Console.WriteLine(" - Reading file: " + entry.Path);
                        Console.WriteLine("Hash: " + GetString(entry.ComputeHash()));
                        if (entry.VerifyRSASignature())
                            Console.WriteLine("RSA signature is verified.");
                        else
                            Console.WriteLine("RSA signature is NOT verified!");
                        if (entry.VerifyECDSASignature())
                            Console.WriteLine("ECDSA signature is verified.");
                        else
                            Console.WriteLine("ECDSA signature is NOT verified!");
                    }
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press any key to continue ...");
            Console.ReadKey();
        }

        private static AsymmetricCipherKeyPair GetKeyPair(string pem)
        {
            using (StringReader sr = new StringReader(pem))
            {
                PemReader reader = new PemReader(sr);
                return (AsymmetricCipherKeyPair)reader.ReadObject();
            }
        }

        private static void SetEntry(DieFledermauZArchive archive, byte[] bigBuffer, MausCompressionFormat compFormat, MausEncryptionFormat encFormat,
            RsaKeyParameters encKey)
        {
            var entry = archive.Create("Files/" + compFormat.ToString() + encFormat.ToString() + ".dat", compFormat, encFormat);

            Console.WriteLine(" - Building file: " + entry.Path);

            if (encFormat != MausEncryptionFormat.None)
                entry.RSAEncryptParameters = encKey;

            using (Stream stream = entry.OpenWrite())
                stream.Write(bigBuffer, 0, bigBufferLength);

            Console.WriteLine("Hash: " + GetString(entry.ComputeHash()));
        }

        private static void SetPasswd(DieFledermauZItem item)
        {
            const string passwd = "Correct Horse!Battery#Staple69105";

            item.Password = passwd;
            Stopwatch sw = Stopwatch.StartNew();
            item.DeriveKey();
            sw.Stop();
            Console.WriteLine("Time to derive key: {0}ms", sw.Elapsed.TotalMilliseconds);
        }

        private static string GetString(byte[] hash)
        {
            return string.Concat(hash.Select(i => i.ToString("x2", System.Globalization.NumberFormatInfo.InvariantInfo)).ToArray());
        }
    }
}


text:
/* eslint-disable import/prefer-default-export */

import type { ReactChildren, ClassNameMap, Callback, Handler } from '../../types';

export const INPUT_CLASSES = {
  input: 'input',
  input__large: 'input--large',
  input__small: 'input--small',
  input__checked: 'is-checked',
  input__disabled: 'is-disabled',
  input__invalid: 'is-invalid',
  input__multiple: 'is-multiple',
  input__readOnly: 'is-read-only',
  input__required: 'is-required',
};

export type InputValue = string | string[];

export type SelectOption = {
  disabled: boolean,
  label: string,
  value: string,
  options?: SelectOption[],
};

export type ChangedData = {
  name: string,
  value: InputValue,
  checked?: boolean,
};

export type RenderedProps = {
  checked?: boolean,
  className?: string,
  disabled: boolean,
  id: string,
  multiple?: boolean,
  name: string,
  onChange: Handler,
  readOnly: boolean,
  required: boolean,
  type?: string,
  value: InputValue,
};

export type InputProps = {
  children: ReactChildren,
  classNames: ClassNameMap,
  defaultChecked: string | boolean,
  defaultValue: InputValue,
  disabled: boolean,
  id: string,
  invalid: boolean,
  large: boolean,
  multiple: boolean,
  name: string,
  native: boolean,
  onChanged: Callback,
  onChanging: Callback,
  readOnly: boolean,
  required: boolean,
  small: boolean,
  type: string,
};

export type InputState = {
  checked: boolean,
  value: InputValue,
};

export type InputChoiceProps = {
  children: ReactChildren,
  classNames: ClassNameMap,
  inputID: string,
  large: boolean,
  small: boolean,
};

export type InputStaticProps = {
  children: ReactChildren,
  classNames: ClassNameMap,
  large: boolean,
  small: boolean,
};

export type InputSelectProps = {
  options: SelectOption[],
};


text:
namespace QI4N.Framework.Runtime
{
    using System;
    using System.Collections.Generic;

    using Bootstrap;

    public sealed class ServiceModel : AbstractCompositeModel
    {
        private readonly string identity;

        private readonly bool instantiateOnStartup;

        private readonly string moduleName;

        private ServiceModel(Type compositeType, Visibility visibility, MetaInfo metaInfo, AbstractMixinsModel mixinsModel, AbstractStateModel stateModel, CompositeMethodsModel compositeMethodsModel, string moduleName, string identity, bool instantiateOnStartup)
                : base(compositeType, visibility, metaInfo, mixinsModel, stateModel, compositeMethodsModel)
        {
            this.moduleName = moduleName;
            this.identity = identity;
            this.instantiateOnStartup = instantiateOnStartup;
        }

        public string Identity
        {
            get
            {
                return this.identity;
            }
        }

        public bool InstantiateOnStartup
        {
            get
            {
                return this.instantiateOnStartup;
            }
        }

        public string ModuleName
        {
            get
            {
                return this.moduleName;
            }
        }

        public static ServiceModel NewModel(Type compositeType,
                                            Visibility visibility,
                                            MetaInfo metaInfo,
                                            IEnumerable<Type> assemblyConcerns,
                                            IEnumerable<Type> sideEffects,
                                            IList<Type> mixins,
                                            String moduleName,
                                            String identity,
                                            bool instantiateOnStartup)
        {
            PropertyDeclarations propertyDeclarations = new MetaInfoDeclaration();
            var constraintsModel = new ConstraintsModel(compositeType);
            bool immutable = metaInfo.Get<ImmutableAttribute>() != null;
            var propertiesModel = new ServicePropertiesModel(constraintsModel, propertyDeclarations, immutable);
            var stateModel = new ServiceStateModel(propertiesModel);
            var mixinsModel = new MixinsModel(compositeType, mixins);

            var concerns = new List<ConcernDeclaration>();
            ConcernsDeclaration.ConcernDeclarations(assemblyConcerns, concerns);
            ConcernsDeclaration.ConcernDeclarations(compositeType, concerns);
            var concernsModel = new ConcernsDeclaration(concerns);
            var sideEffectsModel = new SideEffectsDeclaration(compositeType, sideEffects);
            var compositeMethodsModel = new CompositeMethodsModel(compositeType, constraintsModel, concernsModel, sideEffectsModel, mixinsModel);
            stateModel.AddStateFor(compositeMethodsModel.Properties, compositeType);

            return new ServiceModel(
                    compositeType, visibility, metaInfo, mixinsModel, stateModel, compositeMethodsModel, moduleName, identity, instantiateOnStartup);
        }

        public bool IsServiceFor(Type serviceType, Visibility visibility)
        {
            // Check visibility
            if (visibility != this.Visibility)
            {
                return false;
            }

            // Plain class check

            return serviceType.IsAssignableFrom(this.compositeType);
        }

        //[DebuggerStepThrough]
        ////[DebuggerHidden]
        public ServiceInstance NewInstance(ModuleInstance module)
        {
            object[] mixins = this.mixinsModel.NewMixinHolder();
            var serviceInstance = new ServiceInstance(this, module, mixins);

            var uses = new UsesInstance();
            uses.Use(this);

            // Instantiate all mixins
            ((MixinsModel)this.mixinsModel).NewMixins(serviceInstance,
                                                      uses,
                                                      null,
                                                      mixins);

            return serviceInstance;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:property-placeholder location="classpath:serviceconfig/olat.properties, classpath:olat.local.properties" />

	<!-- OLAT specific popup windows default layout, which is also applied to
	popupwindows opened within core controllers, e.g. html editor or thelike -->
	<bean id="popupBrowserWindowControllerCreator"
		class="org.olat.presentation.framework.layout.fullWebApp.popup.BaseFullWebappPopupLayoutCreator" >
	</bean>
	<!-- the specifed creator is responsible for the frameworks popup browser window layout.
	     Special layouts must be implemented by wrapping the content into a content-layouting controller
	     TODO:pb: discuss a layoutconfig.xml?-->
<!--	<bean id="popupBrowserWindowControllerCreator" -->
<!--		class="org.olat.presentation.framework.core.control.generic.popup.BasePopupWindowControllerCreator" >-->
<!--	</bean> -->

	<!-- An alternate popup controller when the base full web app controller is used
	<bean id="popupBrowserWindowControllerCreator"
		class="org.olat.presentation.framework.layout.fullWebApp.popup.BaseFullWebappPopupLayoutCreator" >
	</bean>
	 -->

	<!--
		******************************************
		*** Configure the controller in the    ***
		*** header part, e.g. for a logo       ***
		******************************************
	-->
	<bean id="fullWebApp.HeaderControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator" >
		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.EmptyHeaderController"/>
	</bean>
	<!-- use the following header controller instead if you want a logo header header or configure you own
	<bean id="fullWebApp.HeaderControllerCreator" class="org.olat.presentation.framework.layout.fullWebApp.LogoWithLinkHeaderControllerCreator" scope="prototype">
		<property name="linkURI" value="http://www.brasatoframework.org" />
		<property name="imgURI" value="http://www.brasatoframework.org/images/logo.png" />
		<property name="imgAltText" value="Brasato Open Source WebApp Framework" />
	</bean>
	-->
	<!-- in case a Guest uses OLAT, see GuestBFWCParts -->
	<!-- <bean id="fullWebApp.GuestHeaderControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator" scope="prototype">
		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.EmptyHeaderController"/>
	</bean> -->
	<!-- Header for DMZ, see DmzBFWCParts -->
    <!-- <bean  id="fullWebApp.DMZHeaderControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.EmptyHeaderController"/>
	</bean> -->

	<!--
		******************************************
		*** Configure the controller in the    ***
		*** right upper corner.                ***
		******************************************
	-->
	<bean id="fullWebApp.DMZTopNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatDmzTopNavController"/>
	</bean>
	<bean id="fullWebApp.TopNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatTopNavController"/>
	</bean>
	<!-- uncomment this and comment above line if automatic guest login should be enabled
	<bean id="fullWebApp.TopNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatGuestTopNavController"/>
	</bean>
	 -->
<!--	<bean id="fullWebApp.TopNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator" >-->
<!--		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.DefaultTopNavController"/>-->
<!--	</bean>-->

	<!--
		******************************************
		*** Configure the controller in the    ***
		*** right upper corner in pop ups      ***
		******************************************
	-->
	<bean id="fullWebApp.MinimalTopNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatMinimalTopNavController"/>
	</bean>
<!--	<bean id="fullWebApp.MinimalTopNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">-->
<!--		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.DefaultMinimalTopNavController" />-->
<!--	</bean>-->

	<!--
		******************************************
		*** Configure the controller in the    ***
		*** Footer.                            ***
		******************************************
	-->
	<bean  id="fullWebApp.FooterControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatFooterController"/>
	</bean>

	<bean id="fullWebApp.ContextHelpFooterControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator" >
		<property name="className" value="org.olat.presentation.framework.layout.OlatFooterController"/>
	</bean>

    <!-- uncomment this and comment above line if automatic guest login should be enabled:
	<bean  id="fullWebApp.FooterControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatGuestFooterController"/>
	</bean>
    -->
	<!-- in case a Guest uses OLAT, see GuestBFWCParts -->
    <bean  id="fullWebApp.GuestFooterControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatGuestFooterController"/>
	</bean>
	<!-- Footer for DMZ, see DmzBFWCParts -->
    <bean  id="fullWebApp.DMZFooterControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.layout.OlatGuestFooterController"/>
	</bean>
	<!--
	<bean id="fullWebApp.MinimalFooterControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator" >
		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.DefaultFooterController"/>
	</bean>
	 -->

	<!--
		******************************************
		*** Configure the controller in the    ***
		*** header part, in context help       ***
		******************************************
	-->
	<bean id="fullWebApp.ContextHelpHeaderControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator" >
		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.EmptyHeaderController"/>
	</bean>
	<!--	<bean id="fullWebApp.ContextHelpHeaderControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">-->
	<!--		<property name="className" value="org.olat.presentation.framework.layout.fullWebApp.EmptyHeaderController"/>-->
	<!--	</bean> 		-->
	<!--
		******************************************
		*** Configure the controller in the    ***
		*** right upper corner in context help**
		******************************************
	-->
	<bean id="fullWebApp.ContextHelpTopNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">
		<property name="className" value="org.olat.presentation.framework.common.contextHelp.ContextHelpTopNavController" />
	</bean>

<!--	<bean id="fullWebApp.ContextHelpNavControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator">-->
<!--		<property name="className" value="org.olat.presentation.framework.common.contextHelp.ContextHelpMinimalTopNavController" />-->
<!--	</bean>-->

	<!--
		**************************************************************************
		*** Configure the controller-workflow which should be presented		   ***
		*** right after a user logged in.                                      ***
		*** See comment in AfterLoginInterceptorController                     ***
		**************************************************************************
	-->
	<bean id="fullWebApp.AfterLoginInterceptionControllerCreator" class="org.olat.presentation.framework.core.control.creator.AutoCreator" >
		<property name="className" value="org.olat.presentation.security.authentication.AfterLoginInterceptionController"/>
	</bean>

<!--
	Optional configuration of the column default width given in EM values.
	Set your custom values if the default values do not fit your layout theme
<bean id="org.olat.presentation.framework.layout.fullWebApp.LayoutMain3ColsConfig" class="org.olat.presentation.framework.layout.fullWebApp.LayoutMain3ColsConfig">
	<property name="col1WidthEmDefault" value="14" />
	<property name="col2WidthEmDefault" value="12" />
</bean>
-->

<bean id="org.olat.presentation.framework.core.dev.IDE" class="org.olat.presentation.framework.core.dev.impl.EclipseIDE"/>

</beans>


text:
package com.thoughtworks.go.util;

import com.thoughtworks.go.util.command.CommandLineException;
import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ProcessManager {

    private static final Logger LOG = LoggerFactory.getLogger(ProcessManager.class);
    private static final ProcessManager processManager = new ProcessManager();

    private ConcurrentMap<Process, ProcessWrapper> processMap = new ConcurrentHashMap<>();

    ProcessManager() {
    }

    public static ProcessManager getInstance() {
        return processManager;
    }

    public ProcessWrapper createProcess(String[] commandLine, String commandLineForDisplay, File workingDir, Map<String, String> envMap, EnvironmentVariableContext environmentVariableContext,
                                        ConsoleOutputStreamConsumer consumer, ProcessTag processTag, String encoding, String errorPrefix) {
        ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
        LOG.debug("Executing: {}", commandLineForDisplay);
        if (workingDir != null) {
            LOG.debug("[Command Line] Using working directory {} to start the process.", workingDir.getAbsolutePath());
            processBuilder.directory(workingDir);
        }

        processBuilder.environment().putAll(environmentVariableContext.getProperties());
        processBuilder.environment().putAll(envMap);

        Process process = startProcess(processBuilder, commandLineForDisplay);
        ProcessWrapper processWrapper = new ProcessWrapper(process, processTag, commandLineForDisplay, consumer, encoding, errorPrefix);
        processMap.putIfAbsent(process, processWrapper);
        return processWrapper;
    }

    public void processKilled(Process process) {
        if (process != null && processMap.containsKey(process)) {
            processMap.remove(process);
        }
    }

    public long getIdleTimeFor(ProcessTag processTag) {
        for (ProcessWrapper processWrapper : processMap.values()) {
            ProcessTag tag = processWrapper.getProcessTag();
            if (processTag.equals(tag)) {
                return processWrapper.getIdleTime();
            }
        }
        return 0;
    }

    public Collection<ProcessWrapper> currentProcessListForDisplay() {
        return processMap.values();
    }

    public Set<String> environmentVariableNames() {
        return System.getenv().keySet();
    }

    //should be used only for tests
    ConcurrentMap<Process, ProcessWrapper> getProcessMap() {
        return processMap;
    }

    Process startProcess(ProcessBuilder processBuilder, String commandLineForDisplay) {
        Process process;
        try {
            LOG.debug("[Command Line] START command {}", commandLineForDisplay);
            process = processBuilder.start();
            LOG.debug("[Command Line] END command {}", commandLineForDisplay);
        } catch (IOException e) {
            LOG.error("[Command Line] Failed executing [{}]", commandLineForDisplay);
            LOG.error("[Command Line] Agent's Environment Variables: {}", System.getenv());
            throw new CommandLineException(String.format("Error while executing [%s] \n Make sure this command can execute manually.", commandLineForDisplay), e);
        }
        return process;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusidium potentillae Thüm.

### Remarks
null


text:
namespace onnxruntime {
namespace contrib {
namespace snpe {

size_t CalcSizeFromDims(const zdl::DlSystem::Dimension* dims, size_t rank, size_t elementSize) {
  if (rank == 0) return 0;
  SafeInt<size_t> size = elementSize;
  while (rank--) {
    size = size * (*dims);
    dims++;
  }
  return size;
}

Status SnpeLib::SetupUserBufferAttribute(const std::string& name) {
  auto buffer_attributes = snpe_->getInputOutputBufferAttributes(name.c_str());
  ORT_ENFORCE(buffer_attributes, "Error obtaining attributes for input/output tensor: ", name);
  zdl::DlSystem::UserBufferEncoding* user_buffer_encoding = nullptr;
  size_t buffer_element_size = 0;
  if (BufferType::TF8 == buffer_type_ || BufferType::TF16 == buffer_type_) {
    int bit_width = buffer_type_ == BufferType::TF16 ? 16 : 8;
    buffer_element_size = bit_width / 8;
    auto encoding = (*buffer_attributes)->getEncoding();
    ORT_ENFORCE(encoding, "Failed to get buffer encoding for: ", name);
    user_buffer_encoding_.push_back(std::make_unique<zdl::DlSystem::UserBufferEncodingTfN>(*encoding));
    user_buffer_encoding = user_buffer_encoding_.back().get();
  } else if (BufferType::FLOAT == buffer_type_) {
    buffer_element_size = sizeof(float);
    user_buffer_encoding_.push_back(std::make_unique<zdl::DlSystem::UserBufferEncodingFloat>());
    user_buffer_encoding = user_buffer_encoding_.back().get();
  } else if (BufferType::UINT8 == buffer_type_) {
    buffer_element_size = 1;
    user_buffer_encoding_.push_back(std::make_unique<zdl::DlSystem::UserBufferEncodingUnsigned8Bit>());
    user_buffer_encoding = user_buffer_encoding_.back().get();
  }

  zdl::DlSystem::Optional<zdl::DlSystem::TensorShape> tensor_shape = (*buffer_attributes)->getDims();
  auto shape_rank = (*tensor_shape).rank();
  std::vector<size_t> strides(shape_rank);
  strides[strides.size() - 1] = buffer_element_size;
  size_t stride = strides[strides.size() - 1];
  for (size_t j = shape_rank - 1; j > 0; j--) {
    stride *= (*tensor_shape)[j];
    strides[j - 1] = stride;
  }
  size_t bufSize = CalcSizeFromDims((*tensor_shape).getDimensions(), shape_rank, buffer_element_size);

  user_buffer_attr_table_.emplace(name, UserBufferAttribute(bufSize, strides, user_buffer_encoding));

  return Status::OK();
}

Status SnpeLib::SetupUserBufferAttributes(const std::vector<std::string>& tensor_names) {
  for (size_t i = 0; i < tensor_names.size(); ++i) {
    ORT_RETURN_IF_ERROR(SetupUserBufferAttribute(tensor_names[i]));
  }

  return Status::OK();
}

Status SnpeLib::CheckInputsSize(const std::vector<std::string>& input_tensor_names,
                              const std::vector<int64_t>& input_sizes) {
  size_t elementSize = 1;
  for (size_t i = 0; i < input_tensor_names.size(); ++i) {
    auto input_shape = snpe_->getInputDimensions(input_tensor_names[i].c_str());
    ORT_ENFORCE(input_shape, "Snpe cannot get input shape for input name: ", input_tensor_names[i]);
    int64_t input_size = CalcSizeFromDims((*input_shape).getDimensions(), (*input_shape).rank(), elementSize);
    ORT_RETURN_IF(input_sizes.at(i) != input_size,
                  "Input size mismatch for : ", input_tensor_names[i],
                  " size on dlc: ", input_size,
                  " size on onnx: ", input_sizes.at(i));
  }
  return Status::OK();
}

Status SnpeLib::SetupInputTensors(const std::vector<std::string>& input_tensor_names) {
  input_tensor_map_.clear();
  input_tensors_.clear();
  input_tensors_.resize(input_tensor_names.size());
  for (size_t i = 0; i < input_tensor_names.size(); ++i) {
    auto input_shape = snpe_->getInputDimensions(input_tensor_names[i].c_str());
    if (!input_shape) {
      input_tensor_map_.clear();
      input_tensors_.clear();
      return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Failed to get input shape from Snpe for: ", input_tensor_names[i]);
    }
    input_tensors_[i] = zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(*input_shape);
    zdl::DlSystem::ITensor* input_tensor = input_tensors_[i].get();
    if (!input_tensor) {
      input_tensor_map_.clear();
      input_tensors_.clear();
      return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Snpe cannot create ITensor for inputs!");
    }
    input_tensor_map_.add(input_tensor_names[i].c_str(), input_tensor);
  }
  return Status::OK();
}

Status SnpeLib::InitializeSnpe(zdl::DlContainer::IDlContainer* container,
                               const std::vector<std::string>& output_tensor_names,
                               const std::vector<std::string>& input_tensor_names,
                               const std::vector<int64_t>& input_sizes,
                               const SnpeRuntimeOptions& snpe_settings) {
  ORT_RETURN_IF_NOT(snpe_settings.GetRuntimeTarget().IsAvailable(),
                    "Provided runtime target is not available: ",
                    snpe_settings.GetRuntimeTarget().ToString());

  ORT_RETURN_IF(0 == output_tensor_names.size() || 0 == input_tensor_names.size(),
                "Input names or output names are empty!");

  zdl::SNPE::SNPEBuilder snpe_builder(container);
  zdl::DlSystem::StringList dl_output_tensor_names = zdl::DlSystem::StringList();
  for (auto it = output_tensor_names.begin(); it != output_tensor_names.end(); ++it) {
    dl_output_tensor_names.append((*it).c_str());
  }

  buffer_type_ = snpe_settings.GetBufferType();
  bool use_user_buffer = buffer_type_ == BufferType::ITENSOR ? false : true;
  snpe_builder.setOutputTensors(dl_output_tensor_names)
              .setRuntimeProcessor(snpe_settings.GetRuntimeTarget().Get())
              .setExecutionPriorityHint(snpe_settings.GetExecutionPriority())
              .setUseUserSuppliedBuffers(use_user_buffer);
#ifdef __ANDROID__
  // use sustained performance mode on android variants.
  LOGS_DEFAULT(INFO) << "setPerformanceProfile to SUSTAINED_HIGH_PERFORMANCE for Android environment!";
  snpe_builder.setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::SUSTAINED_HIGH_PERFORMANCE);
#endif

#ifdef _WIN32
  if (snpe_settings.GetRuntimeTarget().Get() == zdl::DlSystem::Runtime_t::DSP) {
    zdl::DlSystem::PlatformConfig platformConfig;
    ORT_RETURN_IF_NOT(platformConfig.setPlatformOptionValue("unsignedPD", "ON"),
                      "unsignedPD is not available! ", GetSnpeErrorString());
    snpe_builder.setPlatformConfig(platformConfig);
  }
#endif

  snpe_ = snpe_builder.build();
  ORT_ENFORCE(snpe_, "Failed to create snpe instance! ", GetSnpeErrorString());

  // Make sure shape of snpe inputs are same with onnx model inputs
  ORT_RETURN_IF_ERROR(CheckInputsSize(input_tensor_names, input_sizes));

  ORT_ENFORCE(BufferType::UNKNOWN != buffer_type_, "Buffer type unknown!");

  if (BufferType::ITENSOR == buffer_type_) {
    ORT_RETURN_IF_ERROR(SetupInputTensors(input_tensor_names));
  } else {
    ORT_RETURN_IF_ERROR(SetupUserBufferAttributes(input_tensor_names));
    ORT_RETURN_IF_ERROR(SetupUserBufferAttributes(output_tensor_names));
  }

  return Status::OK();
}

Status SnpeLib::Initialize(const char* dlcPath,
                           const std::vector<std::string>& output_layer_names,
                           const std::vector<std::string>& input_layer_names,
                           const std::vector<int64_t>& input_sizes,
                           const SnpeRuntimeOptions& snpe_settings) {
  auto container = zdl::DlContainer::IDlContainer::open(zdl::DlSystem::String(dlcPath));
  ORT_ENFORCE(container, "Failed open " , dlcPath, " container file");

  ORT_RETURN_IF_ERROR(InitializeSnpe(container.get(),
                                     output_layer_names,
                                     input_layer_names,
                                     input_sizes,
                                     snpe_settings));

  return Status::OK();
}

Status SnpeLib::Initialize(const unsigned char* dlcData, size_t size,
                           const std::vector<std::string>& output_layer_names,
                           const std::vector<std::string>& input_layer_names,
                           const std::vector<int64_t>& input_sizes,
                           const SnpeRuntimeOptions& snpe_settings) {
  auto container = zdl::DlContainer::IDlContainer::open(dlcData, size);
  ORT_ENFORCE(container, "failed open container buffer!");

  ORT_RETURN_IF_ERROR(InitializeSnpe(container.get(),
                                     output_layer_names,
                                     input_layer_names,
                                     input_sizes,
                                     snpe_settings));

  return Status::OK();
}

Status SnpeLib::SnpeProcessMultipleOutput(const unsigned char* input,
                                          size_t input_size,
                                          size_t output_number,
                                          unsigned char* outputs[],
                                          size_t output_sizes[],
                                          const std::unordered_map<std::string, size_t>& output_names_index) {
  try {
    zdl::DlSystem::Optional<zdl::DlSystem::TensorShape> input_shape = snpe_->getInputDimensions();
    ORT_ENFORCE(input_shape, "Snpe cannot get input shape");

    ORT_RETURN_IF(input_tensors_.size() < 1, "Failed to create Snpe ITensor at initialization time.");

    zdl::DlSystem::ITensor* input_tensor = input_tensors_[0].get();
    // ensure size of the input buffer matches input shape buffer size
    size_t input_data_size = input_tensor->getSize() * sizeof(float);
    ORT_RETURN_IF(input_data_size != input_size, "Snpe input size incorrect: expected bytes ",
                  input_data_size, " given bytes ", input_size);
    memcpy(input_tensor->begin().dataPointer(), input, input_size);

    zdl::DlSystem::TensorMap output_tensor_map;
    ORT_RETURN_IF_NOT(snpe_->execute(input_tensor, output_tensor_map),
                      "Snpe Error while executing the network: ",
                      GetSnpeErrorString());
    ORT_RETURN_IF(output_tensor_map.size() == 0, "Failed to get output tensor map, ", GetSnpeErrorString());

    zdl::DlSystem::StringList tensor_names = output_tensor_map.getTensorNames();

    for (size_t i = 0; i < output_number; i++) {
      zdl::DlSystem::ITensor* tensor = output_tensor_map.getTensor(tensor_names.at(i));

      auto pos = output_names_index.find(tensor_names.at(i));
      ORT_RETURN_IF(pos == output_names_index.end(), "Something wrong with output name: ", tensor_names.at(i));
      size_t output_name_index = pos->second;

      // ensure size of the output buffer matches output shape buffer size
      size_t output_data_size = tensor->getSize() * sizeof(float);
      ORT_RETURN_IF(output_data_size > output_sizes[output_name_index],
                    "Snpe output size incorrect: output_layer: ", tensor_names.at(i),
                    " expected bytes ", output_data_size,
                    " given bytes ", output_sizes[output_name_index]);
      memcpy(outputs[output_name_index], tensor->cbegin().dataPointer(), output_data_size);
    }

    return Status::OK();
  } catch (...) {
    LOGS_DEFAULT(ERROR) << "Snpe threw exception " << GetSnpeErrorString();
    return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Snpe threw exception ", GetSnpeErrorString());
  }
}

Status SnpeLib::SnpeProcess(const unsigned char* input, size_t input_size, unsigned char* output, size_t output_size,
                          const std::unordered_map<std::string, size_t>& output_names_index) {
  // Use SnpeProcessMultipleOutput with 1 output layer
  const int output_layer = 1;
  unsigned char* outputs_array[output_layer];
  size_t output_sizes_array[output_layer];
  outputs_array[0] = output;
  output_sizes_array[0] = output_size;
  ORT_RETURN_IF_ERROR(SnpeProcessMultipleOutput(input, input_size, output_layer, outputs_array,
                                                output_sizes_array, output_names_index));
  return Status::OK();
}

Status SnpeLib::SnpeProcessMultiInputsMultiOutputs(const unsigned char** inputs,
                                                 const size_t* input_sizes,
                                                 size_t input_number,
                                                 unsigned char** outputs,
                                                 const size_t* output_sizes,
                                                 size_t output_number,
                                                 const std::unordered_map<std::string, size_t>& output_names_index) {
  try {
    ORT_RETURN_IF(input_number != input_tensors_.size(),
                  "Snpe number of inputs doesn't match: expected ", input_number,
                  " given ", input_tensors_.size());
    for (size_t i = 0; i < input_number; ++i) {
      zdl::DlSystem::ITensor* input_tensor = input_tensors_[i].get();
      // ensure size of the input buffer matches input shape buffer size
      size_t input_data_size = input_tensor->getSize() * sizeof(float);
      ORT_RETURN_IF(input_data_size != input_sizes[i],
                    "Snpe input size incorrect: expected bytes ", input_data_size,
                    ", given bytes ", input_sizes[i]);
      memcpy(input_tensor->begin().dataPointer(), inputs[i], input_sizes[i]);
    }
    zdl::DlSystem::TensorMap output_tensor_map;
    ORT_RETURN_IF_NOT(snpe_->execute(input_tensor_map_, output_tensor_map),
                      "Snpe Error while executing the network: ",
                      GetSnpeErrorString());
    ORT_RETURN_IF(output_tensor_map.size() == 0, "Failed to get output tensor map, ", GetSnpeErrorString());

    zdl::DlSystem::StringList tensor_names = output_tensor_map.getTensorNames();

    for (size_t i = 0; i < output_number; i++) {
      zdl::DlSystem::ITensor* tensor = output_tensor_map.getTensor(tensor_names.at(i));

      auto pos = output_names_index.find(tensor_names.at(i));
      ORT_RETURN_IF(pos == output_names_index.end(), "Something wrong with output name: ", tensor_names.at(i));
      size_t output_name_index = pos->second;

      // ensure size of the output buffer matches output shape buffer size
      size_t output_data_size = tensor->getSize() * sizeof(float);
      ORT_RETURN_IF(output_data_size > output_sizes[output_name_index],
                    "Snpe output size incorrect: output_layer: ", tensor_names.at(i),
                    " expected bytes ", output_data_size,
                    " given bytes ", output_sizes[output_name_index]);
      memcpy(outputs[output_name_index], tensor->cbegin().dataPointer(), output_data_size);
    }

    return Status::OK();
  } catch (...) {
    LOGS_DEFAULT(ERROR) << "Snpe threw exception " << GetSnpeErrorString();
    return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Snpe threw exception ", GetSnpeErrorString());
  }
}

Status SnpeLib::SnpeProcessWithUserBuffer(const std::vector<std::string>& input_names,
                                        const unsigned char** inputs,
                                        size_t input_number,
                                        unsigned char** outputs,
                                        const std::unordered_map<std::string, size_t>& output_names_index) {
  zdl::DlSystem::IUserBufferFactory& user_buffer_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory();
  snpe_user_input_buffers_.clear();
  snpe_user_input_buffers_.reserve(input_number);
  zdl::DlSystem::UserBufferMap input_buffer_map;
  for (size_t i = 0; i < input_number; ++i) {
    std::string input_name(input_names.at(i));
    auto buffer_attr_pos = user_buffer_attr_table_.at(input_name);
    snpe_user_input_buffers_.push_back(user_buffer_factory.createUserBuffer(const_cast<unsigned char*>(inputs[i]),
                                                                            buffer_attr_pos.buffer_size,
                                                                            buffer_attr_pos.strides,
                                                                            buffer_attr_pos.user_buffer_encoding));
    input_buffer_map.add(input_name.c_str(), snpe_user_input_buffers_.back().get());
  }

  zdl::DlSystem::UserBufferMap output_buffer_map;
  snpe_user_output_buffers_.clear();
  snpe_user_output_buffers_.reserve(output_names_index.size());
  for (auto it = output_names_index.begin(); it != output_names_index.end(); ++it) {
    auto buffer_attr_pos = user_buffer_attr_table_.at(it->first);
    snpe_user_output_buffers_.push_back(user_buffer_factory.createUserBuffer(outputs[it->second],
                                                                             buffer_attr_pos.buffer_size,
                                                                             buffer_attr_pos.strides,
                                                                             buffer_attr_pos.user_buffer_encoding));
    output_buffer_map.add(it->first.c_str(), snpe_user_output_buffers_.back().get());
  }

  // Execute the input buffer map on the model with SNPE
  ORT_RETURN_IF_NOT(snpe_->execute(input_buffer_map, output_buffer_map),
                    "Snpe Error while executing the network: ",
                    GetSnpeErrorString());

  return Status::OK();
}

std::unique_ptr<SnpeLib> SnpeLibFactory(const unsigned char* dlc_data,
                                        size_t size,
                                        const std::unordered_map<std::string, std::string>& options,
                                        const std::vector<std::string>& output_layer_names,
                                        const std::vector<std::string>& input_layer_names,
                                        const std::vector<int64_t>& input_sizes,
                                        BufferType& buffer_type) {
  auto object = std::make_unique<SnpeLib>();

  if (!object) {
    ORT_THROW("failed to make snpe library");
  }

  SnpeRuntimeOptions runtime_options(options);
  ORT_THROW_IF_ERROR(object->Initialize(dlc_data,
                                        size,
                                        output_layer_names,
                                        input_layer_names,
                                        input_sizes,
                                        runtime_options));

  buffer_type = runtime_options.GetBufferType();

  return object;
}

}  // namespace snpe
}  // namespace contrib
}  // namespace onnxruntime


text:
package ca.uhn.fhir.jpa.dao.data;

import ca.uhn.fhir.jpa.entity.TermConceptMapGroupElementTarget;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface ITermConceptMapGroupElementTargetDao extends JpaRepository<TermConceptMapGroupElementTarget, Long>, IHapiFhirJpaRepository {
	@Query("DELETE FROM TermConceptMapGroupElementTarget t WHERE t.myId = :pid")
	@Modifying
	void deleteTermConceptMapGroupElementTargetById(@Param("pid") Long theId);
}