text:
#ifndef _IXGBE_ETHDEV_H_
#define _IXGBE_ETHDEV_H_
#include "ixgbe/ixgbe_dcb.h"
#include "ixgbe/ixgbe_dcb_82599.h"
#include "ixgbe/ixgbe_dcb_82598.h"
#include "ixgbe_bypass.h"

/* need update link, bit flag */
#define IXGBE_FLAG_NEED_LINK_UPDATE (uint32_t)(1 << 0)
#define IXGBE_FLAG_MAILBOX          (uint32_t)(1 << 1)

/*
 * Defines that were not part of ixgbe_type.h as they are not used by the
 * FreeBSD driver.
 */
#define IXGBE_ADVTXD_MAC_1588       0x00080000 /* IEEE1588 Timestamp packet */
#define IXGBE_RXD_STAT_TMST         0x10000    /* Timestamped Packet indication */
#define IXGBE_ADVTXD_TUCMD_L4T_RSV  0x00001800 /* L4 Packet TYPE, resvd  */
#define IXGBE_RXDADV_ERR_CKSUM_BIT  30
#define IXGBE_RXDADV_ERR_CKSUM_MSK  3
#define IXGBE_ADVTXD_MACLEN_SHIFT   9          /* Bit shift for l2_len */
#define IXGBE_NB_STAT_MAPPING_REGS  32
#define IXGBE_EXTENDED_VLAN	  (uint32_t)(1 << 26) /* EXTENDED VLAN ENABLE */
#define IXGBE_VFTA_SIZE 128
#define IXGBE_VLAN_TAG_SIZE 4
#define IXGBE_MAX_RX_QUEUE_NUM	128
#ifndef NBBY
#define NBBY	8	/* number of bits in a byte */
#endif
#define IXGBE_HWSTRIP_BITMAP_SIZE (IXGBE_MAX_RX_QUEUE_NUM / (sizeof(uint32_t) * NBBY))

/* Loopback operation modes */
/* 82599 specific loopback operation types */
#define IXGBE_LPBK_82599_NONE   0x0 /* Default value. Loopback is disabled. */
#define IXGBE_LPBK_82599_TX_RX  0x1 /* Tx->Rx loopback operation is enabled. */

#define IXGBE_MAX_JUMBO_FRAME_SIZE      0x2600 /* Maximum Jumbo frame size. */

#define IXGBE_RTTBCNRC_RF_INT_MASK_BASE 0x000003FF
#define IXGBE_RTTBCNRC_RF_INT_MASK_M \
	(IXGBE_RTTBCNRC_RF_INT_MASK_BASE << IXGBE_RTTBCNRC_RF_INT_SHIFT)

#define IXGBE_MAX_QUEUE_NUM_PER_VF  8

#define IXGBE_SYN_FILTER_ENABLE         0x00000001 /* syn filter enable field */
#define IXGBE_SYN_FILTER_QUEUE          0x000000FE /* syn filter queue field */
#define IXGBE_SYN_FILTER_QUEUE_SHIFT    1          /* syn filter queue field shift */
#define IXGBE_SYN_FILTER_SYNQFP         0x80000000 /* syn filter SYNQFP */

#define IXGBE_ETQF_UP                   0x00070000 /* ethertype filter priority field */
#define IXGBE_ETQF_SHIFT                16
#define IXGBE_ETQF_UP_EN                0x00080000
#define IXGBE_ETQF_ETHERTYPE            0x0000FFFF /* ethertype filter ethertype field */
#define IXGBE_ETQF_MAX_PRI              7

#define IXGBE_SDPQF_DSTPORT             0xFFFF0000 /* dst port field */
#define IXGBE_SDPQF_DSTPORT_SHIFT       16         /* dst port field shift */
#define IXGBE_SDPQF_SRCPORT             0x0000FFFF /* src port field */

#define IXGBE_L34T_IMIR_SIZE_BP         0x00001000
#define IXGBE_L34T_IMIR_RESERVE         0x00080000 /* bit 13 to 19 must be set to 1000000b. */
#define IXGBE_L34T_IMIR_LLI             0x00100000
#define IXGBE_L34T_IMIR_QUEUE           0x0FE00000
#define IXGBE_L34T_IMIR_QUEUE_SHIFT     21
#define IXGBE_5TUPLE_MAX_PRI            7
#define IXGBE_5TUPLE_MIN_PRI            1

#define IXGBE_RSS_OFFLOAD_ALL ( \
	ETH_RSS_IPV4 | \
	ETH_RSS_NONFRAG_IPV4_TCP | \
	ETH_RSS_NONFRAG_IPV4_UDP | \
	ETH_RSS_IPV6 | \
	ETH_RSS_NONFRAG_IPV6_TCP | \
	ETH_RSS_NONFRAG_IPV6_UDP | \
	ETH_RSS_IPV6_EX | \
	ETH_RSS_IPV6_TCP_EX | \
	ETH_RSS_IPV6_UDP_EX)

/*
 * Information about the fdir mode.
 */

struct ixgbe_hw_fdir_mask {
	uint16_t vlan_tci_mask;
	uint32_t src_ipv4_mask;
	uint32_t dst_ipv4_mask;
	uint16_t src_ipv6_mask;
	uint16_t dst_ipv6_mask;
	uint16_t src_port_mask;
	uint16_t dst_port_mask;
	uint16_t flex_bytes_mask;
};

struct ixgbe_hw_fdir_info {
	struct ixgbe_hw_fdir_mask mask;
	uint8_t     flex_bytes_offset;
	uint16_t    collision;
	uint16_t    free;
	uint16_t    maxhash;
	uint8_t     maxlen;
	uint64_t    add;
	uint64_t    remove;
	uint64_t    f_add;
	uint64_t    f_remove;
};

/* structure for interrupt relative data */
struct ixgbe_interrupt {
	uint32_t flags;
	uint32_t mask;
};

struct ixgbe_stat_mapping_registers {
	uint32_t tqsm[IXGBE_NB_STAT_MAPPING_REGS];
	uint32_t rqsmr[IXGBE_NB_STAT_MAPPING_REGS];
};

struct ixgbe_vfta {
	uint32_t vfta[IXGBE_VFTA_SIZE];
};

struct ixgbe_hwstrip {
	uint32_t bitmap[IXGBE_HWSTRIP_BITMAP_SIZE];
};

/*
 * VF data which used by PF host only
 */
#define IXGBE_MAX_VF_MC_ENTRIES		30
#define IXGBE_MAX_MR_RULE_ENTRIES	4 /* number of mirroring rules supported */
#define IXGBE_MAX_UTA                   128

struct ixgbe_uta_info {
	uint8_t  uc_filter_type;
	uint16_t uta_in_use;
	uint32_t uta_shadow[IXGBE_MAX_UTA];
};

struct ixgbe_mirror_info {
	struct rte_eth_vmdq_mirror_conf mr_conf[ETH_VMDQ_NUM_MIRROR_RULE];
	/**< store PF mirror rules configuration*/
};

struct ixgbe_vf_info {
	uint8_t vf_mac_addresses[ETHER_ADDR_LEN];
	uint16_t vf_mc_hashes[IXGBE_MAX_VF_MC_ENTRIES];
	uint16_t num_vf_mc_hashes;
	uint16_t default_vf_vlan_id;
	uint16_t vlans_enabled;
	bool clear_to_send;
	uint16_t tx_rate[IXGBE_MAX_QUEUE_NUM_PER_VF];
	uint16_t vlan_count;
	uint8_t spoofchk_enabled;
	uint8_t api_version;
};

/*
 *  Possible l4type of 5tuple filters.
 */
enum ixgbe_5tuple_protocol {
	IXGBE_FILTER_PROTOCOL_TCP = 0,
	IXGBE_FILTER_PROTOCOL_UDP,
	IXGBE_FILTER_PROTOCOL_SCTP,
	IXGBE_FILTER_PROTOCOL_NONE,
};

TAILQ_HEAD(ixgbe_5tuple_filter_list, ixgbe_5tuple_filter);

struct ixgbe_5tuple_filter_info {
	uint32_t dst_ip;
	uint32_t src_ip;
	uint16_t dst_port;
	uint16_t src_port;
	enum ixgbe_5tuple_protocol proto;        /* l4 protocol. */
	uint8_t priority;        /* seven levels (001b-111b), 111b is highest,
				      used when more than one filter matches. */
	uint8_t dst_ip_mask:1,   /* if mask is 1b, do not compare dst ip. */
		src_ip_mask:1,   /* if mask is 1b, do not compare src ip. */
		dst_port_mask:1, /* if mask is 1b, do not compare dst port. */
		src_port_mask:1, /* if mask is 1b, do not compare src port. */
		proto_mask:1;    /* if mask is 1b, do not compare protocol. */
};

/* 5tuple filter structure */
struct ixgbe_5tuple_filter {
	TAILQ_ENTRY(ixgbe_5tuple_filter) entries;
	uint16_t index;       /* the index of 5tuple filter */
	struct ixgbe_5tuple_filter_info filter_info;
	uint16_t queue;       /* rx queue assigned to */
};

#define IXGBE_5TUPLE_ARRAY_SIZE \
	(RTE_ALIGN(IXGBE_MAX_FTQF_FILTERS, (sizeof(uint32_t) * NBBY)) / \
	 (sizeof(uint32_t) * NBBY))

/*
 * Structure to store filters' info.
 */
struct ixgbe_filter_info {
	uint8_t ethertype_mask;  /* Bit mask for every used ethertype filter */
	/* store used ethertype filters*/
	uint16_t ethertype_filters[IXGBE_MAX_ETQF_FILTERS];
	/* Bit mask for every used 5tuple filter */
	uint32_t fivetuple_mask[IXGBE_5TUPLE_ARRAY_SIZE];
	struct ixgbe_5tuple_filter_list fivetuple_list;
};

/*
 * Structure to store private data for each driver instance (for each port).
 */
struct ixgbe_adapter {
	struct ixgbe_hw             hw;
	struct ixgbe_hw_stats       stats;
	struct ixgbe_hw_fdir_info   fdir;
	struct ixgbe_interrupt      intr;
	struct ixgbe_stat_mapping_registers stat_mappings;
	struct ixgbe_vfta           shadow_vfta;
	struct ixgbe_hwstrip		hwstrip;
	struct ixgbe_dcb_config     dcb_config;
	struct ixgbe_mirror_info    mr_data;
	struct ixgbe_vf_info        *vfdata;
	struct ixgbe_uta_info       uta_info;
#ifdef RTE_NIC_BYPASS
	struct ixgbe_bypass_info    bps;
#endif /* RTE_NIC_BYPASS */
	struct ixgbe_filter_info    filter;
};

#define IXGBE_DEV_PRIVATE_TO_HW(adapter)\
	(&((struct ixgbe_adapter *)adapter)->hw)

#define IXGBE_DEV_PRIVATE_TO_STATS(adapter) \
	(&((struct ixgbe_adapter *)adapter)->stats)

#define IXGBE_DEV_PRIVATE_TO_INTR(adapter) \
	(&((struct ixgbe_adapter *)adapter)->intr)

#define IXGBE_DEV_PRIVATE_TO_FDIR_INFO(adapter) \
	(&((struct ixgbe_adapter *)adapter)->fdir)

#define IXGBE_DEV_PRIVATE_TO_STAT_MAPPINGS(adapter) \
	(&((struct ixgbe_adapter *)adapter)->stat_mappings)

#define IXGBE_DEV_PRIVATE_TO_VFTA(adapter) \
	(&((struct ixgbe_adapter *)adapter)->shadow_vfta)

#define IXGBE_DEV_PRIVATE_TO_HWSTRIP_BITMAP(adapter) \
	(&((struct ixgbe_adapter *)adapter)->hwstrip)

#define IXGBE_DEV_PRIVATE_TO_DCB_CFG(adapter) \
	(&((struct ixgbe_adapter *)adapter)->dcb_config)

#define IXGBE_DEV_PRIVATE_TO_P_VFDATA(adapter) \
	(&((struct ixgbe_adapter *)adapter)->vfdata)

#define IXGBE_DEV_PRIVATE_TO_PFDATA(adapter) \
	(&((struct ixgbe_adapter *)adapter)->mr_data)

#define IXGBE_DEV_PRIVATE_TO_UTA(adapter) \
	(&((struct ixgbe_adapter *)adapter)->uta_info)

#define IXGBE_DEV_PRIVATE_TO_FILTER_INFO(adapter) \
	(&((struct ixgbe_adapter *)adapter)->filter)

/*
 * RX/TX function prototypes
 */
void ixgbe_dev_clear_queues(struct rte_eth_dev *dev);

void ixgbe_dev_rx_queue_release(void *rxq);

void ixgbe_dev_tx_queue_release(void *txq);

int  ixgbe_dev_rx_queue_setup(struct rte_eth_dev *dev, uint16_t rx_queue_id,
		uint16_t nb_rx_desc, unsigned int socket_id,
		const struct rte_eth_rxconf *rx_conf,
		struct rte_mempool *mb_pool);

int  ixgbe_dev_tx_queue_setup(struct rte_eth_dev *dev, uint16_t tx_queue_id,
		uint16_t nb_tx_desc, unsigned int socket_id,
		const struct rte_eth_txconf *tx_conf);

uint32_t ixgbe_dev_rx_queue_count(struct rte_eth_dev *dev,
		uint16_t rx_queue_id);

int ixgbe_dev_rx_descriptor_done(void *rx_queue, uint16_t offset);

int ixgbe_dev_rx_init(struct rte_eth_dev *dev);

void ixgbe_dev_tx_init(struct rte_eth_dev *dev);

int ixgbe_dev_rxtx_start(struct rte_eth_dev *dev);

int ixgbe_dev_rx_queue_start(struct rte_eth_dev *dev, uint16_t rx_queue_id);

int ixgbe_dev_rx_queue_stop(struct rte_eth_dev *dev, uint16_t rx_queue_id);

int ixgbe_dev_tx_queue_start(struct rte_eth_dev *dev, uint16_t tx_queue_id);

int ixgbe_dev_tx_queue_stop(struct rte_eth_dev *dev, uint16_t tx_queue_id);

int ixgbevf_dev_rx_init(struct rte_eth_dev *dev);

void ixgbevf_dev_tx_init(struct rte_eth_dev *dev);

void ixgbevf_dev_rxtx_start(struct rte_eth_dev *dev);

uint16_t ixgbe_recv_pkts(void *rx_queue, struct rte_mbuf **rx_pkts,
		uint16_t nb_pkts);

uint16_t ixgbe_recv_scattered_pkts(void *rx_queue,
		struct rte_mbuf **rx_pkts, uint16_t nb_pkts);

uint16_t ixgbe_xmit_pkts(void *tx_queue, struct rte_mbuf **tx_pkts,
		uint16_t nb_pkts);

uint16_t ixgbe_xmit_pkts_simple(void *tx_queue, struct rte_mbuf **tx_pkts,
		uint16_t nb_pkts);

int ixgbe_dev_rss_hash_update(struct rte_eth_dev *dev,
			      struct rte_eth_rss_conf *rss_conf);

int ixgbe_dev_rss_hash_conf_get(struct rte_eth_dev *dev,
				struct rte_eth_rss_conf *rss_conf);

/*
 * Flow director function prototypes
 */
int ixgbe_fdir_configure(struct rte_eth_dev *dev);

void ixgbe_configure_dcb(struct rte_eth_dev *dev);

/*
 * misc function prototypes
 */
void ixgbe_vlan_hw_filter_enable(struct rte_eth_dev *dev);

void ixgbe_vlan_hw_filter_disable(struct rte_eth_dev *dev);

void ixgbe_vlan_hw_strip_enable_all(struct rte_eth_dev *dev);

void ixgbe_vlan_hw_strip_disable_all(struct rte_eth_dev *dev);

void ixgbe_pf_host_init(struct rte_eth_dev *eth_dev);

void ixgbe_pf_mbx_process(struct rte_eth_dev *eth_dev);

int ixgbe_pf_host_configure(struct rte_eth_dev *eth_dev);

uint32_t ixgbe_convert_vm_rx_mask_to_val(uint16_t rx_mask, uint32_t orig_val);

int ixgbe_fdir_ctrl_func(struct rte_eth_dev *dev,
			enum rte_filter_op filter_op, void *arg);
#endif /* _IXGBE_ETHDEV_H_ */


text:
package io.netty.handler.ssl;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import org.apache.tomcat.jni.SSL;
import org.apache.tomcat.jni.SSLContext;

import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import static io.netty.util.internal.ObjectUtil.*;

/**
 * A server-side {@link SslContext} which uses OpenSSL's SSL/TLS implementation.
 */
public final class OpenSslServerContext extends OpenSslContext {
    private final OpenSslServerSessionContext sessionContext;
    private final OpenSslEngineMap engineMap;

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format
     * @param keyFile a PKCS#8 private key file in PEM format
     */
    public OpenSslServerContext(File certChainFile, File keyFile) throws SSLException {
        this(certChainFile, keyFile, null);
    }

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format
     * @param keyFile a PKCS#8 private key file in PEM format
     * @param keyPassword the password of the {@code keyFile}.
     *                    {@code null} if it's not password-protected.
     */
    public OpenSslServerContext(File certChainFile, File keyFile, String keyPassword) throws SSLException {
        this(certChainFile, keyFile, keyPassword, null, null,
            OpenSslDefaultApplicationProtocolNegotiator.INSTANCE, 0, 0);
    }

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format
     * @param keyFile a PKCS#8 private key file in PEM format
     * @param keyPassword the password of the {@code keyFile}.
     *                    {@code null} if it's not password-protected.
     * @param ciphers the cipher suites to enable, in the order of preference.
     *                {@code null} to use the default cipher suites.
     * @param apn Provides a means to configure parameters related to application protocol negotiation.
     * @param sessionCacheSize the size of the cache used for storing SSL session objects.
     *                         {@code 0} to use the default value.
     * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
     *                       {@code 0} to use the default value.
     */
    public OpenSslServerContext(
            File certChainFile, File keyFile, String keyPassword,
            Iterable<String> ciphers, ApplicationProtocolConfig apn,
            long sessionCacheSize, long sessionTimeout) throws SSLException {
        this(certChainFile, keyFile, keyPassword, null, ciphers,
            toNegotiator(apn, false), sessionCacheSize, sessionTimeout);
    }

    /**
     * @deprecated Use the constructors that accepts {@link ApplicationProtocolConfig} or
     *             {@link ApplicationProtocolNegotiator} instead.
     *
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format
     * @param keyFile a PKCS#8 private key file in PEM format
     * @param keyPassword the password of the {@code keyFile}.
     *                    {@code null} if it's not password-protected.
     * @param ciphers the cipher suites to enable, in the order of preference.
     *                {@code null} to use the default cipher suites.
     * @param nextProtocols the application layer protocols to accept, in the order of preference.
     *                      {@code null} to disable TLS NPN/ALPN extension.
     * @param sessionCacheSize the size of the cache used for storing SSL session objects.
     *                         {@code 0} to use the default value.
     * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
     *                       {@code 0} to use the default value.
     */
    @Deprecated
    public OpenSslServerContext(
            File certChainFile, File keyFile, String keyPassword,
            Iterable<String> ciphers, Iterable<String> nextProtocols,
            long sessionCacheSize, long sessionTimeout) throws SSLException {
        this(certChainFile, keyFile, keyPassword, ciphers,
            toApplicationProtocolConfig(nextProtocols), sessionCacheSize, sessionTimeout);
    }

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format
     * @param keyFile a PKCS#8 private key file in PEM format
     * @param keyPassword the password of the {@code keyFile}.
     *                    {@code null} if it's not password-protected.
     * @param ciphers the cipher suites to enable, in the order of preference.
     *                {@code null} to use the default cipher suites.
     * @param config Application protocol config.
     * @param sessionCacheSize the size of the cache used for storing SSL session objects.
     *                         {@code 0} to use the default value.
     * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
     *                       {@code 0} to use the default value.
     */
    public OpenSslServerContext(
            File certChainFile, File keyFile, String keyPassword, TrustManagerFactory trustManagerFactory,
            Iterable<String> ciphers, ApplicationProtocolConfig config,
            long sessionCacheSize, long sessionTimeout) throws SSLException {
        this(certChainFile, keyFile, keyPassword, trustManagerFactory, ciphers,
                toNegotiator(config, true), sessionCacheSize, sessionTimeout);
    }

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format
     * @param keyFile a PKCS#8 private key file in PEM format
     * @param keyPassword the password of the {@code keyFile}.
     *                    {@code null} if it's not password-protected.
     * @param ciphers the cipher suites to enable, in the order of preference.
     *                {@code null} to use the default cipher suites.
     * @param apn Application protocol negotiator.
     * @param sessionCacheSize the size of the cache used for storing SSL session objects.
     *                         {@code 0} to use the default value.
     * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
     *                       {@code 0} to use the default value.
     */
    public OpenSslServerContext(
            File certChainFile, File keyFile, String keyPassword, TrustManagerFactory trustManagerFactory,
            Iterable<String> ciphers, OpenSslApplicationProtocolNegotiator apn,
            long sessionCacheSize, long sessionTimeout) throws SSLException {

         super(ciphers, apn, sessionCacheSize, sessionTimeout, SSL.SSL_MODE_SERVER);
         OpenSsl.ensureAvailability();

        checkNotNull(certChainFile, "certChainFile");
        if (!certChainFile.isFile()) {
            throw new IllegalArgumentException("certChainFile is not a file: " + certChainFile);
        }
        checkNotNull(keyFile, "keyFile");
        if (!keyFile.isFile()) {
            throw new IllegalArgumentException("keyPath is not a file: " + keyFile);
        }
        if (keyPassword == null) {
            keyPassword = "";
        }

        // Create a new SSL_CTX and configure it.
        boolean success = false;
        try {
            synchronized (OpenSslContext.class) {
                /* Set certificate verification policy. */
                SSLContext.setVerify(ctx, SSL.SSL_CVERIFY_NONE, VERIFY_DEPTH);

                /* Load the certificate chain. We must skip the first cert when server mode */
                if (!SSLContext.setCertificateChainFile(ctx, certChainFile.getPath(), true)) {
                    long error = SSL.getLastErrorNumber();
                    if (OpenSsl.isError(error)) {
                        String err = SSL.getErrorString(error);
                        throw new SSLException(
                                "failed to set certificate chain: " + certChainFile + " (" + err + ')');
                    }
                }

                /* Load the certificate file and private key. */
                try {
                    if (!SSLContext.setCertificate(
                            ctx, certChainFile.getPath(), keyFile.getPath(), keyPassword, SSL.SSL_AIDX_RSA)) {
                        long error = SSL.getLastErrorNumber();
                        if (OpenSsl.isError(error)) {
                            String err = SSL.getErrorString(error);
                            throw new SSLException("failed to set certificate: " +
                                    certChainFile + " and " + keyFile + " (" + err + ')');
                        }
                    }
                } catch (SSLException e) {
                    throw e;
                } catch (Exception e) {
                    throw new SSLException("failed to set certificate: " + certChainFile + " and " + keyFile, e);
                }
                try {
                    KeyStore ks = KeyStore.getInstance("JKS");
                    ks.load(null, null);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    KeyFactory rsaKF = KeyFactory.getInstance("RSA");
                    KeyFactory dsaKF = KeyFactory.getInstance("DSA");

                    ByteBuf encodedKeyBuf = PemReader.readPrivateKey(keyFile);
                    byte[] encodedKey = new byte[encodedKeyBuf.readableBytes()];
                    encodedKeyBuf.readBytes(encodedKey).release();

                    char[] keyPasswordChars = keyPassword.toCharArray();
                    PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec(keyPasswordChars, encodedKey);

                    PrivateKey key;
                    try {
                        key = rsaKF.generatePrivate(encodedKeySpec);
                    } catch (InvalidKeySpecException ignore) {
                        key = dsaKF.generatePrivate(encodedKeySpec);
                    }

                    List<Certificate> certChain = new ArrayList<Certificate>();
                    ByteBuf[] certs = PemReader.readCertificates(certChainFile);
                    try {
                        for (ByteBuf buf: certs) {
                            certChain.add(cf.generateCertificate(new ByteBufInputStream(buf)));
                        }
                    } finally {
                        for (ByteBuf buf: certs) {
                            buf.release();
                        }
                    }

                    ks.setKeyEntry("key", key, keyPasswordChars, certChain.toArray(new Certificate[certChain.size()]));

                    if (trustManagerFactory == null) {
                        // Mimic the way SSLContext.getInstance(KeyManager[], null, null) works
                        trustManagerFactory = TrustManagerFactory.getInstance(
                                TrustManagerFactory.getDefaultAlgorithm());
                        trustManagerFactory.init((KeyStore) null);
                    } else {
                        trustManagerFactory.init(ks);
                    }

                    final X509TrustManager manager = chooseTrustManager(trustManagerFactory.getTrustManagers());

                    engineMap = newEngineMap(manager);
                    // Use this to prevent an error when running on java < 7
                    if (useExtendedTrustManager(manager)) {
                        final X509ExtendedTrustManager extendedManager = (X509ExtendedTrustManager) manager;
                        SSLContext.setCertVerifyCallback(ctx, new AbstractCertificateVerifier() {
                            @Override
                            void verify(long ssl, X509Certificate[] peerCerts, String auth) throws Exception {
                                OpenSslEngine engine = engineMap.remove(ssl);
                                extendedManager.checkClientTrusted(peerCerts, auth, engine);
                            }
                        });
                    } else {
                        SSLContext.setCertVerifyCallback(ctx, new AbstractCertificateVerifier() {
                            @Override
                            void verify(long ssl, X509Certificate[] peerCerts, String auth) throws Exception {
                                manager.checkClientTrusted(peerCerts, auth);
                            }
                        });
                    }
                } catch (Exception e) {
                    throw new SSLException("unable to setup trustmanager", e);
                }
            }
            sessionContext = new OpenSslServerSessionContext(ctx);
            success = true;
        } finally {
            if (!success) {
                destroyPools();
            }
        }
    }

    @Override
    public OpenSslServerSessionContext sessionContext() {
        return sessionContext;
    }

    @Override
    OpenSslEngineMap engineMap() {
        return engineMap;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Substitution::Substitution():
	variable(""), term()
{
	// nothing to do
}

Substitution::Substitution(const Substitution &s):
	variable(s.variable), term(s.term)
{
	// nothing to do
}

Substitution::Substitution(const Term &t, const String &v):
	variable(v), term(t)
{
	// nothing to do
}

Substitution::~Substitution()
{
	// nothing to do
}

// assignment operator
Substitution &
Substitution::operator=(const Substitution &rhs)
{
	if (this != &rhs)
	{
		variable = rhs.variable;
		term = rhs.term;
	}
	return(*this);
}

// comparison operators
int
Substitution::operator==(const Substitution &s) const
{
	return(variable == s.variable);
}

int
Substitution::operator!=(const Substitution &s) const
{
	return(variable != s.variable);
}

int
Substitution::operator<(const Substitution &s) const
{
	return(variable < s.variable);
}

int
Substitution::operator<=(const Substitution &s) const
{
	return(variable <= s.variable);
}

int
Substitution::operator>(const Substitution &s) const
{
	return(variable > s.variable);
}

int
Substitution::operator>=(const Substitution &s) const
{
	return(variable >= s.variable);
}

// composition, combine two substitutions
Substitution
Substitution::operator*(const Substitution &s) const
{
	Substitution composition(*this);
	MustBeTrue(s.applyTo(composition.term) == OK);
	return(composition);
}

int
Substitution::applyTo(Term &t) const
{
	// search for the substitution variable in the term
	if (t.type == Term::Variable)
	{
		// check if the variables are the same
		if (t.value == variable)
			t = term;
	}
	else if (t.type == Term::PredicateFunction || t.type == Term::Function)
	{
		ListIterator<Term *> pargsIter(*t.pargs);
		for ( ; !pargsIter.done(); pargsIter++)
		{
			if (pargsIter() == NULL)
				continue;
			if (applyTo(*pargsIter()) != OK)
				return(NOTOK);
		}
	}
	return(OK);
}

// print data
ostream &
operator<<(ostream &os, const Substitution &s)
{
	os << "{ " << s.term << "/" << s.variable << " }";
	return(os);
}

// substitution constructors and destructor
Substitutions::Substitutions():
	psubs(NULL)
{
	psubs = new List<Substitution *>;
	MustBeTrue(psubs != NULL);
}

Substitutions::Substitutions(const Substitutions &s):
	psubs(NULL)
{
	psubs = new List<Substitution *>;
	MustBeTrue(psubs != NULL);
	ListIterator<Substitution *> psubsIter(*s.psubs);
	for ( ; !psubsIter.done(); psubsIter++)
	{
		if (psubsIter() == NULL)
			continue;
		Substitution *psub = new Substitution(*psubsIter());
		MustBeTrue(psub != NULL);
		MustBeTrue(psubs->insertAtEnd(psub) == OK);
	}
}

Substitutions::~Substitutions()
{
	ListIterator<Substitution *> psubsIter(*psubs);
	for ( ; !psubsIter.done(); psubsIter++)
	{
		if (psubsIter() != NULL)
			delete psubsIter();
	}
	psubs->clear();
	delete psubs;
	psubs = NULL;
}

// assignment operator
Substitutions &
Substitutions::operator=(const Substitutions &rhs)
{
	if (this != &rhs)
	{
		// delete current data
		ListIterator<Substitution *> psubsIter(*psubs);
		for ( ; !psubsIter.done(); psubsIter++)
		{
			if (psubsIter() != NULL)
				delete psubsIter();
		}
		psubs->clear();

		// insert new data
		ListIterator<Substitution *> prhssubsIter(*rhs.psubs);
		for ( ; !prhssubsIter.done(); prhssubsIter++)
		{
			if (prhssubsIter() == NULL)
				continue;
			Substitution *psub = new Substitution(*prhssubsIter());
			MustBeTrue(psub != NULL);
			MustBeTrue(psubs->insertAtEnd(psub) == OK);
		}
	}
	return(*this);
}

// comparison operators
int
Substitutions::operator==(const Substitutions &s) const
{
	ListIterator<Substitution *> psi(*psubs);
	ListIterator<Substitution *> pssi(*s.psubs);
	for ( ; !psi.done() && !pssi.done(); psi++, pssi++)
	{
		if (psi()->variable != pssi()->variable)
			return(0);
	}
	if (!psi.done() || !pssi.done())
		return(0);
	else
		return(1);
}

int
Substitutions::operator!=(const Substitutions &s) const
{
	ListIterator<Substitution *> psi(*psubs);
	ListIterator<Substitution *> pssi(*s.psubs);
	for ( ; !psi.done() && !pssi.done(); psi++, pssi++)
	{
		if (psi()->variable != pssi()->variable)
			return(1);
	}
	if (!psi.done() || !pssi.done())
		return(1);
	else
		return(0);
}

int
Substitutions::operator<(const Substitutions &s) const
{
	ListIterator<Substitution *> psi(*psubs);
	ListIterator<Substitution *> pssi(*s.psubs);
	for ( ; !psi.done() && !pssi.done(); psi++, pssi++)
	{
		if (psi()->variable < pssi()->variable)
			return(1);
		else if (psi()->variable > pssi()->variable)
			return(0);
	}
	if (psi.done() && !pssi.done())
		return(1);
	else
		return(0);
}

int
Substitutions::operator>(const Substitutions &s) const
{
	ListIterator<Substitution *> psi(*psubs);
	ListIterator<Substitution *> pssi(*s.psubs);
	for ( ; !psi.done() && !pssi.done(); psi++, pssi++)
	{
		if (psi()->variable > pssi()->variable)
			return(1);
		else if (psi()->variable < pssi()->variable)
			return(0);
	}
	if (!psi.done() && pssi.done())
		return(1);
	else
		return(0);
}

int
Substitutions::operator<=(const Substitutions &s) const
{
	ListIterator<Substitution *> psi(*psubs);
	ListIterator<Substitution *> pssi(*s.psubs);
	for ( ; !psi.done() && !pssi.done(); psi++, pssi++)
	{
		if (psi()->variable < pssi()->variable)
			return(1);
		else if (psi()->variable > pssi()->variable)
			return(0);
	}
	if (psi.done() && !pssi.done())
		return(1);
	else if (psi.done() && pssi.done())
		return(1);
	else
		return(0);
}

int
Substitutions::operator>=(const Substitutions &s) const
{
	ListIterator<Substitution *> psi(*psubs);
	ListIterator<Substitution *> pssi(*s.psubs);
	for ( ; !psi.done() && !pssi.done(); psi++, pssi++)
	{
		if (psi()->variable > pssi()->variable)
			return(1);
		else if (psi()->variable < pssi()->variable)
			return(0);
	}
	if (!psi.done() && pssi.done())
		return(1);
	else if (psi.done() && pssi.done())
		return(1);
	else
		return(0);
}

// insert a substitution in the list
int
Substitutions::insert(const Substitution &s)
{
	Substitution *psub = new Substitution(s);
	MustBeTrue(psub != NULL);
	return(psubs->insertAtEnd(psub));
}

void
Substitutions::clear()
{
	// delete current data
	ListIterator<Substitution *> psubsIter(*psubs);
	for ( ; !psubsIter.done(); psubsIter++)
	{
		if (psubsIter() != NULL)
			delete psubsIter();
	}
	psubs->clear();
	return;
}

int
Substitutions::isEmpty() const
{
	return(psubs->isEmpty());
}

// compositions, combine two substitutions
Substitutions
Substitutions::operator*(const Substitutions &s) const
{
	// composition
	Substitutions composition;

	// iterators
	ListIterator<Substitution *> ti(*psubs);
	ListIterator<Substitution *> si(*s.psubs);

	// apply substitutions
	for ( ; !ti.done(); ti++)
	{
		Substitution newsub = *ti();
		for (si.reset(); !si.done(); si++)
		{
			newsub = newsub*(*si());
		}
		if (!newsub.isDegenerate())
		{
			MustBeTrue(composition.insert(newsub) == OK);
		}
	}

	// copy any substitutions not in the original
	for (si.reset(); !si.done(); si++)
	{
		int found = 0;
		for (ti.reset() ; !ti.done(); ti++)
		{
			if (ti()->variable == si()->variable)
			{
				found = 1;
				break;
			}
		}
		if (!found)
		{
			MustBeTrue(composition.insert(*si()) == OK);
		}
	}
	return(composition);
}

Substitutions
Substitutions::operator*(const Substitution &s) const
{
	// composition
	Substitutions composition;

	// iterators
	ListIterator<Substitution *> ti(*psubs);

	// apply substitutions
	for ( ; !ti.done(); ti++)
	{
		Substitution newsub = (*ti())*s;
		if (!newsub.isDegenerate())
		{
			MustBeTrue(composition.insert(newsub) == OK);
		}
	}

	// copy any substitutions not in the original
	int found = 0;
	for (ti.reset() ; !ti.done(); ti++)
	{
		if (ti()->variable == s.variable)
		{
			found = 1;
			break;
		}
	}
	if (!found)
	{
		MustBeTrue(composition.insert(s) == OK);
	}
	return(composition);
}

int
Substitutions::applyTo(Term &t) const
{
	ListIterator<Substitution *> psi(*psubs);
	for ( ; !psi.done(); psi++)
	{
		if (psi()->applyTo(t) != OK)
			return(NOTOK);
	}
	return(OK);
}

// check if variable is also the term
int
Substitution::isDegenerate() const
{
	if ((term.type == Term::Variable) &&
	    (term.value == variable))
		return(1);
	else
		return(0);
}

// print data
ostream &
operator<<(ostream &os, const Substitutions &s)
{
	if (s.psubs != NULL)
	{
		os << "{ ";
		ListIterator<Substitution *> psubsIter(*s.psubs);
		for ( ; !psubsIter.done(); psubsIter++)
		{
			if (psubsIter() != NULL)
				os << *psubsIter() << " , ";
		}
		os << " }";
	}
	return(os);
}


text:
<?php

namespace ZendPdf\Exception;

/**
 * Exception class for Zend\Pdf.
 *
 * @category  Zend
 * @package    Zend_PDF
 * @subpackage Zend_PDF_Exception
 */
class CorruptedImageException extends RuntimeException
{
}


text:
Radio_Project
=============

This project is making additional accessory to portable radio

We created accessories for a portable radio which already has many functions such as hand crank generator, solar cells, radio, flash light, USB 5V out, and mini USB, and audio jack.
This project was our attempt to address culture of over accessorized and multifunctional electronics. We used USB connection as starting point of exploration of accessory because of its ubiquity.
We created utensils to expand functionality but turn radio into accessory, and digger shovel and hard hat for comical simulation for large construction machinery operation changing context to radio into toy.
Function of radio changes in relation to sets of accessories. personalization.


text:
namespace http {
namespace server4 {

struct request;

/// Parser for incoming requests.
class request_parser : boost::asio::coroutine
{
public:
  /// Parse some data. The tribool return value is true when a complete request
  /// has been parsed, false if the data is invalid, indeterminate when more
  /// data is required. The InputIterator return value indicates how much of the
  /// input has been consumed.
  template <typename InputIterator>
  boost::tuple<boost::tribool, InputIterator> parse(request& req,
      InputIterator begin, InputIterator end)
  {
    while (begin != end)
    {
      boost::tribool result = consume(req, *begin++);
      if (result || !result)
        return boost::make_tuple(result, begin);
    }
    boost::tribool result = boost::indeterminate;
    return boost::make_tuple(result, begin);
  }

private:
  /// The name of the content length header.
  static std::string content_length_name_;

  /// Content length as decoded from headers. Defaults to 0.
  std::size_t content_length_;

  /// Handle the next character of input.
  boost::tribool consume(request& req, char input);

  /// Check if a byte is an HTTP character.
  static bool is_char(int c);

  /// Check if a byte is an HTTP control character.
  static bool is_ctl(int c);

  /// Check if a byte is defined as an HTTP tspecial character.
  static bool is_tspecial(int c);

  /// Check if a byte is a digit.
  static bool is_digit(int c);

  /// Check if two characters are equal, without regard to case.
  static bool tolower_compare(char a, char b);

  /// Check whether the two request header names match.
  bool headers_equal(const std::string& a, const std::string& b);
};

} // namespace server4
} // namespace http

#endif // HTTP_SERVER4_REQUEST_PARSER_HPP


text:
namespace ceres {
namespace internal {

template class PartitionedMatrixView<4, 4, Eigen::Dynamic>;

}  // namespace internal
}  // namespace ceres

#endif  // CERES_RESTRICT_SCHUR_SPECIALIZATION


text:
  {% assign words = content | number_of_words %}
  {% if words < 360 %}
    1 min
  {% else %}
    {{ words | divided_by:180 }} mins
  {% endif %}


text:
package com.intellij.debugger.memory.agent;

import com.intellij.debugger.engine.DebugProcess;
import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;

final class MemoryAgentInitializer {
  private static final Key<MemoryAgent> MEMORY_AGENT_KEY = Key.create("MEMORY_AGENT_KEY");
  private static final Logger LOG = Logger.getInstance(MemoryAgentInitializer.class);

  @NotNull
  static MemoryAgent getAgent(@NotNull EvaluationContextImpl evaluationContext) {
    MemoryAgent agent = evaluationContext.getDebugProcess().getUserData(MEMORY_AGENT_KEY);
    return agent == null ? initializeAgent(evaluationContext) : agent;
  }

  static boolean isAgentLoaded(@NotNull DebugProcess debugProcess) {
    MemoryAgent memoryAgent = debugProcess.getUserData(MEMORY_AGENT_KEY);
    return memoryAgent != null && !memoryAgent.isDisabled();
  }

  static MemoryAgent initializeAgent(@NotNull EvaluationContextImpl evaluationContext) {
    DebuggerManagerThreadImpl.assertIsManagerThread();
    MemoryAgent agent = MemoryAgentImpl.DISABLED;

    try {
      agent = MemoryAgentImpl.createMemoryAgent(evaluationContext);
    }
    catch (EvaluateException e) {
      LOG.error("Could not initialize memory agent. ", e);
    }
    evaluationContext.getDebugProcess().putUserData(MEMORY_AGENT_KEY, agent);
    return agent;
  }
}


text:
package gov.nih.nci.codegen.core.util;
import gov.nih.nci.common.util.Constant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.apache.log4j.Logger;

/**
 * @author caBIO Team
 * @version 1.0
 */
public class LicenseUpdater {

	private static Logger logger = Logger.getLogger(LicenseUpdater.class);

	private String _beginPattern;

	private String _endPattern;

	private String _outputDirName;

	private String _text;

	private String _logFileName;

	private Collection _files = new ArrayList();

	private FileWriter _log;

	/**
	 *
	 */
	public LicenseUpdater() {
		super();

	}

	public void setBeginPattern(String p_beginPattern) {
		_beginPattern = p_beginPattern;
	}

	public String getBeginPattern() {
		return _beginPattern;
	}

	public void setEndPattern(String p_endPattern) {
		_endPattern = p_endPattern;
	}

	public String getEndPattern() {
		return _endPattern;
	}

	public void setOutputDirName(String p_outputDirName) {
		_outputDirName = p_outputDirName;
	}

	public String getOutputDirName() {
		return _outputDirName;
	}

	public void setLogFileName(String p_logFileName) {
		_logFileName = p_logFileName;
	}

	public String getLogFileName() {
		return _logFileName;
	}

	public Collection getFiles() {
		return _files;
	}

	public void setText(String p_text) {
		_text = p_text;
	}

	public String getText() {
		return _text;
	}

	public void validate() throws IllegalStateException {
		if (_beginPattern == null) {
			logger.error("beginPattern not set");
			throw new IllegalStateException("beginPattern not set");
		}
		if (_endPattern == null) {
			logger.error("endPattern not set");
			throw new IllegalStateException("endPattern not set");
		}
		if (_text == null) {
			logger.error("text not set");
			throw new IllegalStateException("text not set");
		}
	}

	private void init() throws Exception {
		validate();
		if (_logFileName != null) {
			File f = new File(_logFileName);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}
			_log = new FileWriter(new File(_logFileName));
		}
	}

	public void run() throws Exception {
		init();
		log("Processing " + _files.size() + " files...");
		for (Iterator i = _files.iterator(); i.hasNext();) {
			File f = (File) i.next();
			int beginLineNum = getLineNumber(f, getBeginPattern());
			int endLineNum = getLineNumber(f, getEndPattern());
			if (beginLineNum < 0) {
				log("No begin pattern: " + f.getAbsolutePath());
			} else if (endLineNum < 0) {
				log("No end pattern: " + f.getAbsolutePath());
			} else {
				File outFile = getOutFile(f, getOutputDirName());
				insertText(f, outFile, beginLineNum, endLineNum, getText());
			}
		}
		log("...done");
	}

	/**
	 * @param f
	 * @param outputDirName
	 * @return
	 */
	private File getOutFile(File f, String outputDirName) {
		File outFile = null;
		if (outputDirName == null) {
			outFile = f;
		} else {
			String currDir = (new File(".")).getAbsolutePath();
			String relDir = f.getParentFile().getAbsolutePath().substring(
					currDir.length() - 1);
			outFile = new File(outputDirName + Constant.FORWARD_SLASH + relDir + Constant.FORWARD_SLASH + f.getName());
			if (!outFile.getParentFile().exists()) {
				outFile.getParentFile().mkdirs();
			}
		}
		return outFile;
	}

	/**
	 * @param endPattern
	 * @return
	 */
	private int getLineNumber(File inFile, String pattern) {
		boolean found = false;
		int lineNum = 1;
		try {
			BufferedReader br = new BufferedReader(new FileReader(inFile));
			String line = null;
			while ((line = br.readLine()) != null) {
				if (line.indexOf(pattern) > -1) {
					found = true;
					break;
				}
				lineNum++;
			}
			br.close();
		} catch (Exception ex) {
			logger.error("Error reading file" + ex.getMessage());
			throw new RuntimeException("Error reading file", ex);
		}
		if (!found) {
			lineNum = -1;
		}
		return lineNum;
	}

	/**
	 * @param f
	 * @param beginPattern
	 * @param endPattern
	 * @param text
	 */
	private void insertText(File inFile, File outFile, int beginLineNum,
			int endLineNum, String text) {
		StringBuffer sb = new StringBuffer();
		StringBuffer upToInc = getUpToIncluding(inFile, beginLineNum);
		StringBuffer afterInc = getAfterIncluding(inFile, endLineNum);

		sb.append(upToInc);
		sb.append(text);
		if(!text.endsWith("\n")){
			sb.append("\n");
		}
		sb.append(afterInc);
		try {
			FileWriter out = new FileWriter(outFile);
			out.write(sb.toString());
			out.flush();
			out.close();
		} catch (Exception ex) {
			logger.error("Error writing " + ex.getMessage());
			throw new RuntimeException("Error writing", ex);
		}
	}

	/**
	 * @param inFile
	 * @param endLineNum
	 * @return
	 */
	private StringBuffer getAfterIncluding(File inFile, int endLineNum) {
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new FileReader(inFile));
			String line = null;
			int lineNum = 1;
			while ((line = br.readLine()) != null) {
				if (lineNum >= endLineNum) {
					sb.append(line);
					sb.append("\n");
				}
				lineNum++;
			}
			br.close();
		} catch (Exception ex) {
			logger.error("Error reading file " + ex.getMessage());
			throw new RuntimeException("Error reading file", ex);
		}
		return sb;
	}

	/**
	 * @param inFile
	 * @param beginLineNum
	 * @return
	 */
	private StringBuffer getUpToIncluding(File inFile, int beginLineNum) {
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new FileReader(inFile));
			String line = null;
			int lineNum = 1;
			while ((line = br.readLine()) != null && lineNum <= beginLineNum) {
				sb.append(line);
				sb.append("\n");
				lineNum++;
			}
			br.close();
		} catch (Exception ex) {
			logger.error("Error reading file "+ ex.getMessage());
			throw new RuntimeException("Error reading file", ex);
		}
		return sb;
	}

	private void log(String msg) {
		if (_log != null) {
			try {
				_log.write(msg + "\n");
				_log.flush();
			} catch (IOException e) {
				logger.error("IOException: ", e);
			}

		} else {
			logger.error("_log is null");
		}
	}

	public void finalize() {
		if (_log != null) {
			try {
				_log.close();
			} catch (IOException e) {
				logger.error("IOExcepiont: ", e);
			}
		}
	}

	public static void main(String[] args) {
		try {
			LicenseUpdater lu = new LicenseUpdater();
			lu.setBeginPattern(args[0]);
			lu.setEndPattern(args[1]);
			lu.setOutputDirName(args[2]);
			lu.setText(args[3]);
			lu.setLogFileName(args[4]);
			lu.getFiles().add(new File(args[5]));
			lu.run();

		} catch (Exception ex) {
			logger.error("Exception: ", ex);
		}

	}
}


text:
----------------------------------------------------------
-- Load RayUI Environment
----------------------------------------------------------
RayUI:LoadEnv("MiniMap")

local MM = R:NewModule("MiniMap", "AceEvent-3.0", "AceHook-3.0")

MM.modName = L["小地图"]
_MiniMap = MM

local function MiniMapTrackingDropDown_Initialize(self, level)
    local name, texture, active, category, nested, numTracking;
    local count = GetNumTrackingTypes();
    local info;
    local _, class = UnitClass("player");

    if (level == 1) then
        info = Lib_UIDropDownMenu_CreateInfo();
        info.text=MINIMAP_TRACKING_NONE;
        info.checked = MiniMapTrackingDropDown_IsNoTrackingActive;
        info.func = ClearAllTracking;
        info.icon = nil;
        info.arg1 = nil;
        info.isNotRadio = true;
        info.keepShownOnClick = true;
        Lib_UIDropDownMenu_AddButton(info, level);

        if (class == "HUNTER") then --only show hunter dropdown for hunters
            numTracking = 0;
            -- make sure there are at least two options in dropdown
            for id=1, count do
                name, texture, active, category, nested = GetTrackingInfo(id);
                if (nested == _G.HUNTER_TRACKING and category == "spell") then
                    numTracking = numTracking + 1;
                end
            end
            if (numTracking > 1) then
                info.text = _G.HUNTER_TRACKING_TEXT;
                info.func = nil;
                info.notCheckable = true;
                info.keepShownOnClick = false;
                info.hasArrow = true;
                info.value = _G.HUNTER_TRACKING;
                Lib_UIDropDownMenu_AddButton(info, level)
            end
        end

        info.text = _G.TOWNSFOLK_TRACKING_TEXT;
        info.func = nil;
        info.notCheckable = true;
        info.keepShownOnClick = false;
        info.hasArrow = true;
        info.value = _G.TOWNSFOLK;
        Lib_UIDropDownMenu_AddButton(info, level)
    end
    for id=1, count do
        name, texture, active, category, nested = GetTrackingInfo(id);
        info = Lib_UIDropDownMenu_CreateInfo();
        info.text = name;
        info.checked = MiniMapTrackingDropDownButton_IsActive;
        info.func = MiniMapTracking_SetTracking;
        info.icon = texture;
        info.arg1 = id;
        info.isNotRadio = true;
        info.keepShownOnClick = true;
        if ( category == "spell" ) then
            info.tCoordLeft = 0.0625;
            info.tCoordRight = 0.9;
            info.tCoordTop = 0.0625;
            info.tCoordBottom = 0.9;
        else
            info.tCoordLeft = 0;
            info.tCoordRight = 1;
            info.tCoordTop = 0;
            info.tCoordBottom = 1;
        end
        if (level == 1 and
            (nested < 0 or -- this tracking shouldn't be nested
                (nested == _G.HUNTER_TRACKING and class ~= "HUNTER") or
                (numTracking == 1 and category == "spell"))) then -- this is a hunter tracking ability, but you only have one
            Lib_UIDropDownMenu_AddButton(info, level);
        elseif (level == 2 and (nested == _G.TOWNSFOLK or (nested == _G.HUNTER_TRACKING and class == "HUNTER")) and nested == _G.LIB_UIDROPDOWNMENU_MENU_VALUE) then
            Lib_UIDropDownMenu_AddButton(info, level);
        end
    end
end
local RayUI_MinimapTrackDropDown = CreateFrame("Frame", "RayUI_MinimapTrackDropDown", UIParent, "Lib_UIDropDownMenuTemplate")
RayUI_MinimapTrackDropDown:SetID(1)
RayUI_MinimapTrackDropDown:SetClampedToScreen(true)
RayUI_MinimapTrackDropDown:Hide()
Lib_UIDropDownMenu_Initialize(RayUI_MinimapTrackDropDown, MiniMapTrackingDropDown_Initialize, "MENU");
RayUI_MinimapTrackDropDown.noResize = true

local menuFrame = CreateFrame("Frame", "RayUI_MinimapRightClickMenu", R.UIParent)
local menuList = {
    {text = CHARACTER_BUTTON,
        func = function() ToggleCharacter("PaperDollFrame") end},
    {text = SPELLBOOK_ABILITIES_BUTTON,
        func = function() if not SpellBookFrame:IsShown() then ShowUIPanel(SpellBookFrame) else HideUIPanel(SpellBookFrame) end end},
    {text = TALENTS_BUTTON,
        func = function()
            if not PlayerTalentFrame then
                TalentFrame_LoadUI()
            end

            if not PlayerTalentFrame:IsShown() then
                ShowUIPanel(PlayerTalentFrame)
            else
                HideUIPanel(PlayerTalentFrame)
            end
        end
    },
    {text = ACHIEVEMENT_BUTTON,
        func = function() ToggleAchievementFrame() end},
    {text = SOCIAL_BUTTON,
        func = function() ToggleFriendsFrame() end},
    {text = ACHIEVEMENTS_GUILD_TAB,
        func = function() ToggleGuildFrame() end},
    {text = ENCOUNTER_JOURNAL,
        func = function() if not IsAddOnLoaded("Blizzard_EncounterJournal") then EncounterJournal_LoadUI() end ToggleFrame(EncounterJournal) end},
    {text = COLLECTIONS,
        func = function() ToggleCollectionsJournal() end},
    {text = LFG_TITLE,
        func = function() ToggleLFDParentFrame() end},
    {text = BLIZZARD_STORE,
        func = function() StoreMicroButton:Click() end},
    {text = HELP_BUTTON,
        func = function() ToggleHelpFrame() end},
    {text = GARRISON_LANDING_PAGE_TITLE,
        func = function() GarrisonLandingPageMinimapButton_OnClick() end},
    {text = CALENDAR,
        func = function() GameTimeFrame:Click() end},
    {text = LOOT_ROLLS,
        func = function() ToggleFrame(LootHistoryFrame) end},
}

function MM:TimeManagerClockButton_UpdateTooltip()
    GameTooltip:SetOwner(Minimap, "ANCHOR_BOTTOMRIGHT", 5, 142)
    GameTooltip:ClearLines()

    if ( TimeManagerClockButton.alarmFiring ) then
        if ( gsub(Settings.alarmMessage, "%s", "") ~= "" ) then
            GameTooltip:AddLine(Settings.alarmMessage, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b, 1)
            GameTooltip:AddLine(" ")
        end
        GameTooltip:AddLine(TIMEMANAGER_ALARM_TOOLTIP_TURN_OFF)
    else
        GameTime_UpdateTooltip()
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine(GAMETIME_TOOLTIP_TOGGLE_CLOCK)
    end
    GameTooltip:Show()
end

local function PositionGarrisonButton(self, screenQuadrant)
    GarrisonLandingPageMinimapButton:SetScale(0.7)
    screenQuadrant = screenQuadrant or R:GetScreenQuadrant(self)
    if strfind(screenQuadrant, "RIGHT") then
        GarrisonLandingPageMinimapButton:ClearAllPoints()
        GarrisonLandingPageMinimapButton:SetPoint("TOPLEFT", Minimap, "TOPLEFT", -100, 10)
    else
        GarrisonLandingPageMinimapButton:ClearAllPoints()
        GarrisonLandingPageMinimapButton:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", 100, 10)
    end
end

function MM:SkinMiniMap()
    local frames = {
        "GameTimeFrame",
        "MinimapBorderTop",
        "MinimapNorthTag",
        "MinimapBorder",
        "MinimapZoneTextButton",
        "MinimapZoomOut",
        "MinimapZoomIn",
        "MiniMapVoiceChatFrame",
        "MiniMapWorldMapButton",
        "MiniMapMailBorder",
    }
    for i in pairs(frames) do
        _G[frames[i]]:Kill()
    end
    Minimap:Size(175, 175)
    Minimap:CreateShadow("Background", nil, true)
    Minimap:SetPlayerTexture("Interface\\AddOns\\RayUI\\media\\MinimapArrow")
    Minimap.shadow:SetBackdrop( {
            edgeFile = R["media"].glow,
            bgFile = R["media"].blank,
            edgeSize = R:Scale(4),
            tile = false,
            tileSize = 0,
            insets = {left = R:Scale(4), right = R:Scale(4), top = R:Scale(4), bottom = R:Scale(4)},
        })
    MinimapCluster:EnableMouse(false)
    MiniMapTracking:Hide()
    MiniMapMailFrame:ClearAllPoints()
    MiniMapMailFrame:SetPoint("BOTTOMRIGHT", Minimap, "BOTTOMRIGHT", 2, -6)
    MiniMapMailIcon:SetTexture("Interface\\AddOns\\RayUI\\media\\mail")
    GameTimeCalendarInvitesTexture:ClearAllPoints()
    GameTimeCalendarInvitesTexture:SetParent(Minimap)
    GameTimeCalendarInvitesTexture:SetPoint("TOPRIGHT")
    if FeedbackUIButton then
        FeedbackUIButton:Kill()
    end
    if StreamingIcon then
        StreamingIcon:ClearAllPoints()
        StreamingIcon:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", 8, 8)
        StreamingIcon:SetScale(0.8)
    end
    function GetMinimapShape()
        return "SQUARE"
    end
    Minimap:SetMaskTexture("Interface\\Buttons\\WHITE8X8")
    local zoneTextFrame = CreateFrame("Frame", nil, R.UIParent)
    zoneTextFrame:SetPoint("TOPLEFT", Minimap, "TOPLEFT", 0, 10)
    zoneTextFrame:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", 0, 10)
    zoneTextFrame:SetHeight(19)
    zoneTextFrame:SetAlpha(0)
    MinimapZoneText:SetParent(zoneTextFrame)
    MinimapZoneText:ClearAllPoints()
    MinimapZoneText:SetPoint("LEFT", 2, 1)
    MinimapZoneText:SetPoint("RIGHT", -2, 1)
    MinimapZoneText:SetFont(R["media"].font, R["media"].fontsize, R["media"].fontflag)
    Minimap:HookScript("OnEnter", function(self)
            UIFrameFadeIn(zoneTextFrame, 0.3, zoneTextFrame:GetAlpha(), 1)
        end)
    Minimap:HookScript("OnLeave", function(self)
            UIFrameFadeOut(zoneTextFrame, 0.3, zoneTextFrame:GetAlpha(), 0)
        end)
    DropDownList1:SetClampedToScreen(true)
    LFGDungeonReadyStatus:SetClampedToScreen(true)
    HelpOpenTicketButton:SetParent(Minimap)
    HelpOpenTicketButton:ClearAllPoints()
    HelpOpenTicketButton:SetPoint("BOTTOMRIGHT", Minimap, "BOTTOMRIGHT")
end

function MM:CheckMail()
    local inv = CalendarGetNumPendingInvites()
    local mail = MiniMapMailFrame:IsShown() and true or false
    if inv > 0 and mail then -- New invites and mail
        Minimap.shadow:SetBackdropBorderColor(1, .5, 0)
        R.Skins:CreatePulse(Minimap.shadow, 1, 1)
    elseif inv > 0 and not mail then -- New invites and no mail
        Minimap.shadow:SetBackdropBorderColor(1, 30/255, 60/255)
        R.Skins:CreatePulse(Minimap.shadow, 1, 1)
    elseif inv==0 and mail then -- No invites and new mail
        Minimap.shadow:SetBackdropBorderColor(.5, 1, 1)
        R.Skins:CreatePulse(Minimap.shadow, 1, 1)
    else -- None of the above
        Minimap.shadow:SetScript("OnUpdate", nil)
        if not R.PixelMode then
            Minimap.shadow:SetAlpha(1)
        else
            Minimap.shadow:SetAlpha(0)
        end
        Minimap.shadow:SetBackdropBorderColor(unpack(R["media"].bordercolor))
    end
end

function MM:ADDON_LOADED(event, addon)
    if addon == "Blizzard_TimeManager" then
        self:UnregisterEvent(event)
        if ( not BlizzardStopwatchOptions ) then
            BlizzardStopwatchOptions = {}
        end

        if ( BlizzardStopwatchOptions.position ) then
            StopwatchFrame:ClearAllPoints()
            StopwatchFrame:SetPoint("CENTER", R.UIParent, "BOTTOMLEFT", BlizzardStopwatchOptions.position.x, BlizzardStopwatchOptions.position.y)
            StopwatchFrame:SetUserPlaced(true)
        else
            StopwatchFrame:SetPoint("TOPRIGHT", R.UIParent, "TOPRIGHT", -250, -300)
        end
        self:RawHook("TimeManagerClockButton_UpdateTooltip", true)

        local clockFrame, clockTime = TimeManagerClockButton:GetRegions()
        clockFrame:Hide()
        clockTime:SetFont(R["media"].font, R["media"].fontsize, R["media"].fontflag)
        clockTime:SetTextColor(1,1,1)
        TimeManagerClockButton:SetPoint("BOTTOM", Minimap, "BOTTOM", 0, -3)
        TimeManagerClockButton:SetScript("OnClick", function(_,btn)
                if btn == "LeftButton" then
                    ToggleFrame(TimeManagerFrame)
                end
                if btn == "RightButton" then
                    GameTimeFrame:Click()
                end
            end)
    end
end

function MM:Minimap_OnMouseUp(btn)
    local position = self:GetPoint()
    if btn == "MiddleButton" or (btn == "RightButton" and IsShiftKeyDown()) then
        if position:match("LEFT") then
            R:DropDown(menuList, menuFrame)
        else
            R:DropDown(menuList, menuFrame, -160, 0)
        end
    elseif btn == "RightButton" then
        Lib_ToggleDropDownMenu(1, nil, RayUI_MinimapTrackDropDown, "cursor")
    else
        Minimap_OnClick(self)
    end
end

function MM:CreateMenu()
    Minimap:SetScript("OnMouseUp", MM.Minimap_OnMouseUp)
    R.Skins:CreateBD(menuFrame)
    R.Skins:CreateStripesThin(menuFrame)
end

function MM:Info()
    return L["|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r小地图模块."]
end

local function MinimapPostDrag(self, screenQuadrant)
    MM:PositionButtonCollector(self, screenQuadrant)
    PositionGarrisonButton(self, screenQuadrant)
    if screenQuadrant == "TOPLEFT" then
        UIParent:SetAttribute("LEFT_OFFSET", MinimapButtonCollectFrame:GetLeft() + MinimapButtonCollectFrame:GetWidth() + 5)
    else
        UIParent:SetAttribute("LEFT_OFFSET", 16)
    end
end

function MM:Minimap_OnMouseWheel(d)
    if d > 0 then
        MinimapZoomIn:Click()
    elseif d < 0 then
        MinimapZoomOut:Click()
    end
end

function MM:Initialize()
    self:SkinMiniMap()
    self:CreateMenu()
    self:ButtonCollector()

    Minimap:ClearAllPoints()
    Minimap:Point("TOPLEFT", R.UIParent, "TOPLEFT", 10, -20)
    Minimap:SetFrameLevel(10)
    Minimap:EnableMouseWheel(true)
    Minimap:SetScript("OnMouseWheel", MM.Minimap_OnMouseWheel)

    self:RegisterEvent("ADDON_LOADED")
    self:RegisterEvent("CALENDAR_UPDATE_PENDING_INVITES", "CheckMail")
    self:RegisterEvent("UPDATE_PENDING_MAIL", "CheckMail")
    self:RegisterEvent("PLAYER_ENTERING_WORLD", "CheckMail")
    self:HookScript(MiniMapMailFrame, "OnHide", "CheckMail")
    self:HookScript(MiniMapMailFrame, "OnShow", "CheckMail")

    R:CreateMover(Minimap, "MinimapMover", L["小地图锚点"], true, MinimapPostDrag)
end

R:RegisterModule(MM:GetName())

-----------------------------------------------------------
-- 转载自NGA,[小玩意儿][6.0+] 小地图副本难度标示. (小旗子再见) ,by sakaras
-- Say thanks: FreeUI , 斬擊 , nannan828 , 水月 , liubingchen3
-----------------------------------------------------------
MiniMapInstanceDifficulty:Hide()
MiniMapInstanceDifficulty.Show = function() return end

GuildInstanceDifficulty:Hide()
GuildInstanceDifficulty.Show = function() return end

local function CreateFS(parent, size, justify)
    local f = parent:CreateFontString(nil, "OVERLAY")
    f:SetFont(GameFontNormal:GetFont(), 16, "OUTLINE")
    f:SetShadowColor(0, 0, 0, 0)

    if justify then f:SetJustifyH(justify) end

    return f
end

local rd = CreateFrame("Frame", nil, Minimap)
rd:SetSize(24, 8)
rd:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", -2, -2)
rd:RegisterEvent("PLAYER_ENTERING_WORLD")
rd:RegisterEvent("PLAYER_DIFFICULTY_CHANGED")
rd:RegisterEvent("GUILD_PARTY_STATE_UPDATED")
rd:RegisterEvent("INSTANCE_GROUP_SIZE_CHANGED")

local rdt = CreateFS(rd, R["media"].fontsize, "RIGHT")
rdt:SetPoint("TOPRIGHT")

local instanceTexts = {
    [0] = "",
    [1] = "5",
    [2] = "5H",
    [3] = "10",
    [4] = "25",
    [5] = "10H",
    [6] = "25H",
    [7] = "RF",
    [8] = "C",
    [9] = "40",
    [11] = "HB",
    [12] = "B",
    [16] = "M",
    [23] = "5M",    -- Mythic 5-player
    [24] = "TW",    -- Timewalker 5-player
}

rd:SetScript("OnEvent", function()
    local inInstance, instanceType = IsInInstance()
    local _, _, difficultyID, _, maxPlayers, _, _, _, instanceGroupSize = GetInstanceInfo()

    if instanceTexts[difficultyID] ~= nil then
        rdt:SetText(instanceTexts[difficultyID])
    else
        if difficultyID == 14 then
            rdt:SetText(instanceGroupSize.."N")
        elseif difficultyID == 15 then
            rdt:SetText(instanceGroupSize.."H")
        elseif difficultyID == 17 then
            rdt:SetText(instanceGroupSize.."RF")
        else
            rdt:SetText("")
        end
    end

    rd:SetShown(inInstance and (instanceType == "party" or instanceType == "raid" or instanceType == "scenario"))

    if GuildInstanceDifficulty:IsShown() then
        rdt:SetTextColor(0, .9, 0)
    else
        rdt:SetTextColor(1, 1, 1)
    end
end)


text:
package urlpath

import (
	"errors"
	"os"
	"strings"
)

// A lazybuf is a lazily constructed path buffer.
// It supports append, reading previously appended bytes,
// and retrieving the final string. It does not allocate a buffer
// to hold the output until that output diverges from s.
type lazybuf struct {
	path       string
	buf        []byte
	w          int
	volAndPath string
	volLen     int
}

func (b *lazybuf) index(i int) byte {
	if b.buf != nil {
		return b.buf[i]
	}
	return b.path[i]
}

func (b *lazybuf) append(c byte) {
	if b.buf == nil {
		if b.w < len(b.path) && b.path[b.w] == c {
			b.w++
			return
		}
		b.buf = make([]byte, len(b.path))
		copy(b.buf, b.path[:b.w])
	}
	b.buf[b.w] = c
	b.w++
}

func (b *lazybuf) string() string {
	if b.buf == nil {
		return b.volAndPath[:b.volLen+b.w]
	}
	return b.volAndPath[:b.volLen] + string(b.buf[:b.w])
}

const (
	Separator = '/'
)

// Clean returns the shortest path name equivalent to path
// by purely lexical processing. It applies the following rules
// iteratively until no further processing can be done:
//
//	1. Replace multiple Separator elements with a single one.
//	2. Eliminate each . path name element (the current directory).
//	3. Eliminate each inner .. path name element (the parent directory)
//	   along with the non-.. element that precedes it.
//	4. Eliminate .. elements that begin a rooted path:
//	   that is, replace "/.." by "/" at the beginning of a path,
//	   assuming Separator is '/'.
//
// The returned path ends in a slash only if it represents a root directory,
// such as "/" on Unix or `C:\` on Windows.
//
// If the result of this process is an empty string, Clean
// returns the string ".".
//
// See also Rob Pike, ``Lexical File Names in Plan 9 or
// Getting Dot-Dot Right,''
// https://9p.io/sys/doc/lexnames.html
func Clean(path string) string {
	originalPath := path
	if path == "" {
		return originalPath + "."
	}
	// rooted := os.IsPathSeparator(path[0])
	rooted := path[0] == '/'

	// Invariants:
	//	reading from path; r is index of next byte to process.
	//	writing to buf; w is index of next byte to write.
	//	dotdot is index in buf where .. must stop, either because
	//		it is the leading slash or it is a leading ../../.. prefix.
	n := len(path)
	out := lazybuf{path: path, volAndPath: originalPath, volLen: 0}
	r, dotdot := 0, 0
	if rooted {
		out.append(Separator)
		r, dotdot = 1, 1
	}

	for r < n {
		switch {
		// case os.IsPathSeparator(path[r]):
		case path[r] == '/':
			// empty path element
			r++
		// case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])):
		case path[r] == '.' && (r+1 == n || path[r+1] == '/'):
			// . element
			r++
		// case path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])):
		case path[r] == '.' && path[r+1] == '.' && (r+2 == n || path[r+2] == '/'):
			// .. element: remove to last separator
			r += 2
			switch {
			case out.w > dotdot:
				// can backtrack
				out.w--
				// for out.w > dotdot && !os.IsPathSeparator(out.index(out.w)) {
				for out.w > dotdot && !(out.index(out.w) == '/') {
					out.w--
				}
			case !rooted:
				// cannot backtrack, but not rooted, so append .. element.
				if out.w > 0 {
					out.append(Separator)
				}
				out.append('.')
				out.append('.')
				dotdot = out.w
			}
		default:
			// real path element.
			// add slash if needed
			if rooted && out.w != 1 || !rooted && out.w != 0 {
				out.append(Separator)
			}
			// copy element
			// for ; r < n && !os.IsPathSeparator(path[r]); r++ {
			for ; r < n && !(path[r] == '/'); r++ {
				out.append(path[r])
			}
		}
	}

	// Turn empty string into "."
	if out.w == 0 {
		out.append('.')
	}

	return out.string()
}

// Split splits path immediately following the final Separator,
// separating it into a directory and file name component.
// If there is no Separator in path, Split returns an empty dir
// and file set to path.
// The returned values have the property that path = dir+file.
func Split(path string) (dir, file string) {
	vol := VolumeName(path)
	i := len(path) - 1
	// for i >= len(vol) && !os.IsPathSeparator(path[i]) {
	for i >= len(vol) && !(path[i] == '/') {
		i--
	}
	return path[:i+1], path[i+1:]
}

// Join joins any number of path elements into a single path, adding
// a Separator if necessary. The result is Cleaned, in particular
// all empty strings are ignored.
// On Windows, the result is a UNC path if and only if the first path
// element is a UNC path.
func Join(elem ...string) string {
	return join(elem)
}

// Ext returns the file name extension used by path.
// The extension is the suffix beginning at the final dot
// in the final element of path; it is empty if there is
// no dot.
func Ext(path string) string {
	// for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- {
	for i := len(path) - 1; i >= 0 && !(path[i] == '/'); i-- {
		if path[i] == '.' {
			return path[i:]
		}
	}
	return ""
}

// Abs returns an absolute representation of path.
// If the path is not absolute it will be joined with the current
// working directory to turn it into an absolute path. The absolute
// path name for a given file is not guaranteed to be unique.
func Abs(path string) (string, error) {
	return abs(path)
}

func unixAbs(path string) (string, error) {
	if IsAbs(path) {
		return Clean(path), nil
	}
	wd, err := os.Getwd()
	if err != nil {
		return "", err
	}
	return Join(wd, path), nil
}

// Rel returns a relative path that is lexically equivalent to targpath when
// joined to basepath with an intervening separator. That is,
// Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
// On success, the returned path will always be relative to basepath,
// even if basepath and targpath share no elements.
// An error is returned if targpath can't be made relative to basepath or if
// knowing the current working directory would be necessary to compute it.
func Rel(basepath, targpath string) (string, error) {
	baseVol := VolumeName(basepath)
	targVol := VolumeName(targpath)
	base := Clean(basepath)
	targ := Clean(targpath)
	if sameWord(targ, base) {
		return ".", nil
	}
	base = base[len(baseVol):]
	targ = targ[len(targVol):]
	if base == "." {
		base = ""
	}
	// Can't use IsAbs - `\a` and `a` are both relative in Windows.
	baseSlashed := len(base) > 0 && base[0] == Separator
	targSlashed := len(targ) > 0 && targ[0] == Separator
	if baseSlashed != targSlashed || !sameWord(baseVol, targVol) {
		return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
	}
	// Position base[b0:bi] and targ[t0:ti] at the first differing elements.
	bl := len(base)
	tl := len(targ)
	var b0, bi, t0, ti int
	for {
		for bi < bl && base[bi] != Separator {
			bi++
		}
		for ti < tl && targ[ti] != Separator {
			ti++
		}
		if !sameWord(targ[t0:ti], base[b0:bi]) {
			break
		}
		if bi < bl {
			bi++
		}
		if ti < tl {
			ti++
		}
		b0 = bi
		t0 = ti
	}
	if base[b0:bi] == ".." {
		return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
	}
	if b0 != bl {
		// Base elements left. Must go up before going down.
		seps := strings.Count(base[b0:bl], string(Separator))
		size := 2 + seps*3
		if tl != t0 {
			size += 1 + tl - t0
		}
		buf := make([]byte, size)
		n := copy(buf, "..")
		for i := 0; i < seps; i++ {
			buf[n] = Separator
			copy(buf[n+1:], "..")
			n += 3
		}
		if t0 != tl {
			buf[n] = Separator
			copy(buf[n+1:], targ[t0:])
		}
		return string(buf), nil
	}
	return targ[t0:], nil
}

// Base returns the last element of path.
// Trailing path separators are removed before extracting the last element.
// If the path is empty, Base returns ".".
// If the path consists entirely of separators, Base returns a single separator.
func Base(path string) string {
	if path == "" {
		return "."
	}
	// Strip trailing slashes.
	// for len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) {
	for len(path) > 0 && path[len(path)-1] == '/' {
		path = path[0 : len(path)-1]
	}
	// Throw away volume name
	path = path[len(VolumeName(path)):]
	// Find the last element
	i := len(path) - 1
	for i >= 0 && !(path[i] == '/') {
		i--
	}
	if i >= 0 {
		path = path[i+1:]
	}
	// If empty now, it had only slashes.
	if path == "" {
		return string(Separator)
	}
	return path
}

// Dir returns all but the last element of path, typically the path's directory.
// After dropping the final element, the path is Cleaned and trailing
// slashes are removed.
// If the path is empty, Dir returns ".".
// If the path consists entirely of separators, Dir returns a single separator.
// The returned path does not end in a separator unless it is the root directory.
func Dir(path string) string {
	vol := VolumeName(path)
	i := len(path) - 1
	for i >= len(vol) && !(path[i] == '/') {
		i--
	}
	dir := Clean(path[len(vol) : i+1])
	return vol + dir
}

// VolumeName returns leading volume name.
// Given "C:\foo\bar" it returns "C:" on Windows.
// Given "\\host\share\foo" it returns "\\host\share".
// On other platforms it returns "".
func VolumeName(path string) string {
	return path[:volumeNameLen(path)]
}

// IsAbs reports whether the path is absolute.
func IsAbs(path string) bool {
	return strings.HasPrefix(path, "/")
}

// volumeNameLen returns length of the leading volume name on Windows.
// It returns 0 elsewhere.
func volumeNameLen(path string) int {
	return 0
}

// HasPrefix exists for historical compatibility and should not be used.
func HasPrefix(p, prefix string) bool {
	return strings.HasPrefix(p, prefix)
}

func splitList(path string) []string {
	if path == "" {
		return []string{}
	}
	return strings.Split(path, ";")
}

func abs(path string) (string, error) {
	return unixAbs(path)
}

func join(elem []string) string {
	// If there's a bug here, fix the logic in ./path_plan9.go too.
	for i, e := range elem {
		if e != "" {
			return Clean(strings.Join(elem[i:], string(Separator)))
		}
	}
	return ""
}

func sameWord(a, b string) bool {
	return a == b
}


text:
<?php
/**
 * Abstraction of WordPress roles and capabilities and how they apply to Loco
 * - Currently only one capability exists, proving full access "loco_admin"
 * - Any user with "manage_options" permission automatically inherits this permission
 * - A single custom role is added called "translator"
 */
class Loco_data_Permissions {

    /**
     * Polyfill for wp_roles which requires WP >= 4.3
     */
    private static function wp_roles(){
        global $wp_roles;
        if( ! isset($wp_roles) ){
            get_role('ping');
        }
        return $wp_roles;
    }

    /**
     * @return array<WP_Role>
     */
    public function getRoles(){
        $roles = self::wp_roles();
        // lazy create "translator" role
        if( ! $roles->get_role('translator') ){
            $roles->add_role( 'translator', 'Translator', array( 'loco_admin' => true ) );
        }
        return $roles->role_objects;
    }

    /**
     * Completely remove all Loco permissions, as if uninstalling
     * @return Loco_data_Permissions
     */
    public function remove(){
        /* @var $role WP_Role */
        foreach( $this->getRoles() as $role ){
            $role->remove_cap('loco_admin');
        }
        // we'll only remove our custom role if it has no capabilities
        // this avoids breaking other plugins that use it, or added it.
        if( $role = get_role('translator') ){
            if( ! $role->capabilities ){
                remove_role('translator');
            }
        }
        return $this;
    }

    /**
     * Reset to default: roles include no Loco capabilities unless they have manage_options or are custom "translator" role
     * @return Loco_data_Permissions
     */
    public function reset(){
        /* @var $role WP_Role */
        foreach( $this->getRoles() as $role ){
            if( $role->has_cap('manage_options') || 'translator' === $role->name ){
                $role->add_cap('loco_admin');
            }
            else {
                $role->remove_cap('loco_admin');
            }
        }
        return $this;
    }

    /**
     * Get translated WordPress role name
     */
    public function getRoleName( $id ){
        if( 'translator' === $id ){
            $label = _x( 'Translator', 'User role', 'loco' );
        }
        else {
            $names = self::wp_roles()->role_names;
            $label = isset($names[$id]) ? translate_user_role( $names[$id] ) : $id;
        }
        return $label;
    }

    /**
     * Populate permission settings from posted checkboxes
     * @return Loco_data_Permissions
     */
    public function populate( array $caps ){
        // drop all permissions before adding (cos checkboxes)
        $this->reset();
        $roles = $this->getRoles();
        foreach( $caps as $id => $checked ){
            if( isset($roles[$id]) ){
                $role = $roles[$id];
                foreach( array('loco_admin') as $cap ){
                    if( ! empty($checked[$cap]) && ! $role->has_cap($cap) ){
                        $role->add_cap($cap);
                    }
                }
            }
        }
        return $this;
    }

}


text:
class CreateOperations < ActiveRecord::Migration
  def change
    create_table :operations do |t|
      t.integer :device_property_id
      t.string :value
      t.string :status
      t.timestamps
    end
  end
end


text:
# include <cstring>
# include <set>
# include <cstddef>
# include "utest.hpp"
# include "gds-math-eval.h"
# include "gds/arithmetic_eval.h"

# include <iostream>

/**@file gds-math-eval.cpp
 * @brief GDS interpretator base level test.
 *
 * This file provides testing of some auxilliary basics in GDS evaluator.
 * */

static std::unordered_set<BinOpKey> _static_uniqSet;

extern "C" int
binop_key_is_unique( BinOpKey c ) {
    auto res = _static_uniqSet.insert(c);
    return res.second ? 1 : 0;
}

GOO_UT_BGN( GDS_MATH_EVAL, "GDS simple arithmetic evaluator" )

{
    {
        struct DataOffsets {
                const char * name;
                size_t offset, size; } arithOffsets[] = {
            # define set_offset_entry_table( code, cTypeName, gooName, gdsName )    \
                { # cTypeName,                                                      \
                  offsetof( ArithmeticConstant::ArithmeticValue, gooName ## Val ),  \
                  sizeof( cTypeName ) } ,
            for_all_atomic_datatypes( set_offset_entry_table )
            # undef set_offset_entry_table
        };
        char * bf;
        size_t bflen;
        FILE * of = ::open_memstream( &bf, &bflen );
        fprintf( of, "In whole %zu bytes:\n", sizeof(ArithmeticConstant::ArithmeticValue) );
        for( struct DataOffsets & entry : arithOffsets ) {
            fprintf(of, " %-10s  %3zu %3zu\n", entry.name, entry.offset, entry.size );
        }
        ::fclose(of);
        os << bf;
        free( bf );
    }

    int rc = goo_gds__check_codes_structures();
    _ASSERT( !rc, "Checking of arithmetic operations subtable code system failed #1: %d.", rc );
    os << "Code table test passed with rc = " << rc << std::endl;
    rc = goo_gds__check_simple_arithmetics_evaluation();
    _ASSERT( !rc, "Checking of arithmetic operations subtable code system failed #1: %d.", rc );
    os << "Simple evaluation test passed with rc = " << rc << std::endl;
}

GOO_UT_END( GDS_MATH_EVAL )


text:
define(function(require) {
    'use strict';

    var HideStartRule;
    var Rule = require('./jpm-base-rule');

    HideStartRule = Rule.extend({
        name: 'HideStart',
        match: function(cell) {
            if (cell.step.get('order') < 0 && cell.children.length < 1) {
                this.root = cell;
                this.items = [];
                return true;
            } else {
                this.root = null;
                this.items = [];
                return false;
            }
        },
        apply: function() {
            var context = this.context;
            var changed = false;
            if (this.root !== null) {
                changed = true;
                context.remove(this.root);
                this.root = null;
                this.items = [];
            }
            return changed;
        }
    });

    return HideStartRule;
});


text:
/**
 * Helper definition for the range-bounded-area helper
 */

import {path} from 'd3-path'
import curves from 'd3-shape'
import Ember from 'ember'
const {Helper, String: EmberString} = Ember

export function rangeBoundedArea ({smooth = 'basis'}) {
  return function ({chartState, points, xRange, yRange}) {
    const _path = path()

    if (points.length >= 2) {
      const curve = curves[EmberString.camelize(`curve-${smooth}`)](_path)
      curve.lineStart()
      points.forEach(point => {
        curve.point(point.x, point.y)
      })
      curve.lineEnd()

      const firstPoint = points[0]
      const lastPoint = points[points.length - 1]
      _path.lineTo(lastPoint.x, yRange[0])
      _path.lineTo(firstPoint.x, yRange[0])
      _path.lineTo(firstPoint.x, firstPoint.y)
    }

    return _path.toString()
  }
}

export default Helper.helper(rangeBoundedArea)


text:
<?php

$config['base_url'] = 'http://localhost/libelula.dev'; // Base URL including trailing slash (e.g. http://localhost/)

$config['default_controller'] = 'main'; // Default controller to load
$config['error_controller'] = 'error'; // Controller used for errors (e.g. 404, 500 etc)

$config['db_host'] = 'localhost'; // Database host (e.g. localhost)
$config['db_name'] = 'db_libelula'; // Database name
$config['db_username'] = 'root'; // Database username
$config['db_password'] = 'root'; // Database password

$config['static_dir'] = $config['base_url'] . "/static"; // localizacion de los archivos estaticos para las parginas.

?>


text:
#pragma once

#include "tinyxml.h"
#include "xpath_static.h"
#include <string>

class NNXML
{
public:
	NNXML( std::string path );
	NNXML( char *buf );
	NNXML();
	~NNXML();

	static NNXML* Create( std::string path );
	static NNXML* Create();
	static NNXML* CreateStream( char* buf );

	TiXmlString XPathToString( std::string xpath );
	TiXmlDocument *GetDoc() { return &m_Document; }
private:
	TiXmlDocument m_Document;

	bool m_LoadSuccess;
};


text:
package commands

import (
	"encoding/json"
	"fmt"
	"os"
	"regexp"
	"sort"
	"sync"
	"text/tabwriter"

	"github.com/daidokoro/qaz/log"
	"github.com/daidokoro/qaz/stacks"
	"github.com/daidokoro/qaz/utils"

	"github.com/spf13/cobra"
)

// output, export and parameters commands

var (
	// output command
	outputsCmd = &cobra.Command{
		Use:     "outputs [stack]",
		Short:   "Prints stack outputs",
		Example: "qaz outputs vpc subnets --config path/to/config",
		PreRun:  initialise,
		Run: func(cmd *cobra.Command, args []string) {
			var wg sync.WaitGroup
			if len(args) < 1 {
				fmt.Println("Please specify stack(s) to check, For details try --> qaz outputs --help")
				return
			}

			stks, err := Configure(run.cfgSource, run.cfgRaw)
			utils.HandleError(err)

			for _, s := range args {
				// check if stack exists
				if _, ok := stks.Get(s); !ok {
					utils.HandleError(fmt.Errorf("%s: does not Exist in Config", s))
				}

				wg.Add(1)
				go func(s string) {
					defer wg.Done()
					if err := stks.MustGet(s).Outputs(); err != nil {
						log.Error(err.Error())
						return
					}

					for _, i := range stks.MustGet(s).Output.Stacks {
						m, err := json.MarshalIndent(i.Outputs, "", "  ")
						if err != nil {
							log.Error(err.Error())
						}

						resp := regexp.MustCompile(OutputRegex).
							ReplaceAllStringFunc(string(m), func(s string) string {
								return log.ColorString(s, log.CYAN)
							})

						fmt.Println(resp)
					}
					return
				}(s)
			}
			wg.Wait()

		},
	}

	// export command
	exportsCmd = &cobra.Command{
		Use:     "exports",
		Short:   "Prints stack exports",
		Example: "qaz exports",
		PreRun:  initialise,
		Run: func(cmd *cobra.Command, args []string) {
			sess, err := GetSession()
			utils.HandleError(err)
			utils.HandleError(stacks.Exports(sess))
		},
	}

	// parameters command
	parametersCmd = &cobra.Command{
		Use:     "parameters [stack]",
		Short:   "Prints parameters of deployed stack",
		Example: "qaz parameters vpc subnets --config path/to/config",
		PreRun:  initialise,
		Run: func(cmd *cobra.Command, args []string) {
			var wg sync.WaitGroup
			if len(args) < 1 {
				fmt.Println("Please specify stack(s) to check, For details try --> qaz parameters --help")
				return
			}

			stks, err := Configure(run.cfgSource, run.cfgRaw)
			utils.HandleError(err)

			for _, s := range args {
				// check if stack exists
				if _, ok := stks.Get(s); !ok {
					utils.HandleError(fmt.Errorf("%s: does not Exist in Config", s))
				}

				wg.Add(1)
				go func(s string) {
					defer wg.Done()
					if err := stks.MustGet(s).Outputs(); err != nil {
						log.Error(err.Error())
						return
					}

					for _, stack := range stks.MustGet(s).Output.Stacks {

						w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, '.', 0)
						// sort parameters by key
						sort.Slice(stack.Parameters, func(i, j int) bool {
							return *stack.Parameters[i].ParameterKey < *stack.Parameters[j].ParameterKey
						})
						// iterate over deployed stack parameters
						for _, p := range stack.Parameters {
							fmt.Fprintf(w, "%s\t %s", log.ColorString(*p.ParameterKey, log.CYAN), *p.ParameterValue)
							// find corresponding parameter in local qaz config
							for _, pl := range stks.MustGet(s).Parameters {
								if *pl.ParameterKey == *p.ParameterKey {
									if *pl.ParameterValue != *p.ParameterValue {
										// explicitly log divergent local values
										fmt.Fprintf(w, " vs. %s", log.ColorString(*pl.ParameterValue, log.RED))
									}
								}
							}
							fmt.Fprint(w, "\n")
						}
						w.Flush()

					}
					return
				}(s)
			}
			wg.Wait()

		},
	}
)


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>CS171 - Lab 5</title>

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

	<link href='https://fonts.googleapis.com/css?family=Lato:400,300,400italic,700' rel='stylesheet' type='text/css'>

Coffee House Chains

A ranking of selected leading coffee house chains worldwide

		<form class="form-inline">

		    Group by
		    <select class="form-control" id="ranking-type">
				  <option value="stores">Stores worldwide</option>
				  <option value="revenue">Revenue in billion U.S. dollars</option>
				</select>

				<button type="button" class="btn btn-link" id="change-sorting"> Sort</button>

		</form>


text:
import time
from multiprocessing import Pool, Process
import pychemia

__author__ = 'Guillermo Avendano-Franco'

def cluster_worker(db_settings):
    while True:
        pcdb = pychemia.db.get_database(db_settings)
        population = pychemia.population.LJCluster(pcdb)

        entry = population.pcdb.db.pychemia_entries.find_one({'status.' + population.tag: True,
                                                              'status.lock': {'$exists': False},
                                                              'properties': {}}, {'_id': 1})
        if entry is not None:
            population.pcdb.lock(entry['_id'])
            structure, properties, energy = population.evaluate(entry['_id'])
            population.pcdb.update(entry['_id'], structure=structure, properties=properties)
            population.pcdb.unlock(entry['_id'])
        else:
            break

def cluster_evaluator(db_settings, nparal):
    pcdb = pychemia.db.get_database(db_settings)
    population = pychemia.population.LJCluster(pcdb)
    population.recover()
    print('Staring evaluator for %s' % population.name)
    while True:
        entry = population.pcdb.db.pychemia_entries.find_one({'status.' + population.tag: True,
                                                              'status.lock': {'$exists': False},
                                                              'properties': {}}, {'_id': 1})

        if entry is None:
            time.sleep(2)
            create_pool = False
        else:
            create_pool = True

        if create_pool:
            pool = Pool(processes=nparal)
            pool.map(cluster_worker, nparal * [db_settings])
            pool.close()
            pool.join()

def cluster_launcher(db_settings, nparal):
    p = Process(target=cluster_evaluator, args=(db_settings, nparal))
    p.start()
    return p