text:
package org.jitsi.impl.neomedia.transform.srtp;

import java.util.*;

import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.digests.*;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.macs.*;
import org.bouncycastle.crypto.params.*;
import org.jitsi.bccontrib.macs.*;
import org.jitsi.bccontrib.params.*;
import org.jitsi.impl.neomedia.*;

/**
 * SRTPCryptoContext class is the core class of SRTP implementation.
 * There can be multiple SRTP sources in one SRTP session. And each SRTP stream
 * has a corresponding SRTPCryptoContext object, identified by SSRC. In this
 * way, different sources can be protected independently.
 *
 * SRTPCryptoContext class acts as a manager class and maintains all the
 * information used in SRTP transformation. It is responsible for deriving
 * encryption keys / salting keys / authentication keys from master keys. And
 * it will invoke certain class to encrypt / decrypt (transform / reverse
 * transform) RTP packets. It will hold a replay check db and do replay check
 * against incoming packets.
 *
 * Refer to section 3.2 in RFC3711 for detailed description of cryptographic
 * context.
 *
 * Cryptographic related parameters, i.e. encryption mode / authentication mode,
 * master encryption key and master salt key are determined outside the scope
 * of SRTP implementation. They can be assigned manually, or can be assigned
 * automatically using some key management protocol, such as MIKEY (RFC3830) or
 * Phil Zimmermann's ZRTP protocol.
 *
 * @author Bing SU (nova.su@gmail.com)
 */
public class SRTCPCryptoContext
{
    /**
     * The replay check windows size
     */
    private static final long REPLAY_WINDOW_SIZE = 64;

    /**
     * RTCP SSRC of this cryptographic context
     */
    private long ssrcCtx;

    /**
     * Master key identifier
     */
    private byte[] mki;

    /**
     * Index received so far
     */
    private int receivedIndex = 0;

    /**
     * Index sent so far
     */
    private int sentIndex = 0;

    /**
     * Bit mask for replay check
     */
    private long replayWindow;

    /**
     * Master encryption key
     */
    private byte[] masterKey;

    /**
     * Master salting key
     */
    private byte[] masterSalt;

    /**
     * Derived session encryption key
     */
    private byte[] encKey;

    /**
     * Derived session authentication key
     */
    private byte[] authKey;

    /**
     * Derived session salting key
     */
    private byte[] saltKey;

    /**
     * Encryption / Authentication policy for this session
     */
    private final SRTPPolicy policy;

    /**
     * The HMAC object we used to do packet authentication
     */
    private Mac mac;             // used for various HMAC computations

    // The symmetric cipher engines we need here
    private BlockCipher cipher = null;
    private BlockCipher cipherF8 = null; // used inside F8 mode only

    // implements the counter cipher mode for RTP according to RFC 3711
    private final SRTPCipherCTR cipherCtr = new SRTPCipherCTR();

    // Here some fields that a allocated here or in constructor. The methods
    // use these fields to avoid too many new operations

    private final byte[] tagStore;
    private final byte[] ivStore = new byte[16];
    private final byte[] rbStore = new byte[4];

    // this is some working store, used by some methods to avoid new operations
    // the methods must use this only to store some reults for immediate processing
    private final byte[] tempStore = new byte[100];

    /**
     * Construct an empty SRTPCryptoContext using ssrc.
     * The other parameters are set to default null value.
     *
     * @param ssrc SSRC of this SRTPCryptoContext
     */
    public SRTCPCryptoContext(long ssrcIn)
    {
        ssrcCtx = ssrcIn;
        mki = null;
        masterKey = null;
        masterSalt = null;
        encKey = null;
        authKey = null;
        saltKey = null;
        policy = null;
        tagStore = null;
    }

    /**
     * Construct a normal SRTPCryptoContext based on the given parameters.
     *
     * @param ssrc
     *            the RTP SSRC that this SRTP cryptographic context protects.
     * @param masterKey
     *            byte array holding the master key for this SRTP cryptographic
     *            context. Refer to chapter 3.2.1 of the RFC about the role of
     *            the master key.
     * @param masterSalt
     *            byte array holding the master salt for this SRTP cryptographic
     *            context. It is used to computer the initialization vector that
     *            in turn is input to compute the session key, session
     *            authentication key and the session salt.
     * @param policy
     *            SRTP policy for this SRTP cryptographic context, defined the
     *            encryption algorithm, the authentication algorithm, etc
     */
    @SuppressWarnings("fallthrough")
    public SRTCPCryptoContext(long ssrcIn,
            byte[] masterK, byte[] masterS, SRTPPolicy policyIn)
    {
        ssrcCtx = ssrcIn;
        mki = null;

        policy = policyIn;

        masterKey = new byte[policy.getEncKeyLength()];
        System.arraycopy(masterK, 0, masterKey, 0, policy
                .getEncKeyLength());

        masterSalt = new byte[policy.getSaltKeyLength()];
        System.arraycopy(masterS, 0, masterSalt, 0, policy
                .getSaltKeyLength());

        switch (policy.getEncType()) {
        case SRTPPolicy.NULL_ENCRYPTION:
            encKey = null;
            saltKey = null;
            break;

        case SRTPPolicy.AESF8_ENCRYPTION:
            cipherF8 = new AESFastEngine();

        case SRTPPolicy.AESCM_ENCRYPTION:
            cipher = new AESFastEngine();
            encKey = new byte[this.policy.getEncKeyLength()];
            saltKey = new byte[this.policy.getSaltKeyLength()];
            break;

        case SRTPPolicy.TWOFISHF8_ENCRYPTION:
            cipherF8 = new TwofishEngine();

        case SRTPPolicy.TWOFISH_ENCRYPTION:
            cipher = new TwofishEngine();
            encKey = new byte[this.policy.getEncKeyLength()];
            saltKey = new byte[this.policy.getSaltKeyLength()];
            break;
        }

        switch (policy.getAuthType()) {
        case SRTPPolicy.NULL_AUTHENTICATION:
            authKey = null;
            tagStore = null;
            break;

        case SRTPPolicy.HMACSHA1_AUTHENTICATION:
            mac = new HMac(new SHA1Digest());
            authKey = new byte[policy.getAuthKeyLength()];
            tagStore = new byte[mac.getMacSize()];
            break;

        case SRTPPolicy.SKEIN_AUTHENTICATION:
            mac = new SkeinMac();
            authKey = new byte[policy.getAuthKeyLength()];
            tagStore = new byte[policy.getAuthTagLength()];
            break;

        default:
            tagStore = null;
        }
    }

    /**
     * Close the crypto context.
     *
     * The close functions deletes key data and performs a cleanup of the
     * crypto context.
     *
     * Clean up key data, maybe this is the second time. However, sometimes
     * we cannot know if the CryptoContext was used and the application called
     * deriveSrtpKeys(...) tah would have cleaned the key data.
     *
     */
    public void close()
    {
        Arrays.fill(masterKey, (byte)0);
        Arrays.fill(masterSalt, (byte)0);
    }

    /**
     * Get the authentication tag length of this SRTP cryptographic context
     *
     * @return the authentication tag length of this SRTP cryptographic context
     */
    public int getAuthTagLength()
    {
        return policy.getAuthTagLength();
    }

    /**
     * Get the MKI length of this SRTP cryptographic context
     *
     * @return the MKI length of this SRTP cryptographic context
     */
    public int getMKILength()
    {
        if (mki != null)
            return mki.length;
        return 0;
    }

    /**
     * Get the SSRC of this SRTP cryptographic context
     *
     * @return the SSRC of this SRTP cryptographic context
     */
    public long getSSRC()
    {
        return ssrcCtx;
    }

    /**
     * Transform a RTP packet into a SRTP packet.
     * This method is called when a normal RTP packet ready to be sent.
     *
     * Operations done by the transformation may include: encryption, using
     * either Counter Mode encryption, or F8 Mode encryption, adding
     * authentication tag, currently HMC SHA1 method.
     *
     * Both encryption and authentication functionality can be turned off
     * as long as the SRTPPolicy used in this SRTPCryptoContext is requires no
     * encryption and no authentication. Then the packet will be sent out
     * untouched. However this is not encouraged. If no SRTP feature is enabled,
     * then we shall not use SRTP TransformConnector. We should use the original
     * method (RTPManager managed transportation) instead.
     *
     * @param pkt the RTP packet that is going to be sent out
     */
    public void transformPacket(RawPacket pkt)
    {
        boolean encrypt = false;
        /* Encrypt the packet using Counter Mode encryption */
        if (policy.getEncType() == SRTPPolicy.AESCM_ENCRYPTION ||
                policy.getEncType() == SRTPPolicy.TWOFISH_ENCRYPTION)
        {
            processPacketAESCM(pkt, sentIndex);
            encrypt = true;
        }

        /* Encrypt the packet using F8 Mode encryption */
        else if (policy.getEncType() == SRTPPolicy.AESF8_ENCRYPTION ||
                policy.getEncType() == SRTPPolicy.TWOFISHF8_ENCRYPTION)
        {
            processPacketAESF8(pkt, sentIndex);
            encrypt = true;
        }
        int index = 0;
        if (encrypt)
            index = sentIndex | 0x80000000;

        // Grow packet storage in one step
        pkt.grow(4 + policy.getAuthTagLength());

        // Authenticate the packet
        // The authenticate method gets the index via parameter and stores
        // it in network order in rbStore variable.
        if (policy.getAuthType() != SRTPPolicy.NULL_AUTHENTICATION)
        {
            authenticatePacket(pkt, index);
            pkt.append(rbStore, 4);
            pkt.append(tagStore, policy.getAuthTagLength());
        }
        sentIndex++;
        sentIndex &= ~0x80000000;       // clear possible overflow
    }

    /**
     * Transform a SRTCP packet into a RTCP packet.
     * This method is called when a SRTCP packet was received.
     *
     * Operations done by the this operation include:
     * Authentication check, Packet replay check and decryption.
     *
     * Both encryption and authentication functionality can be turned off
     * as long as the SRTPPolicy used in this SRTPCryptoContext requires no
     * encryption and no authentication. Then the packet will be sent out
     * untouched. However this is not encouraged. If no SRTCP feature is enabled,
     * then we shall not use SRTP TransformConnector. We should use the original
     * method (RTPManager managed transportation) instead.
     *
     * @param pkt the received RTCP packet
     * @return true if the packet can be accepted
     *         false if authentication or replay check failed
     */
    public boolean reverseTransformPacket(RawPacket pkt)
    {
        boolean decrypt = false;
        int tagLength = policy.getAuthTagLength();
        int indexEflag = pkt.getSRTCPIndex(tagLength);

        if ((indexEflag & 0x80000000) == 0x80000000)
            decrypt = true;

        int index = indexEflag & ~0x80000000;

        /* Replay control */
        if (!checkReplay(index))
        {
            return false;
        }

        /* Authenticate the packet */
        if (policy.getAuthType() != SRTPPolicy.NULL_AUTHENTICATION)
        {
            // get original authentication data and store in tempStore
            pkt.readRegionToBuff(pkt.getLength() - tagLength, tagLength,
                    tempStore);

            // Shrink packet to remove the authentication tag and index
            // because this is part of authenicated data
            pkt.shrink(tagLength + 4);

            // compute, then save authentication in tagStore
            authenticatePacket(pkt, indexEflag);

            for (int i = 0; i < tagLength; i++)
            {
                if ((tempStore[i] & 0xff) == (tagStore[i] & 0xff))
                    continue;
                else
                    return false;
            }
        }

        if (decrypt)
        {
            /* Decrypt the packet using Counter Mode encryption */
            if (policy.getEncType() == SRTPPolicy.AESCM_ENCRYPTION
                    || policy.getEncType() == SRTPPolicy.TWOFISH_ENCRYPTION)
            {
                processPacketAESCM(pkt, index);
            }

            /* Decrypt the packet using F8 Mode encryption */
            else if (policy.getEncType() == SRTPPolicy.AESF8_ENCRYPTION
                    || policy.getEncType() == SRTPPolicy.TWOFISHF8_ENCRYPTION)
            {
                processPacketAESF8(pkt, index);
            }
        }
        update(index);

        return true;
    }

    /**
     * Perform Counter Mode AES encryption / decryption
     * @param pkt the RTP packet to be encrypted / decrypted
     */
    public void processPacketAESCM(RawPacket pkt, int index)
    {
        long ssrc = pkt.getRTCPSSRC();

        /* Compute the CM IV (refer to chapter 4.1.1 in RFC 3711):
        *
        * k_s   XX XX XX XX XX XX XX XX XX XX XX XX XX XX
        * SSRC              XX XX XX XX
        * index                               XX XX XX XX
        * ------------------------------------------------------XOR
        * IV    XX XX XX XX XX XX XX XX XX XX XX XX XX XX 00 00
        *        0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
        */
        ivStore[0] = saltKey[0];
        ivStore[1] = saltKey[1];
        ivStore[2] = saltKey[2];
        ivStore[3] = saltKey[3];

        // The shifts transform the ssrc and index into network order
        ivStore[4] = (byte) (((ssrc >> 24) & 0xff) ^ this.saltKey[4]);
        ivStore[5] = (byte) (((ssrc >> 16) & 0xff) ^ this.saltKey[5]);
        ivStore[6] = (byte) (((ssrc >> 8) & 0xff) ^ this.saltKey[6]);
        ivStore[7] = (byte) ((ssrc & 0xff) ^ this.saltKey[7]);

        ivStore[8] = saltKey[8];
        ivStore[9] = saltKey[9];

        ivStore[10] = (byte) (((index >> 24) & 0xff) ^ this.saltKey[10]);
        ivStore[11] = (byte) (((index >> 16) & 0xff) ^ this.saltKey[11]);
        ivStore[12] = (byte) (((index >> 8) & 0xff) ^ this.saltKey[12]);
        ivStore[13] = (byte) ((index & 0xff) ^ this.saltKey[13]);

        ivStore[14] = ivStore[15] = 0;

        // Encrypted part excludes fixed header (8 bytes)
        final int payloadOffset = 8;
        final int payloadLength = pkt.getLength() - payloadOffset;

        cipherCtr.process(cipher, pkt.getBuffer(),
            pkt.getOffset() + payloadOffset,
            payloadLength, ivStore);
    }

    /**
     * Perform F8 Mode AES encryption / decryption
     *
     * @param pkt the RTP packet to be encrypted / decrypted
     */
    public void processPacketAESF8(RawPacket pkt, int index)
    {
        // byte[] iv = new byte[16];

        // 4 bytes of the iv are zero
        // the first byte of the RTP header is not used.
        ivStore[0] = 0;
        ivStore[1] = 0;
        ivStore[2] = 0;
        ivStore[3] = 0;

        // Need the encryption flag
        index = index | 0x80000000;

        // set the index and the encrypt flag in network order into IV
        ivStore[4] = (byte) (index >> 24);
        ivStore[5] = (byte) (index >> 16);
        ivStore[6] = (byte) (index >> 8);
        ivStore[7] = (byte) index;

        // The fixed header follows and fills the rest of the IV
        System.arraycopy(pkt.getBuffer(), pkt.getOffset(), ivStore, 8, 8);

        // Encrypted part excludes fixed header (8 bytes), index (4 bytes), and
        // authentication tag (variable according to policy)
        final int payloadOffset = 8;
        final int payloadLength
            = pkt.getLength() - (4 + policy.getAuthTagLength());

        SRTPCipherF8.process(cipher, pkt.getBuffer(),
            pkt.getOffset() + payloadOffset,
            payloadLength, ivStore, cipherF8);
    }

    /**
     * Authenticate a packet.
     *
     * Calculated authentication tag is stored in tagStore area.
     *
     * @param pkt the RTP packet to be authenticated
     */
    private void authenticatePacket(RawPacket pkt, int index)
    {
        mac.update(pkt.getBuffer(), 0, pkt.getLength());
        // byte[] rb = new byte[4];
        rbStore[0] = (byte) (index >> 24);
        rbStore[1] = (byte) (index >> 16);
        rbStore[2] = (byte) (index >> 8);
        rbStore[3] = (byte) index;
        mac.update(rbStore, 0, rbStore.length);
        mac.doFinal(tagStore, 0);
    }

    /**
     * Checks if a packet is a replayed on based on its sequence number.
     *
     * This method supports a 64 packet history relative the the given
     * sequence number.
     *
     * Sequence Number is guaranteed to be real (not faked) through
     * authentication.
     *
     * @param index index number of the SRTCP packet
     * @return true if this sequence number indicates the packet is not a
     * replayed one, false if not
     */
    boolean checkReplay(int index)
    {
        // compute the index of previously received packet and its
        // delta to the new received packet
        long delta = index - receivedIndex;

        if (delta > 0)
        {
            /* Packet not yet received */
            return true;
        }
        else
        {
            if (-delta > REPLAY_WINDOW_SIZE)
            {
                /* Packet too old */
                return false;
            }
            else
            {
                if (((this.replayWindow >> (-delta)) & 0x1) != 0)
                {
                    /* Packet already received ! */
                    return false;
                }
                else
                {
                    /* Packet not yet received */
                    return true;
                }
            }
        }
    }

    /**
     * Compute the initialization vector, used later by encryption algorithms,
     * based on the label.
     *
     * @param label label specified for each type of iv
     */
    private void computeIv(byte label)
    {
        for (int i = 0; i < 14; i++)
        {
            ivStore[i] = masterSalt[i];
        }
        ivStore[7] ^= label;
        ivStore[14] = ivStore[15] = 0;
    }

    /**
     * Derives the srtcp session keys from the master key.
     *
     */
    public void deriveSrtcpKeys()
    {
        // compute the session encryption key
        byte label = 3;
        computeIv(label);

        KeyParameter encryptionKey = new KeyParameter(masterKey);
        cipher.init(true, encryptionKey);
        Arrays.fill(masterKey, (byte)0);

        cipherCtr.getCipherStream(cipher, encKey, policy.getEncKeyLength(), ivStore);

        if (authKey != null)
        {
            label = 4;
            computeIv(label);
            cipherCtr.getCipherStream(cipher, authKey,
                policy.getAuthKeyLength(), ivStore);

            switch ((policy.getAuthType()))
            {
            case SRTPPolicy.HMACSHA1_AUTHENTICATION:
                KeyParameter key =  new KeyParameter(authKey);
                mac.init(key);
                break;

            case SRTPPolicy.SKEIN_AUTHENTICATION:
                // Skein MAC uses number of bits as MAC size, not just bytes
                ParametersForSkein pfs = new ParametersForSkein(
                    new KeyParameter(authKey),
                    ParametersForSkein.Skein512, tagStore.length * 8);
                mac.init(pfs);
                break;
            }
        }
        Arrays.fill(authKey, (byte)0);

        // compute the session salt
        label = 5;
        computeIv(label);
        cipherCtr.getCipherStream(cipher, saltKey, policy.getSaltKeyLength(), ivStore);
        Arrays.fill(masterSalt, (byte)0);

        // As last step: initialize cipher with derived encryption key.
        if (cipherF8 != null)
            SRTPCipherF8.deriveForIV(cipherF8, encKey, saltKey);
        encryptionKey = new KeyParameter(encKey);
        cipher.init(true, encryptionKey);
        Arrays.fill(encKey, (byte)0);
    }

    /**
     * Update the SRTP packet index.
     *
     * This method is called after all checks were successful.
     *
     * @param index index number of the accepted packet
     */
    private void update(int index)
    {
        int delta = receivedIndex - index;

        /* update the replay bit mask */
        if (delta > 0)
        {
            replayWindow = replayWindow << delta;
            replayWindow |= 1;
        }
        else
        {
            replayWindow |= ( 1 << delta );
        }

        receivedIndex = index;
    }

    /**
     * Derive a new SRTPCryptoContext for use with a new SSRC
     *
     * This method returns a new SRTPCryptoContext initialized with the data of
     * this SRTPCryptoContext. Replacing the SSRC, Roll-over-Counter, and the
     * key derivation rate the application cab use this SRTPCryptoContext to
     * encrypt / decrypt a new stream (Synchronization source) inside one RTP
     * session.
     *
     * Before the application can use this SRTPCryptoContext it must call the
     * deriveSrtpKeys method.
     *
     * @param ssrc
     *            The SSRC for this context
     * @return a new SRTPCryptoContext with all relevant data set.
     */
    public SRTCPCryptoContext deriveContext(long ssrc)
    {
        SRTCPCryptoContext pcc = null;
        pcc = new SRTCPCryptoContext(ssrc, masterKey,
                masterSalt, policy);
        return pcc;
    }
}


text:
import Result from "./result";

export default class Test {
  constructor() {
    if (!Test.instance) {
      this.timeouts = [];

      this.config = null;
      this.result = new Result();

      this.running = false;
      this.status = null;
      this.step = null;
      this.error = false;
      this.alerts = {};

      Test.instance = this;
    }

    return Test.instance;
  }

  /**
   * Store the result in the server
   * @returns {Promise<void>}
   */
  storeResult() {
    return new Promise((resolve, reject) => {
      const endpoint = `${this.config.result.path}`;
      const xhr = new XMLHttpRequest();
      xhr.open("POST", endpoint, true);
      xhr.addEventListener("load", e => {
        this.result.id = xhr.response;
        resolve();
      });
      xhr.addEventListener("error", e => {
        reject({
          status: STATUS.FAILED,
          error: e.error,
          message: e.message
        });
      });
      xhr.send(this.getJsonResult(this.result));
    });
  }

  /**
   * Get result as JSON
   * @param {object} result
   * @returns {string}
   */
  getJsonResult(result) {
    return JSON.stringify({
      timestamp: new Date().getTime(),
      latency: {
        avg: result.latency.avg
      },
      jitter: result.jitter,
      download: {
        speed: result.download.speed
      },
      upload: {
        speed: result.upload.speed
      },
      ipInfo: {
        ip: result.ipInfo.ip,
        org: result.ipInfo.org
      }
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
This project allows you to use computed attributes with Coffeescript
Classes using Knockout.js, like so:

```
class Animal
  ko.hasComputedProperties @
  @computed "greeting", ->
    "#{@name()} says hi!"

  constructor:
    @name = ko.observable("Jaguar")

animal = new Animal
animal.name() # => "Jaguar"
animal.greeting() # => "Jaguar says hi!"
animal.name("Giant Squid")
animal.greeting() # => "Giant Squid says hi!"

animal.getComputed("greeting") # => (the raw computed observable object, for form fields and the like)
```


text:
namespace webkit_base {

// Represents a base Web data element. This could be either one of
// bytes, file or blob data.
class WEBKIT_BASE_EXPORT DataElement {
 public:
  enum Type {
    TYPE_UNKNOWN = -1,
    TYPE_BYTES,
    TYPE_FILE,
    TYPE_BLOB,
    TYPE_FILE_FILESYSTEM,
  };

  DataElement();
  ~DataElement();

  Type type() const { return type_; }
  const char* bytes() const { return bytes_ ? bytes_ : &buf_[0]; }
  const base::FilePath& path() const { return path_; }
  const GURL& url() const { return url_; }
  uint64 offset() const { return offset_; }
  uint64 length() const { return length_; }
  const base::Time& expected_modification_time() const {
    return expected_modification_time_;
  }

  // Sets TYPE_BYTES data. This copies the given data into the element.
  void SetToBytes(const char* bytes, int bytes_len) {
    type_ = TYPE_BYTES;
    buf_.assign(bytes, bytes + bytes_len);
    length_ = buf_.size();
  }

  // Sets TYPE_BYTES data. This does NOT copy the given data and the caller
  // should make sure the data is alive when this element is accessed.
  void SetToSharedBytes(const char* bytes, int bytes_len) {
    type_ = TYPE_BYTES;
    bytes_ = bytes;
    length_ = bytes_len;
  }

  // Sets TYPE_FILE data.
  void SetToFilePath(const base::FilePath& path) {
    SetToFilePathRange(path, 0, kuint64max, base::Time());
  }

  // Sets TYPE_BLOB data.
  void SetToBlobUrl(const GURL& blob_url) {
    SetToBlobUrlRange(blob_url, 0, kuint64max);
  }

  // Sets TYPE_FILE data with range.
  void SetToFilePathRange(const base::FilePath& path,
                          uint64 offset, uint64 length,
                          const base::Time& expected_modification_time);

  // Sets TYPE_BLOB data with range.
  void SetToBlobUrlRange(const GURL& blob_url,
                         uint64 offset, uint64 length);

  // Sets TYPE_FILE_FILESYSTEM with range.
  void SetToFileSystemUrlRange(const GURL& filesystem_url,
                               uint64 offset, uint64 length,
                               const base::Time& expected_modification_time);

 private:
  Type type_;
  std::vector<char> buf_;  // For TYPE_BYTES.
  const char* bytes_;  // For TYPE_BYTES.
  base::FilePath path_;  // For TYPE_FILE.
  GURL url_;  // For TYPE_BLOB or TYPE_FILE_FILESYSTEM.
  uint64 offset_;
  uint64 length_;
  base::Time expected_modification_time_;
};

#if defined(UNIT_TEST)
inline bool operator==(const DataElement& a, const DataElement& b) {
  if (a.type() != b.type() ||
      a.offset() != b.offset() ||
      a.length() != b.length())
    return false;
  switch (a.type()) {
    case DataElement::TYPE_BYTES:
      return memcmp(a.bytes(), b.bytes(), b.length()) == 0;
    case DataElement::TYPE_FILE:
      return a.path() == b.path() &&
             a.expected_modification_time() == b.expected_modification_time();
    case DataElement::TYPE_BLOB:
    case DataElement::TYPE_FILE_FILESYSTEM:
      return a.url() == b.url();
    case DataElement::TYPE_UNKNOWN:
      NOTREACHED();
      return false;
  }
  return false;
}

inline bool operator!=(const DataElement& a, const DataElement& b) {
  return !(a == b);
}
#endif  // defined(UNIT_TEST)

}  // namespace webkit_base

#endif  // WEBKIT_BASE_DATA_ELEMENT_H_


text:
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link rel="stylesheet" type="text/css" href="../css/jsUnitStyle.css"/>
    <link rel="stylesheet" type="text/css" href="../stylesheets/main.css"/>

    <input title='Search for Pipeline' placeholder='Search for Pipeline' id='pipeline-search' type='text'/>
    <button class='header_submit submit button' id='show_pipelines_selector' type='button' value='Personalize'>
        PERSONALIZE
    </button>

        <form action='/pipelines/select_pipelines' method='post'
              onsubmit="PipelineOperations.onPipelineSelector(this, '/pipelines/select_pipelines'); return false;; ">

Select:

                All
                None

                    <input type='checkbox' id='select_group_group-1' name='selector[group][]' value='group-1' checked='checked'/>
                    group-1

                        <input type='checkbox' id='select_pipeline_pipeline-1' name='selector[pipeline][]' value='pipeline-1' checked='checked'/>
                        pipeline-1

                        <input type='checkbox' id='select_pipeline_pipeline-2' name='selector[pipeline][]' value='pipeline-2' checked='checked'/>
                        pipeline-2

                        <input type='checkbox' id='select_pipeline_pipeline-3' name='selector[pipeline][]' value='pipeline-3' checked='checked'/>
                        pipeline-3

                        <input type='checkbox' id='select_pipeline_pipeline-4' name='selector[pipeline][]' value='pipeline-4' checked='checked'/>
                        pipeline-4

                    <input type='checkbox' id='select_group_group-2' name='selector[group][]' value='group-2' checked='checked'/>
                    group-2

                        <input type='checkbox' id='select_pipeline_pipeline-2-1' name='selector[pipeline][]' value='pipeline-2-1' checked='checked'/>
                        pipeline-2-1

                    <input type='checkbox' id='select_group_group-x' name='selector[group][]' value='group-x' checked='checked'/>
                    group-x

                        <input type='checkbox' id='select_pipeline_pipeline-x1' name='selector[pipeline][]' value='pipeline-x1' checked='checked'/>
                        pipeline-x1

                        <input type='checkbox' id='select_pipeline_pipeline-x2' name='selector[pipeline][]' value='pipeline-x2' checked='checked'/>
                        pipeline-x2

                        <input type='checkbox' id='select_pipeline_pipeline-x3' name='selector[pipeline][]' value='pipeline-x3' checked='checked'/>
                        pipeline-x3

                        <input type='checkbox' id='select_pipeline_pipeline-x4' name='selector[pipeline][]' value='pipeline-x4' checked='checked'/>
                        pipeline-x4

                <button class='primary submit' id='apply_pipelines_selector' type='submit' value='Apply'>
                    APPLY
                </button>

        </form>


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * CMS decoding.
 *
 * $Id: cmsdecode.c,v 1.15 2012/04/25 14:50:08 gerv%gerv.net Exp $
 */

#include "cmslocal.h"

#include "cert.h"
#include "key.h"
#include "secasn1.h"
#include "secitem.h"
#include "secoid.h"
#include "prtime.h"
#include "secerr.h"

struct NSSCMSDecoderContextStr {
    SEC_ASN1DecoderContext *	dcx;		/* ASN.1 decoder context */
    NSSCMSMessage *		cmsg;		/* backpointer to the root message */
    SECOidTag			type;		/* type of message */
    NSSCMSContent		content;	/* pointer to message */
    NSSCMSDecoderContext *	childp7dcx;	/* inner CMS decoder context */
    PRBool			saw_contents;
    int				error;
    NSSCMSContentCallback	cb;
    void *			cb_arg;
    PRBool			first_decoded;
    PRBool			need_indefinite_finish;
};

struct NSSCMSDecoderDataStr {
    SECItem data; 	/* must be first */
    unsigned int totalBufferSize;
};

typedef struct NSSCMSDecoderDataStr NSSCMSDecoderData;

static void      nss_cms_decoder_update_filter (void *arg, const char *data,
                 unsigned long len, int depth, SEC_ASN1EncodingPart data_kind);
static SECStatus nss_cms_before_data(NSSCMSDecoderContext *p7dcx);
static SECStatus nss_cms_after_data(NSSCMSDecoderContext *p7dcx);
static SECStatus nss_cms_after_end(NSSCMSDecoderContext *p7dcx);
static void      nss_cms_decoder_work_data(NSSCMSDecoderContext *p7dcx,
		 const unsigned char *data, unsigned long len, PRBool final);
static NSSCMSDecoderData *nss_cms_create_decoder_data(PRArenaPool *poolp);

extern const SEC_ASN1Template NSSCMSMessageTemplate[];

static NSSCMSDecoderData *
nss_cms_create_decoder_data(PRArenaPool *poolp)
{
    NSSCMSDecoderData *decoderData = NULL;

    decoderData = (NSSCMSDecoderData *)
			PORT_ArenaAlloc(poolp,sizeof(NSSCMSDecoderData));
    if (!decoderData) {
	return NULL;
    }
    decoderData->data.data = NULL;
    decoderData->data.len = 0;
    decoderData->totalBufferSize = 0;
    return decoderData;
}

/*
 * nss_cms_decoder_notify -
 *  this is the driver of the decoding process. It gets called by the ASN.1
 *  decoder before and after an object is decoded.
 *  at various points in the decoding process, we intercept to set up and do
 *  further processing.
 */
static void
nss_cms_decoder_notify(void *arg, PRBool before, void *dest, int depth)
{
    NSSCMSDecoderContext *p7dcx;
    NSSCMSContentInfo *rootcinfo, *cinfo;
    PRBool after = !before;

    p7dcx = (NSSCMSDecoderContext *)arg;
    rootcinfo = &(p7dcx->cmsg->contentInfo);

    /* XXX error handling: need to set p7dcx->error */

#ifdef CMSDEBUG
    fprintf(stderr, "%6.6s, dest = 0x%08x, depth = %d\n", before ? "before" : "after", dest, depth);
#endif

    /* so what are we working on right now? */
    if (p7dcx->type == SEC_OID_UNKNOWN) {
	/*
	 * right now, we are still decoding the OUTER (root) cinfo
	 * As soon as we know the inner content type, set up the info,
	 * but NO inner decoder or filter. The root decoder handles the first
	 * level children by itself - only for encapsulated contents (which
	 * are encoded as DER inside of an OCTET STRING) we need to set up a
	 * child decoder...
	 */
	if (after && dest == &(rootcinfo->contentType)) {
	    p7dcx->type = NSS_CMSContentInfo_GetContentTypeTag(rootcinfo);
	    p7dcx->content = rootcinfo->content;
	    /* is this ready already ? need to alloc? */
	    /* XXX yes we need to alloc -- continue here */
	}
    } else if (NSS_CMSType_IsData(p7dcx->type)) {
	/* this can only happen if the outermost cinfo has DATA in it */
	/* otherwise, we handle this type implicitely in the inner decoders */

	if (before && dest == &(rootcinfo->content)) {
	    /* cause the filter to put the data in the right place...
	    ** We want the ASN.1 decoder to deliver the decoded bytes to us
	    ** from now on
	    */
	    SEC_ASN1DecoderSetFilterProc(p7dcx->dcx,
					  nss_cms_decoder_update_filter,
					  p7dcx,
					  (PRBool)(p7dcx->cb != NULL));
	} else if (after && dest == &(rootcinfo->content.data)) {
	    /* remove the filter */
	    SEC_ASN1DecoderClearFilterProc(p7dcx->dcx);
	}
    } else if (NSS_CMSType_IsWrapper(p7dcx->type)) {
	if (!before || dest != &(rootcinfo->content)) {

	    if (p7dcx->content.pointer == NULL)
		p7dcx->content = rootcinfo->content;

	    /* get this data type's inner contentInfo */
	    cinfo = NSS_CMSContent_GetContentInfo(p7dcx->content.pointer,
	                                      p7dcx->type);

	    if (before && dest == &(cinfo->contentType)) {
	        /* at this point, set up the &%$&$ back pointer */
	        /* we cannot do it later, because the content itself
		 * is optional! */
		switch (p7dcx->type) {
		case SEC_OID_PKCS7_SIGNED_DATA:
		    p7dcx->content.signedData->cmsg = p7dcx->cmsg;
		    break;
		case SEC_OID_PKCS7_DIGESTED_DATA:
		    p7dcx->content.digestedData->cmsg = p7dcx->cmsg;
		    break;
		case SEC_OID_PKCS7_ENVELOPED_DATA:
		    p7dcx->content.envelopedData->cmsg = p7dcx->cmsg;
		    break;
		case SEC_OID_PKCS7_ENCRYPTED_DATA:
		    p7dcx->content.encryptedData->cmsg = p7dcx->cmsg;
		    break;
		default:
		    p7dcx->content.genericData->cmsg = p7dcx->cmsg;
		    break;
		}
	    }

	    if (before && dest == &(cinfo->rawContent)) {
		/* we want the ASN.1 decoder to deliver the decoded bytes to us
		 ** from now on
		 */
		SEC_ASN1DecoderSetFilterProc(p7dcx->dcx,
	                                 nss_cms_decoder_update_filter,
					 p7dcx, (PRBool)(p7dcx->cb != NULL));

		/* we're right in front of the data */
		if (nss_cms_before_data(p7dcx) != SECSuccess) {
		    SEC_ASN1DecoderClearFilterProc(p7dcx->dcx);
		    /* stop all processing */
		    p7dcx->error = PORT_GetError();
		}
	    }
	    if (after && dest == &(cinfo->rawContent)) {
		/* we're right after of the data */
		if (nss_cms_after_data(p7dcx) != SECSuccess)
		    p7dcx->error = PORT_GetError();

		/* we don't need to see the contents anymore */
		SEC_ASN1DecoderClearFilterProc(p7dcx->dcx);
	    }
	}
    } else {
	/* unsupported or unknown message type - fail  gracefully */
	p7dcx->error = SEC_ERROR_UNSUPPORTED_MESSAGE_TYPE;
    }
}

/*
 * nss_cms_before_data - set up the current encoder to receive data
 */
static SECStatus
nss_cms_before_data(NSSCMSDecoderContext *p7dcx)
{
    SECStatus rv;
    SECOidTag childtype;
    PLArenaPool *poolp;
    NSSCMSDecoderContext *childp7dcx;
    NSSCMSContentInfo *cinfo;
    const SEC_ASN1Template *template;
    void *mark = NULL;
    size_t size;

    poolp = p7dcx->cmsg->poolp;

    /* call _Decode_BeforeData handlers */
    switch (p7dcx->type) {
    case SEC_OID_PKCS7_SIGNED_DATA:
	/* we're decoding a signedData, so set up the digests */
	rv = NSS_CMSSignedData_Decode_BeforeData(p7dcx->content.signedData);
	break;
    case SEC_OID_PKCS7_DIGESTED_DATA:
	/* we're encoding a digestedData, so set up the digest */
	rv = NSS_CMSDigestedData_Decode_BeforeData(p7dcx->content.digestedData);
	break;
    case SEC_OID_PKCS7_ENVELOPED_DATA:
	rv = NSS_CMSEnvelopedData_Decode_BeforeData(
	                             p7dcx->content.envelopedData);
	break;
    case SEC_OID_PKCS7_ENCRYPTED_DATA:
	rv = NSS_CMSEncryptedData_Decode_BeforeData(
	                             p7dcx->content.encryptedData);
	break;
    default:
	rv = NSS_CMSGenericWrapperData_Decode_BeforeData(p7dcx->type,
				p7dcx->content.genericData);
    }
    if (rv != SECSuccess)
	return SECFailure;

    /* ok, now we have a pointer to cinfo */
    /* find out what kind of data is encapsulated */

    cinfo = NSS_CMSContent_GetContentInfo(p7dcx->content.pointer, p7dcx->type);
    childtype = NSS_CMSContentInfo_GetContentTypeTag(cinfo);

    if (NSS_CMSType_IsData(childtype)) {
	cinfo->content.pointer = (void *) nss_cms_create_decoder_data(poolp);
	if (cinfo->content.pointer == NULL)
	    /* set memory error */
	    return SECFailure;

	p7dcx->childp7dcx = NULL;
	return SECSuccess;
    }

    /* set up inner decoder */

    if ((template = NSS_CMSUtil_GetTemplateByTypeTag(childtype)) == NULL)
	return SECFailure;

    childp7dcx = PORT_ZNew(NSSCMSDecoderContext);
    if (childp7dcx == NULL)
	return SECFailure;

    mark = PORT_ArenaMark(poolp);

    /* allocate space for the stuff we're creating */
    size = NSS_CMSUtil_GetSizeByTypeTag(childtype);
    childp7dcx->content.pointer = (void *)PORT_ArenaZAlloc(poolp, size);
    if (childp7dcx->content.pointer == NULL)
	goto loser;

    /* give the parent a copy of the pointer so that it doesn't get lost */
    cinfo->content.pointer = childp7dcx->content.pointer;

    /* start the child decoder */
    childp7dcx->dcx = SEC_ASN1DecoderStart(poolp, childp7dcx->content.pointer,
                                           template);
    if (childp7dcx->dcx == NULL)
	goto loser;

    /* the new decoder needs to notify, too */
    SEC_ASN1DecoderSetNotifyProc(childp7dcx->dcx, nss_cms_decoder_notify,
                                 childp7dcx);

    /* tell the parent decoder that it needs to feed us the content data */
    p7dcx->childp7dcx = childp7dcx;

    childp7dcx->type = childtype;	/* our type */

    childp7dcx->cmsg = p7dcx->cmsg;	/* backpointer to root message */

    /* should the child decoder encounter real data,
    ** it must give it to the caller
    */
    childp7dcx->cb = p7dcx->cb;
    childp7dcx->cb_arg = p7dcx->cb_arg;
    childp7dcx->first_decoded = PR_FALSE;
    childp7dcx->need_indefinite_finish = PR_FALSE;
    if (childtype == SEC_OID_PKCS7_SIGNED_DATA) {
	childp7dcx->first_decoded = PR_TRUE;
    }

    /* now set up the parent to hand decoded data to the next level decoder */
    p7dcx->cb = (NSSCMSContentCallback)NSS_CMSDecoder_Update;
    p7dcx->cb_arg = childp7dcx;

    PORT_ArenaUnmark(poolp, mark);

    return SECSuccess;

loser:
    if (mark)
	PORT_ArenaRelease(poolp, mark);
    if (childp7dcx)
	PORT_Free(childp7dcx);
    p7dcx->childp7dcx = NULL;
    return SECFailure;
}

static SECStatus
nss_cms_after_data(NSSCMSDecoderContext *p7dcx)
{
    NSSCMSDecoderContext *childp7dcx;
    SECStatus rv = SECFailure;

    /* Handle last block. This is necessary to flush out the last bytes
     * of a possibly incomplete block */
    nss_cms_decoder_work_data(p7dcx, NULL, 0, PR_TRUE);

    /* finish any "inner" decoders - there's no more data coming... */
    if (p7dcx->childp7dcx != NULL) {
	childp7dcx = p7dcx->childp7dcx;
	if (childp7dcx->dcx != NULL) {
	    /* we started and indefinite sequence somewhere, not complete it */
	    if (childp7dcx->need_indefinite_finish) {
		static const char lbuf[2] = { 0, 0 };
		NSS_CMSDecoder_Update(childp7dcx, lbuf, sizeof(lbuf));
		childp7dcx->need_indefinite_finish = PR_FALSE;
	    }

	    if (SEC_ASN1DecoderFinish(childp7dcx->dcx) != SECSuccess) {
		/* do what? free content? */
		rv = SECFailure;
	    } else {
		rv = nss_cms_after_end(childp7dcx);
	    }
	    if (rv != SECSuccess)
		goto done;
	}
	PORT_Free(p7dcx->childp7dcx);
	p7dcx->childp7dcx = NULL;
    }

    switch (p7dcx->type) {
    case SEC_OID_PKCS7_SIGNED_DATA:
	/* this will finish the digests and verify */
	rv = NSS_CMSSignedData_Decode_AfterData(p7dcx->content.signedData);
	break;
    case SEC_OID_PKCS7_ENVELOPED_DATA:
	rv = NSS_CMSEnvelopedData_Decode_AfterData(
	                            p7dcx->content.envelopedData);
	break;
    case SEC_OID_PKCS7_DIGESTED_DATA:
	rv = NSS_CMSDigestedData_Decode_AfterData(
	                           p7dcx->content.digestedData);
	break;
    case SEC_OID_PKCS7_ENCRYPTED_DATA:
	rv = NSS_CMSEncryptedData_Decode_AfterData(
	                            p7dcx->content.encryptedData);
	break;
    case SEC_OID_PKCS7_DATA:
	/* do nothing */
	break;
    default:
	rv = NSS_CMSGenericWrapperData_Decode_AfterData(p7dcx->type,
	                            p7dcx->content.genericData);
	break;
    }
done:
    return rv;
}

static SECStatus
nss_cms_after_end(NSSCMSDecoderContext *p7dcx)
{
    SECStatus rv = SECSuccess;

    switch (p7dcx->type) {
    case SEC_OID_PKCS7_SIGNED_DATA:
	if (p7dcx->content.signedData)
	    rv = NSS_CMSSignedData_Decode_AfterEnd(p7dcx->content.signedData);
	break;
    case SEC_OID_PKCS7_ENVELOPED_DATA:
	if (p7dcx->content.envelopedData)
	    rv = NSS_CMSEnvelopedData_Decode_AfterEnd(
	                               p7dcx->content.envelopedData);
	break;
    case SEC_OID_PKCS7_DIGESTED_DATA:
	if (p7dcx->content.digestedData)
	    rv = NSS_CMSDigestedData_Decode_AfterEnd(
	                              p7dcx->content.digestedData);
	break;
    case SEC_OID_PKCS7_ENCRYPTED_DATA:
	if (p7dcx->content.encryptedData)
	    rv = NSS_CMSEncryptedData_Decode_AfterEnd(
	                               p7dcx->content.encryptedData);
	break;
    case SEC_OID_PKCS7_DATA:
	break;
    default:
	rv = NSS_CMSGenericWrapperData_Decode_AfterEnd(p7dcx->type,
	                               p7dcx->content.genericData);
	break;
    }
    return rv;
}

/*
 * nss_cms_decoder_work_data - handle decoded data bytes.
 *
 * This function either decrypts the data if needed, and/or calculates digests
 * on it, then either stores it or passes it on to the next level decoder.
 */
static void
nss_cms_decoder_work_data(NSSCMSDecoderContext *p7dcx,
			     const unsigned char *data, unsigned long len,
			     PRBool final)
{
    NSSCMSContentInfo *cinfo;
    unsigned char *buf = NULL;
    unsigned char *dest;
    unsigned int offset;
    SECStatus rv;

    /*
     * We should really have data to process, or we should be trying
     * to finish/flush the last block.  (This is an overly paranoid
     * check since all callers are in this file and simple inspection
     * proves they do it right.  But it could find a bug in future
     * modifications/development, that is why it is here.)
     */
    PORT_Assert ((data != NULL && len) || final);

    cinfo = NSS_CMSContent_GetContentInfo(p7dcx->content.pointer, p7dcx->type);
    if (!cinfo) {
	/* The original programmer didn't expect this to happen */
	p7dcx->error = SEC_ERROR_LIBRARY_FAILURE;
	goto loser;
    }

    if (cinfo->privateInfo && cinfo->privateInfo->ciphcx != NULL) {
	/*
	 * we are decrypting.
	 *
	 * XXX If we get an error, we do not want to do the digest or callback,
	 * but we want to keep decoding.  Or maybe we want to stop decoding
	 * altogether if there is a callback, because obviously we are not
	 * sending the data back and they want to know that.
	 */

	unsigned int outlen = 0;	/* length of decrypted data */
	unsigned int buflen;		/* length available for decrypted data */

	/* find out about the length of decrypted data */
	buflen = NSS_CMSCipherContext_DecryptLength(cinfo->privateInfo->ciphcx, len, final);

	/*
	 * it might happen that we did not provide enough data for a full
	 * block (decryption unit), and that there is no output available
	 */

	/* no output available, AND no input? */
	if (buflen == 0 && len == 0)
	    goto loser;	/* bail out */

	/*
	 * have inner decoder: pass the data on (means inner content type is NOT data)
	 * no inner decoder: we have DATA in here: either call callback or store
	 */
	if (buflen != 0) {
	    /* there will be some output - need to make room for it */
	    /* allocate buffer from the heap */
	    buf = (unsigned char *)PORT_Alloc(buflen);
	    if (buf == NULL) {
		p7dcx->error = SEC_ERROR_NO_MEMORY;
		goto loser;
	    }
	}

	/*
	 * decrypt incoming data
	 * buf can still be NULL here (and buflen == 0) here if we don't expect
	 * any output (see above), but we still need to call NSS_CMSCipherContext_Decrypt to
	 * keep track of incoming data
	 */
	rv = NSS_CMSCipherContext_Decrypt(cinfo->privateInfo->ciphcx, buf, &outlen, buflen,
			       data, len, final);
	if (rv != SECSuccess) {
	    p7dcx->error = PORT_GetError();
	    goto loser;
	}

	PORT_Assert (final || outlen == buflen);

	/* swap decrypted data in */
	data = buf;
	len = outlen;
    }

    if (len == 0)
	goto done;		/* nothing more to do */

    /*
     * Update the running digests with plaintext bytes (if we need to).
     */
    if (cinfo->privateInfo && cinfo->privateInfo->digcx)
	NSS_CMSDigestContext_Update(cinfo->privateInfo->digcx, data, len);

    /* at this point, we have the plain decoded & decrypted data
    ** which is either more encoded DER (which we need to hand to the child
    ** decoder) or data we need to hand back to our caller
    */

    /* pass the content back to our caller or */
    /* feed our freshly decrypted and decoded data into child decoder */
    if (p7dcx->cb != NULL) {
	(*p7dcx->cb)(p7dcx->cb_arg, (const char *)data, len);
    }
#if 1
    else
#endif
    if (NSS_CMSContentInfo_GetContentTypeTag(cinfo) == SEC_OID_PKCS7_DATA) {
	/* store it in "inner" data item as well */
	/* find the DATA item in the encapsulated cinfo and store it there */
	NSSCMSDecoderData *decoderData =
				(NSSCMSDecoderData *)cinfo->content.pointer;
	SECItem *dataItem = &decoderData->data;

	offset = dataItem->len;
	if (dataItem->len+len > decoderData->totalBufferSize) {
	    int needLen = (dataItem->len+len) * 2;
	    dest = (unsigned char *)
				PORT_ArenaAlloc(p7dcx->cmsg->poolp, needLen);
	    if (dest == NULL) {
		p7dcx->error = SEC_ERROR_NO_MEMORY;
		goto loser;
	    }

	    if (dataItem->len) {
		PORT_Memcpy(dest, dataItem->data, dataItem->len);
	    }
	    decoderData->totalBufferSize = needLen;
	    dataItem->data = dest;
	}

	/* copy it in */
	PORT_Memcpy(dataItem->data + offset, data, len);
	dataItem->len += len;
    }

done:
loser:
    if (buf)
	PORT_Free (buf);
}

/*
 * nss_cms_decoder_update_filter - process ASN.1 data
 *
 * once we have set up a filter in nss_cms_decoder_notify(),
 * all data processed by the ASN.1 decoder is also passed through here.
 * we pass the content bytes (as opposed to length and tag bytes) on to
 * nss_cms_decoder_work_data().
 */
static void
nss_cms_decoder_update_filter (void *arg, const char *data, unsigned long len,
			  int depth, SEC_ASN1EncodingPart data_kind)
{
    NSSCMSDecoderContext *p7dcx;

    PORT_Assert (len);	/* paranoia */
    if (len == 0)
	return;

    p7dcx = (NSSCMSDecoderContext*)arg;

    p7dcx->saw_contents = PR_TRUE;

    /* pass on the content bytes only */
    if (data_kind == SEC_ASN1_Contents)
	nss_cms_decoder_work_data(p7dcx, (const unsigned char *) data, len,
	                          PR_FALSE);
}

/*
 * NSS_CMSDecoder_Start - set up decoding of a DER-encoded CMS message
 *
 * "poolp" - pointer to arena for message, or NULL if new pool should be created
 * "cb", "cb_arg" - callback function and argument for delivery of inner content
 * "pwfn", pwfn_arg" - callback function for getting token password
 * "decrypt_key_cb", "decrypt_key_cb_arg" - callback function for getting bulk key for encryptedData
 */
NSSCMSDecoderContext *
NSS_CMSDecoder_Start(PRArenaPool *poolp,
		      NSSCMSContentCallback cb, void *cb_arg,
		      PK11PasswordFunc pwfn, void *pwfn_arg,
		      NSSCMSGetDecryptKeyCallback decrypt_key_cb,
		      void *decrypt_key_cb_arg)
{
    NSSCMSDecoderContext *p7dcx;
    NSSCMSMessage *cmsg;

    cmsg = NSS_CMSMessage_Create(poolp);
    if (cmsg == NULL)
	return NULL;

    NSS_CMSMessage_SetEncodingParams(cmsg, pwfn, pwfn_arg, decrypt_key_cb,
                                     decrypt_key_cb_arg, NULL, NULL);

    p7dcx = PORT_ZNew(NSSCMSDecoderContext);
    if (p7dcx == NULL) {
	NSS_CMSMessage_Destroy(cmsg);
	return NULL;
    }

    p7dcx->dcx = SEC_ASN1DecoderStart(cmsg->poolp, cmsg, NSSCMSMessageTemplate);
    if (p7dcx->dcx == NULL) {
	PORT_Free (p7dcx);
	NSS_CMSMessage_Destroy(cmsg);
	return NULL;
    }

    SEC_ASN1DecoderSetNotifyProc (p7dcx->dcx, nss_cms_decoder_notify, p7dcx);

    p7dcx->cmsg = cmsg;
    p7dcx->type = SEC_OID_UNKNOWN;

    p7dcx->cb = cb;
    p7dcx->cb_arg = cb_arg;
    p7dcx->first_decoded = PR_FALSE;
    p7dcx->need_indefinite_finish = PR_FALSE;
    return p7dcx;
}

/*
 * NSS_CMSDecoder_Update - feed DER-encoded data to decoder
 */
SECStatus
NSS_CMSDecoder_Update(NSSCMSDecoderContext *p7dcx, const char *buf,
                      unsigned long len)
{
    SECStatus rv = SECSuccess;
    if (p7dcx->dcx != NULL && p7dcx->error == 0) {
    	/* if error is set already, don't bother */
	if ((p7dcx->type == SEC_OID_PKCS7_SIGNED_DATA)
		&& (p7dcx->first_decoded==PR_TRUE)
		&& (buf[0] == SEC_ASN1_INTEGER)) {
	    /* Microsoft Windows 2008 left out the Sequence wrapping in some
	     * of their kerberos replies. If we are here, we most likely are
	     * dealing with one of those replies. Supply the Sequence wrap
	     * as indefinite encoding (since we don't know the total length
	     * yet) */
	     static const char lbuf[2] =
		{ SEC_ASN1_SEQUENCE|SEC_ASN1_CONSTRUCTED, 0x80 };
	     rv = SEC_ASN1DecoderUpdate(p7dcx->dcx, lbuf, sizeof(lbuf));
	     if (rv != SECSuccess) {
		goto loser;
	    }
	    /* ok, we're going to need the indefinite finish when we are done */
	    p7dcx->need_indefinite_finish = PR_TRUE;
	}

	rv = SEC_ASN1DecoderUpdate(p7dcx->dcx, buf, len);
    }

loser:
    p7dcx->first_decoded = PR_FALSE;
    if (rv != SECSuccess) {
	p7dcx->error = PORT_GetError();
	PORT_Assert (p7dcx->error);
	if (p7dcx->error == 0)
	    p7dcx->error = -1;
    }

    if (p7dcx->error == 0)
	return SECSuccess;

    /* there has been a problem, let's finish the decoder */
    if (p7dcx->dcx != NULL) {
	(void) SEC_ASN1DecoderFinish (p7dcx->dcx);
	p7dcx->dcx = NULL;
    }
    PORT_SetError (p7dcx->error);

    return SECFailure;
}

/*
 * NSS_CMSDecoder_Cancel - stop decoding in case of error
 */
void
NSS_CMSDecoder_Cancel(NSSCMSDecoderContext *p7dcx)
{
    if (p7dcx->dcx != NULL)
	(void)SEC_ASN1DecoderFinish(p7dcx->dcx);
    NSS_CMSMessage_Destroy(p7dcx->cmsg);
    PORT_Free(p7dcx);
}

/*
 * NSS_CMSDecoder_Finish - mark the end of inner content and finish decoding
 */
NSSCMSMessage *
NSS_CMSDecoder_Finish(NSSCMSDecoderContext *p7dcx)
{
    NSSCMSMessage *cmsg;

    cmsg = p7dcx->cmsg;

    if (p7dcx->dcx == NULL ||
        SEC_ASN1DecoderFinish(p7dcx->dcx) != SECSuccess ||
	nss_cms_after_end(p7dcx) != SECSuccess)
    {
	NSS_CMSMessage_Destroy(cmsg);	/* get rid of pool if it's ours */
	cmsg = NULL;
    }

    PORT_Free(p7dcx);
    return cmsg;
}

NSSCMSMessage *
NSS_CMSMessage_CreateFromDER(SECItem *DERmessage,
		    NSSCMSContentCallback cb, void *cb_arg,
		    PK11PasswordFunc pwfn, void *pwfn_arg,
		    NSSCMSGetDecryptKeyCallback decrypt_key_cb,
		    void *decrypt_key_cb_arg)
{
    NSSCMSDecoderContext *p7dcx;

    /* first arg(poolp) == NULL => create our own pool */
    p7dcx = NSS_CMSDecoder_Start(NULL, cb, cb_arg, pwfn, pwfn_arg,
                                 decrypt_key_cb, decrypt_key_cb_arg);
    if (p7dcx == NULL)
	return NULL;
    NSS_CMSDecoder_Update(p7dcx, (char *)DERmessage->data, DERmessage->len);
    return NSS_CMSDecoder_Finish(p7dcx);
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TournamentTracker
{
    public partial class ResultsRecorderForm : Form
    {
        public string actionType = "Cancel";
        public int winningplayer;
        public int oneCP;
        public int twoCP;
        public int oneAP;
        public int twoAP;
        public ResultsRecorderForm()
        {
            InitializeComponent();

        }
        public ResultsRecorderForm(Pairing pair)
        {

            InitializeComponent();
            PlayerOneLabel.Text = pair.Player1.firstName + " " + pair.Player1.lastName;
            playerTwoLabel.Text = pair.Player2.firstName + " " + pair.Player2.lastName;
            factionOnelabel.Text = pair.Player1.faction;
            factionTwolabel.Text = pair.Player2.faction;
            oneCPnumericUpDown.Value = pair.OnePlayerCP;
            oneArmynumericUpDown.Value = pair.OnePlayerAP;
            twoCPnumericUpDown.Value = pair.TwoPlayerCP;
            twoArmynumericUpDown.Value = pair.TwoPlayerAP;
            if (pair.WinningPlayer == 0 || pair.WinningPlayer == 1)
            {
                oneWinnerRadioButton.Checked = true;
            }
            else
            {
                twoWinnerRadioButton.Checked = true;
            }
        }

        private void acceptButton_Click(object sender, EventArgs e)
        {
            if(Decimal.ToInt32(oneCPnumericUpDown.Value) == 0 && Decimal.ToInt32(oneArmynumericUpDown.Value) == 0 && Decimal.ToInt32(twoCPnumericUpDown.Value) == 0 && Decimal.ToInt32(twoArmynumericUpDown.Value) == 0)
            {
                DialogResult result = MessageBox.Show("Control Points and Army Points Are Currently 0. Is this correct?", "Confirmation", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    successfulResult();
                }
            }
            else
            {
                successfulResult();
            }

        }
        private void successfulResult()
        {
            actionType = "Accept";
            if (oneWinnerRadioButton.Checked)
            {
                winningplayer = 1;
            }
            else
            {
                winningplayer = 2;
            }
            oneCP = Decimal.ToInt32(oneCPnumericUpDown.Value);
            oneAP = Decimal.ToInt32(oneArmynumericUpDown.Value);
            twoCP = Decimal.ToInt32(twoCPnumericUpDown.Value);
            twoAP = Decimal.ToInt32(twoArmynumericUpDown.Value);
            // thisPair.Finished = true;
            this.Close();
        }
        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ResultsRecorderForm_Load(object sender, EventArgs e)
        {

        }

        private void oneCPnumericUpDown_Enter(object sender, EventArgs e)
        {
            oneCPnumericUpDown.Select(0, 3);
        }

        private void twoCPnumericUpDown_Enter(object sender, EventArgs e)
        {
            twoCPnumericUpDown.Select(0, 3);
        }

        private void oneArmynumericUpDown_Enter(object sender, EventArgs e)
        {
            oneArmynumericUpDown.Select(0, 3);
        }

        private void twoArmynumericUpDown_Enter(object sender, EventArgs e)
        {
            twoArmynumericUpDown.Select(0, 3);
        }
    }
}


text:
FROM golang:1.7.6
MAINTAINER Nicolas Ruflin <ruflin@elastic.co>

RUN set -x && \
    apt-get update && \
    apt-get install -y --no-install-recommends \
         netcat python-pip virtualenv && \
    apt-get clean

# Setup work environment
ENV FILEBEAT_PATH /go/src/github.com/elastic/beats/filebeat

RUN mkdir -p $FILEBEAT_PATH/build/coverage
WORKDIR $FILEBEAT_PATH


text:
package org.broadinstitute.hellbender.tools.picard.sam;

import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMProgramRecord;
import htsjdk.samtools.SamPairUtil;
import org.broadinstitute.hellbender.cmdline.Argument;
import org.broadinstitute.hellbender.cmdline.CommandLineProgramProperties;
import org.broadinstitute.hellbender.cmdline.PicardCommandLineProgram;
import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions;
import org.broadinstitute.hellbender.cmdline.programgroups.ReadProgramGroup;
import org.broadinstitute.hellbender.exceptions.GATKException;
import org.broadinstitute.hellbender.utils.read.mergealignment.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * A command-line tool to merge BAM/SAM alignment info from a third-party aligner with the data in an
 * unmapped BAM file, producing a third BAM file that has alignment data and all the additional data
 * from the unmapped BAM
 *
 * @author ktibbett@broadinstitute.org
 */
@CommandLineProgramProperties(
        summary = "Merges alignment data from a SAM or BAM " +
                "file with additional data stored in an unmapped BAM file and produces a third SAM " +
                "or BAM file of aligned and unaligned reads. The purpose is to use information from the " +
                "unmapped BAM to fix up aligner output, so that the resulting file is valid for use by other " +
                "Picard programs. For simple BAM file merges, use MergeSamFiles. NOTE that MergeBamAlignment expects to " +
                "find a sequence dictionary in the same directory as REFERENCE_SEQUENCE and expects it " +
                "to have the same base name as the reference fasta except with the extension '.dict'",
        oneLineSummary = "Merges alignment data from a SAM or BAM with data in an unmapped BAM file",
        programGroup = ReadProgramGroup.class
)
public final class MergeBamAlignment extends PicardCommandLineProgram {

    @Argument(shortName = "UNMAPPED",
            doc = "Original SAM or BAM file of unmapped reads, which must be in queryname order.")
    public File UNMAPPED_BAM;

    @Argument(shortName = "ALIGNED",
            doc = "SAM or BAM file(s) with alignment data.",
            mutex = {"READ1_ALIGNED_BAM", "READ2_ALIGNED_BAM"},
            optional = true)
    public List<File> ALIGNED_BAM;

    @Argument(shortName = "R1_ALIGNED",
            doc = "SAM or BAM file(s) with alignment data from the first read of a pair.",
            mutex = {"ALIGNED_BAM"},
            optional = true)
    public List<File> READ1_ALIGNED_BAM;

    @Argument(shortName = "R2_ALIGNED",
            doc = "SAM or BAM file(s) with alignment data from the second read of a pair.",
            mutex = {"ALIGNED_BAM"},
            optional = true)
    public List<File> READ2_ALIGNED_BAM;

    @Argument(shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME,
            doc = "Merged SAM or BAM file to write to.")
    public File OUTPUT;

    @Argument(shortName = StandardArgumentDefinitions.PROGRAM_RECORD_ID_SHORT_NAME,
            doc = "The program group ID of the aligner (if not supplied by the aligned file).",
            optional = true)
    public String PROGRAM_RECORD_ID;

    @Argument(shortName = "PG_VERSION",
            doc = "The version of the program group (if not supplied by the aligned file).",
            optional = true)
    public String PROGRAM_GROUP_VERSION;

    @Argument(shortName = "PG_COMMAND",
            doc = "The command line of the program group (if not supplied by the aligned file).",
            optional = true)
    public String PROGRAM_GROUP_COMMAND_LINE;

    @Argument(shortName = "PG_NAME",
            doc = "The name of the program group (if not supplied by the aligned file).",
            optional = true)
    public String PROGRAM_GROUP_NAME;

    @Argument(doc = "Whether to clip adapters where identified.")
    public boolean CLIP_ADAPTERS = true;

    @Argument(doc = "Whether the lane is bisulfite sequence (used when caculating the NM tag).")
    public boolean IS_BISULFITE_SEQUENCE = false;

    @Argument(doc = "Whether to output only aligned reads.  ")
    public boolean ALIGNED_READS_ONLY = false;

    @Argument(doc = "The maximum number of insertions or deletions permitted for an alignment to be " +
            "included. Alignments with more than this many insertions or deletions will be ignored. " +
            "Set to -1 to allow any number of insertions or deletions.",
            shortName = "MAX_GAPS")
    public int MAX_INSERTIONS_OR_DELETIONS = 1;

    @Argument(doc = "Reserved alignment attributes (tags starting with X, Y, or Z) that should be " +
            "brought over from the alignment data when merging.",
             optional = true)
    public List<String> ATTRIBUTES_TO_RETAIN = new ArrayList<>();

    @Argument(doc = "Attributes from the alignment record that should be removed when merging." +
            "  This overrides ATTRIBUTES_TO_RETAIN if they share common tags.",
            optional = true)
    public List<String> ATTRIBUTES_TO_REMOVE = new ArrayList<>();

    @Argument(shortName = "R1_TRIM",
            doc = "The number of bases trimmed from the beginning of read 1 prior to alignment")
    public int READ1_TRIM = 0;

    @Argument(shortName = "R2_TRIM",
            doc = "The number of bases trimmed from the beginning of read 2 prior to alignment")
    public int READ2_TRIM = 0;

    @Argument(shortName = "ORIENTATIONS",
            doc = "The expected orientation of proper read pairs.",
            optional = true)
    public List<SamPairUtil.PairOrientation> EXPECTED_ORIENTATIONS;

    @Argument(doc = "Use the aligner's idea of what a proper pair is rather than computing in this program.")
    public boolean ALIGNER_PROPER_PAIR_FLAGS = false;

    @Argument(shortName = StandardArgumentDefinitions.SORT_ORDER_SHORT_NAME,
            doc = "The order in which the merged reads should be output.")
    public SAMFileHeader.SortOrder SORT_ORDER = SAMFileHeader.SortOrder.coordinate;

    @Argument(doc = "Strategy for selecting primary alignment when the aligner has provided more than one alignment " +
            "for a pair or fragment, and none are marked as primary, more than one is marked as primary, or the primary " +
            "alignment is filtered out for some reason. " +
            "BestMapq expects that multiple alignments will be correlated with HI tag, and prefers the pair of " +
            "alignments with the largest MAPQ, in the absence of a primary selected by the aligner. " +
            "EarliestFragment prefers the alignment which maps the earliest base in the read. Note that EarliestFragment " +
            "may not be used for paired reads. " +
            "BestEndMapq is appropriate for cases in which the aligner is not pair-aware, and does not output the HI tag. " +
            "It simply picks the alignment for each end with the highest MAPQ, and makes those alignments primary, regardless " +
            "of whether the two alignments make sense together." +
            "MostDistant is also for a non-pair-aware aligner, and picks the alignment pair with the largest insert size. " +
            "If all alignments would be chimeric, it picks the alignments for each end with the best MAPQ.  For all algorithms, " +
            "ties are resolved arbitrarily.")
    public PrimaryAlignmentStrategy PRIMARY_ALIGNMENT_STRATEGY = PrimaryAlignmentStrategy.BestMapq;

    @Argument(doc = "For paired reads, soft clip the 3' end of each read if necessary so that it does not extend past the 5' end of its mate.")
    public boolean CLIP_OVERLAPPING_READS = true;

    @Argument(doc = "If false, do not write secondary alignments to output.")
    public boolean INCLUDE_SECONDARY_ALIGNMENTS = true;

    @Argument(shortName = "MC", optional = true, doc = "Adds the mate CIGAR tag (MC) if true, does not if false.")
    public Boolean ADD_MATE_CIGAR = true;

    /**
     * Mechanism to bridge between command line option and PrimaryAlignmentSelectionStrategy implementation.
     */
    enum PrimaryAlignmentStrategy {
        BestMapq(BestMapqPrimaryAlignmentSelectionStrategy.class),
        EarliestFragment(EarliestFragmentPrimaryAlignmentSelectionStrategy.class),
        BestEndMapq(BestEndMapqPrimaryAlignmentStrategy.class),
        MostDistant(MostDistantPrimaryAlignmentSelectionStrategy.class);

        private final Class<? extends PrimaryAlignmentSelectionStrategy> clazz;

        PrimaryAlignmentStrategy(final Class<? extends PrimaryAlignmentSelectionStrategy> clazz) {
            this.clazz = clazz;
        }

        PrimaryAlignmentSelectionStrategy newInstance() {
            try {
                return clazz.newInstance();
            } catch (Exception e) {
                throw new GATKException("Trouble instantiating " + clazz.getName(), e);
            }
        }
    }

    @Override
    protected Object doWork() {
        // Check the files are readable/writable
        SAMProgramRecord prod = null;
        if (PROGRAM_RECORD_ID != null) {
            prod = new SAMProgramRecord(PROGRAM_RECORD_ID);
            prod.setProgramVersion(PROGRAM_GROUP_VERSION);
            prod.setCommandLine(PROGRAM_GROUP_COMMAND_LINE);
            prod.setProgramName(PROGRAM_GROUP_NAME);
        }
        if (EXPECTED_ORIENTATIONS == null || EXPECTED_ORIENTATIONS.isEmpty()) {
            EXPECTED_ORIENTATIONS = Arrays.asList(SamPairUtil.PairOrientation.FR);
        }

        final SamAlignmentMerger merger = new SamAlignmentMerger(UNMAPPED_BAM, OUTPUT,
                REFERENCE_SEQUENCE, prod, CLIP_ADAPTERS, IS_BISULFITE_SEQUENCE,
                ALIGNED_READS_ONLY, ALIGNED_BAM, MAX_INSERTIONS_OR_DELETIONS,
                ATTRIBUTES_TO_RETAIN, ATTRIBUTES_TO_REMOVE, READ1_TRIM, READ2_TRIM,
                READ1_ALIGNED_BAM, READ2_ALIGNED_BAM, EXPECTED_ORIENTATIONS, SORT_ORDER,
                PRIMARY_ALIGNMENT_STRATEGY.newInstance(), ADD_MATE_CIGAR);
        merger.setClipOverlappingReads(CLIP_OVERLAPPING_READS);
        merger.setKeepAlignerProperPairFlags(ALIGNER_PROPER_PAIR_FLAGS);
        merger.setIncludeSecondaryAlignments(INCLUDE_SECONDARY_ALIGNMENTS);
        merger.mergeAlignment(REFERENCE_SEQUENCE);
        merger.close();

        return null;
    }

    /**
     * Put any custom command-line validation in an override of this method.
     * clp is initialized at this point and can be used to print usage and access argv.
     * Any options set by command-line parser can be validated.
     *
     * @return null if command line is valid.  If command line is invalid, returns
     * an array of error messages to be written to the appropriate place.
     */
    protected String[] customCommandLineValidation() {

        if ((PROGRAM_RECORD_ID != null || PROGRAM_GROUP_VERSION != null ||
                PROGRAM_GROUP_COMMAND_LINE != null) &&
                (PROGRAM_RECORD_ID == null || PROGRAM_GROUP_VERSION == null ||
                        PROGRAM_GROUP_COMMAND_LINE == null)) {

            return new String[]{"PROGRAM_RECORD_ID, PROGRAM_GROUP_VERSION, and " +
                    "PROGRAM_GROUP_COMMAND_LINE must all be supplied or none should " +
                    "be included."};
        }

        final boolean r1sExist = READ1_ALIGNED_BAM != null && READ1_ALIGNED_BAM.size() > 0;
        final boolean r2sExist = READ2_ALIGNED_BAM != null && READ2_ALIGNED_BAM.size() > 0;
        if ((r1sExist && !r2sExist) || (r2sExist && !r1sExist)) {
            return new String[]{"READ1_ALIGNED_BAM and READ2_ALIGNED_BAM " +
                    "must both be supplied or neither should be included.  For " +
                    "single-end read use ALIGNED_BAM."};
        }
        if (ALIGNED_BAM == null || ALIGNED_BAM.size() == 0 && !(r1sExist && r2sExist)) {
            return new String[]{"Either ALIGNED_BAM or the combination of " +
                    "READ1_ALIGNED_BAM and READ2_ALIGNED_BAM must be supplied."};

        }

        return null;
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>P-Index</title>
<meta name="date" content="2018-10-31">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E G H I N O P R S T U V W

P

performClick() - Method in class de.mrapp.android.preference.activity.NavigationPreference

Performs a click on the preference.

PreferenceActivity - Class in de.mrapp.android.preference.activity

An activity, which provides a navigation for accessing preferences, which are grouped as
 different sections.

PreferenceActivity() - Constructor for class de.mrapp.android.preference.activity.PreferenceActivity

PreferenceAdapter - Class in de.mrapp.android.preference.activity.adapter

A recycler view adapter, which extends the class PreferenceGroupAdapter in order to modify the
 appearance of preferences.

PreferenceAdapter(PreferenceScreen) - Constructor for class de.mrapp.android.preference.activity.adapter.PreferenceAdapter

Creates a new recycler view adapter, which extends the class PreferenceGroupAdapter in order
 to modify the appearance of preferences.

PreferenceFragment - Class in de.mrapp.android.preference.activity

A fragment, which allows to show multiple preferences.

PreferenceFragment() - Constructor for class de.mrapp.android.preference.activity.PreferenceFragment

PreferenceFragmentListener - Interface in de.mrapp.android.preference.activity

Defines the interface, a class, which should be notified when the currently shown preference
 fragment of a PreferenceActivity has been changed, must implement.

A C D E G H I N O P R S T U V W

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
from gevent import monkey
monkey.patch_socket()

from gevent.pool import Pool
import urlfetch

pool = Pool(size=5)
urls = ('http://www.google.com', 'http://www.yahoo.com',
        'http://www.blogger.com', 'http://www.python.org',
        'http://sourceforge.net', 'http://www.ubuntu.com',
        'http://www.readwriteweb.com', 'http://gigaom.com',
        'http://www.wired.com')

tasks = pool.map(urlfetch.get, urls)


text:
from ..Foundation import NSObject

class NSHTTPURLResponseInternalSyntheticProvider(NSObject.NSObjectSyntheticProvider):
    """
    Class representing NSHTTPURLResponseInternal.
    """
    def __init__(self, value_obj, internal_dict):
        super(NSHTTPURLResponseInternalSyntheticProvider, self).__init__(value_obj, internal_dict)
        self.type_name = "NSHTTPURLResponseInternal"


text:
#define LOG_TAG "misc"

//
// Miscellaneous utility functions.
//
#include "config.h"

#include "utils/misc.h"
#include "utils/Log.h"

#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <stdio.h>

#if defined(HAVE_PTHREADS)
# include <pthread.h>
#endif

#include "utils/Vector.h"

using namespace tangmai;

namespace tangmai {

/*
 * Get a file's type.
 */
FileType getFileType(const char* fileName)
{
    struct stat sb;

    if (stat(fileName, &sb) < 0) {
        if (errno == ENOENT || errno == ENOTDIR)
            return kFileTypeNonexistent;
        else {
            fprintf(stderr, "getFileType got errno=%d on '%s'\n",
                errno, fileName);
            return kFileTypeUnknown;
        }
    } else {
        if (S_ISREG(sb.st_mode))
            return kFileTypeRegular;
        else if (S_ISDIR(sb.st_mode))
            return kFileTypeDirectory;
        else if (S_ISCHR(sb.st_mode))
            return kFileTypeCharDev;
        else if (S_ISBLK(sb.st_mode))
            return kFileTypeBlockDev;
        else if (S_ISFIFO(sb.st_mode))
            return kFileTypeFifo;
#ifdef HAVE_SYMLINKS
        else if (S_ISLNK(sb.st_mode))
            return kFileTypeSymlink;
        else if (S_ISSOCK(sb.st_mode))
            return kFileTypeSocket;
#endif
        else
            return kFileTypeUnknown;
    }
}

/*
 * Get a file's modification date.
 */
time_t getFileModDate(const char* fileName)
{
    struct stat sb;

    if (stat(fileName, &sb) < 0)
        return (time_t) -1;

    return sb.st_mtime;
}

struct sysprop_change_callback_info {
    sysprop_change_callback callback;
    int priority;
};

#if defined(HAVE_PTHREADS)
static pthread_mutex_t gSyspropMutex = PTHREAD_MUTEX_INITIALIZER;
static Vector<sysprop_change_callback_info>* gSyspropList = NULL;
#endif

void add_sysprop_change_callback(sysprop_change_callback cb, int priority) {
#if defined(HAVE_PTHREADS)
    pthread_mutex_lock(&gSyspropMutex);
    if (gSyspropList == NULL) {
        gSyspropList = new Vector<sysprop_change_callback_info>();
    }
    sysprop_change_callback_info info;
    info.callback = cb;
    info.priority = priority;
    bool added = false;
    for (size_t i=0; i<gSyspropList->size(); i++) {
        if (priority >= gSyspropList->itemAt(i).priority) {
            gSyspropList->insertAt(info, i);
            added = true;
            break;
        }
    }
    if (!added) {
        gSyspropList->add(info);
    }
    pthread_mutex_unlock(&gSyspropMutex);
#endif
}

void report_sysprop_change() {
#if defined(HAVE_PTHREADS)
    pthread_mutex_lock(&gSyspropMutex);
    Vector<sysprop_change_callback_info> listeners;
    if (gSyspropList != NULL) {
        listeners = *gSyspropList;
    }
    pthread_mutex_unlock(&gSyspropMutex);

    //ALOGI("Reporting sysprop change to %d listeners", listeners.size());
    for (size_t i=0; i<listeners.size(); i++) {
        listeners[i].callback();
    }
#endif
}

}; // namespace tangmai


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Conference extends Application {

    function __construct() {
        parent::__construct();
    }

    //-------------------------------------------------------------
    //  The normal pages
    //-------------------------------------------------------------

    function index() {
        $this->data['pagebody'] = 'conference';    // this is the view we want shown
        // build the list of authors, to pass on to our view
        $source = $this->conferences->all();
        $teams = array();
        foreach ($source as $record) {
            $teams[] =  array('id' => $record['id'], 'who' => $record['who'], 'wins' => $record['wins'],
                'losses'=>$record['losses'],'ties' => $record['ties'],
                'home'=> $record['home'], 'road'=>$record['road'], 'streak'=> $record['streak']);

        }
        $this->data['teams'] = $teams;

        $this->render();
    }

}


text:
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.ToolBox.AlgoSeekFuturesConverter;
using QuantConnect.ToolBox.AlgoSeekOptionsConverter;
using QuantConnect.ToolBox.AlphaVantageDownloader;
using QuantConnect.ToolBox.BitfinexDownloader;
using QuantConnect.ToolBox.CoarseUniverseGenerator;
using QuantConnect.ToolBox.CoinApiDataConverter;
using QuantConnect.ToolBox.CryptoiqDownloader;
using QuantConnect.ToolBox.DukascopyDownloader;
using QuantConnect.ToolBox.GDAXDownloader;
using QuantConnect.ToolBox.IEX;
using QuantConnect.ToolBox.IQFeedDownloader;
using QuantConnect.ToolBox.IVolatilityEquityConverter;
using QuantConnect.ToolBox.KaikoDataConverter;
using QuantConnect.ToolBox.KrakenDownloader;
using QuantConnect.ToolBox.NseMarketDataConverter;
using QuantConnect.ToolBox.OandaDownloader;
using QuantConnect.ToolBox.Polygon;
using QuantConnect.ToolBox.QuantQuoteConverter;
using QuantConnect.ToolBox.RandomDataGenerator;
using QuantConnect.ToolBox.YahooDownloader;
using QuantConnect.Util;
using System;
using System.IO;
using static QuantConnect.Configuration.ApplicationParser;

namespace QuantConnect.ToolBox
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Log.DebuggingEnabled = Config.GetBool("debug-mode");
            var destinationDir = Config.Get("results-destination-folder");
            if (!string.IsNullOrEmpty(destinationDir))
            {
                Directory.CreateDirectory(destinationDir);
                Log.FilePath = Path.Combine(destinationDir, "log.txt");
            }
            Log.LogHandler = Composer.Instance.GetExportedValueByTypeName<ILogHandler>(Config.Get("log-handler", "CompositeLogHandler"));

            var optionsObject = ToolboxArgumentParser.ParseArguments(args);
            if (optionsObject.Count == 0)
            {
                PrintMessageAndExit();
            }

            var dataProvider
                = Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider", "DefaultDataProvider"));
            var mapFileProvider
                = Composer.Instance.GetExportedValueByTypeName<IMapFileProvider>(Config.Get("map-file-provider", "LocalDiskMapFileProvider"));
            var factorFileProvider
                = Composer.Instance.GetExportedValueByTypeName<IFactorFileProvider>(Config.Get("factor-file-provider", "LocalDiskFactorFileProvider"));

            mapFileProvider.Initialize(dataProvider);
            factorFileProvider.Initialize(mapFileProvider, dataProvider);

            var targetApp = GetParameterOrExit(optionsObject, "app").ToLowerInvariant();
            if (targetApp.Contains("download") || targetApp.EndsWith("dl"))
            {
                var fromDate = Parse.DateTimeExact(GetParameterOrExit(optionsObject, "from-date"), "yyyyMMdd-HH:mm:ss");
                var resolution = optionsObject.ContainsKey("resolution") ? optionsObject["resolution"].ToString() : "";
                var market = optionsObject.ContainsKey("market") ? optionsObject["market"].ToString() : "";
                var securityType = optionsObject.ContainsKey("security-type") ? optionsObject["security-type"].ToString() : "";
                var tickers = ToolboxArgumentParser.GetTickers(optionsObject);
                var toDate = optionsObject.ContainsKey("to-date")
                    ? Parse.DateTimeExact(optionsObject["to-date"].ToString(), "yyyyMMdd-HH:mm:ss")
                    : DateTime.UtcNow;
                switch (targetApp)
                {
                    case "gdaxdl":
                    case "gdaxdownloader":
                        GDAXDownloaderProgram.GDAXDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "cdl":
                    case "cryptoiqdownloader":
                        CryptoiqDownloaderProgram.CryptoiqDownloader(tickers, GetParameterOrExit(optionsObject, "exchange"), fromDate, toDate);
                        break;
                    case "ddl":
                    case "dukascopydownloader":
                        DukascopyDownloaderProgram.DukascopyDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "iexdl":
                    case "iexdownloader":
                        IEXDownloaderProgram.IEXDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "iqfdl":
                    case "iqfeeddownloader":
                        IQFeedDownloaderProgram.IQFeedDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "kdl":
                    case "krakendownloader":
                        KrakenDownloaderProgram.KrakenDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "odl":
                    case "oandadownloader":
                        OandaDownloaderProgram.OandaDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "qbdl":
                    case "ydl":
                    case "yahoodownloader":
                        YahooDownloaderProgram.YahooDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "bfxdl":
                    case "bitfinexdownloader":
                        BitfinexDownloaderProgram.BitfinexDownloader(tickers, resolution, fromDate, toDate);
                        break;
                    case "pdl":
                    case "polygondownloader":
                        PolygonDownloaderProgram.PolygonDownloader(
                            tickers,
                            GetParameterOrExit(optionsObject, "security-type"),
                            GetParameterOrExit(optionsObject, "market"),
                            resolution,
                            fromDate,
                            toDate);
                        break;

                    case "avdl":
                    case "alphavantagedownloader":
                        AlphaVantageDownloaderProgram.AlphaVantageDownloader(
                            tickers,
                            resolution,
                            fromDate,
                            toDate,
                            GetParameterOrExit(optionsObject, "api-key")
                        );
                        break;

                    default:
                        PrintMessageAndExit(1, "ERROR: Unrecognized --app value");
                        break;
                }
            }
            else if (targetApp.Contains("updater") || targetApp.EndsWith("spu"))
            {
                switch (targetApp)
                {
                    case "gdaxspu":
                    case "gdaxsymbolpropertiesupdater":
                        GDAXDownloaderProgram.ExchangeInfoDownloader();
                        break;
                    case "bfxspu":
                    case "bitfinexsymbolpropertiesupdater":
                        BitfinexDownloaderProgram.ExchangeInfoDownloader();
                        break;
                    default:
                        PrintMessageAndExit(1, "ERROR: Unrecognized --app value");
                        break;
                }
            }
            else
            {
                switch (targetApp)
                {
                    case "asfc":
                    case "algoseekfuturesconverter":
                        AlgoSeekFuturesProgram.AlgoSeekFuturesConverter(GetParameterOrExit(optionsObject, "date"));
                        break;
                    case "asoc":
                    case "algoseekoptionsconverter":
                        AlgoSeekOptionsConverterProgram.AlgoSeekOptionsConverter(GetParameterOrExit(optionsObject, "date"));
                        break;
                    case "ivec":
                    case "ivolatilityequityconverter":
                        IVolatilityEquityConverterProgram.IVolatilityEquityConverter(GetParameterOrExit(optionsObject, "source-dir"),
                                                                                GetParameterOrExit(optionsObject, "source-meta-dir"),
                                                                                GetParameterOrExit(optionsObject, "destination-dir"),
                                                                                GetParameterOrExit(optionsObject, "resolution"));
                        break;
                    case "kdc":
                    case "kaikodataconverter":
                        KaikoDataConverterProgram.KaikoDataConverter(GetParameterOrExit(optionsObject, "source-dir"),
                                                                     GetParameterOrExit(optionsObject, "date"),
                                                                     GetParameterOrDefault(optionsObject, "exchange", string.Empty));
                        break;
                    case "cadc":
                    case "coinapidataconverter":
                        CoinApiDataConverterProgram.CoinApiDataProgram(
                            GetParameterOrExit(optionsObject, "date"),
                            GetParameterOrExit(optionsObject, "source-dir"),
                            GetParameterOrExit(optionsObject, "destination-dir"),
                            GetParameterOrDefault(optionsObject, "market", null));
                        break;
                    case "nmdc":
                    case "nsemarketdataconverter":
                        NseMarketDataConverterProgram.NseMarketDataConverter(GetParameterOrExit(optionsObject, "source-dir"),
                                                                             GetParameterOrExit(optionsObject, "destination-dir"));
                        break;
                    case "qqc":
                    case "quantquoteconverter":
                        QuantQuoteConverterProgram.QuantQuoteConverter(GetParameterOrExit(optionsObject, "destination-dir"),
                                                                       GetParameterOrExit(optionsObject, "source-dir"),
                                                                       GetParameterOrExit(optionsObject, "resolution"));
                        break;
                    case "cug":
                    case "coarseuniversegenerator":
                        CoarseUniverseGeneratorProgram.CoarseUniverseGenerator();
                        break;
                    case "rdg":
                    case "randomdatagenerator":
                        var tickers = ToolboxArgumentParser.GetTickers(optionsObject);
                        RandomDataGeneratorProgram.RandomDataGenerator(
                            GetParameterOrExit(optionsObject, "start"),
                            GetParameterOrExit(optionsObject, "end"),
                            GetParameterOrExit(optionsObject, "symbol-count"),
                            GetParameterOrDefault(optionsObject, "market", null),
                            GetParameterOrDefault(optionsObject, "security-type", "Equity"),
                            GetParameterOrDefault(optionsObject, "resolution", "Minute"),
                            GetParameterOrDefault(optionsObject, "data-density", "Dense"),
                            GetParameterOrDefault(optionsObject, "include-coarse", "true"),
                            GetParameterOrDefault(optionsObject, "quote-trade-ratio", "1"),
                            GetParameterOrDefault(optionsObject, "random-seed", null),
                            GetParameterOrDefault(optionsObject, "ipo-percentage", "5.0"),
                            GetParameterOrDefault(optionsObject, "rename-percentage", "30.0"),
                            GetParameterOrDefault(optionsObject, "splits-percentage", "15.0"),
                            GetParameterOrDefault(optionsObject, "dividends-percentage", "60.0"),
                            GetParameterOrDefault(optionsObject, "dividend-every-quarter-percentage", "30.0"),
                            GetParameterOrDefault(optionsObject, "option-price-engine", "BaroneAdesiWhaleyApproximationEngine"),
                            GetParameterOrDefault(optionsObject, "volatility-model-resolution", "Daily"),
                            GetParameterOrDefault(optionsObject, "chain-symbol-count", "1"),
                            tickers
                        );
                        break;

                    default:
                        PrintMessageAndExit(1, "ERROR: Unrecognized --app value");
                        break;
                }
            }
        }
    }
}


text:
'use strict'; /*jslint node: true, es5: true, indent: 2 */
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'sequence-labeling');

var textDocumentSchema = new mongoose.Schema({
  text: { 'type': String, 'default': ''},
  created: { 'type': Date, 'default': Date.now },
  annotations: [{
    start: Number,
    end: Number,
    color: String,
    text: String,
    tag: String
  }],
});

exports.TextDocument = db.model('textDocument', textDocumentSchema);


text:
#ifndef NUMPP_STRUCTURES_MATRICES_SPARSE_HPP_
#define NUMPP_STRUCTURES_MATRICES_SPARSE_HPP_

/**
  \defgroup numpp_structures_matrices_sparse Sparse
  \ingroup numpp_structures_matrices
  \brief Module containg sparse matrix implementations

  \warning Warnings about compilation times do not apply to blocked and nested_block classes
  as those are runtime only

*/
#include"./sparse/sparse_block.hpp"
#include"./sparse/sparse_block_nested.hpp"

#endif


text:
<?php

namespace Rocketeer\Services\Config;

use Rocketeer\TestCases\BaseTestCase;
use Symfony\Component\Config\Definition\Processor;

class ConfigurationDefinitionTest extends BaseTestCase
{
    /**
     * @var Processor
     */
    protected $processor;

    /**
     * Setup the tests.
     */
    public function setUp()
    {
        parent::setUp();

        $this->processor = new Processor();
    }

    public function testCanUnifyFlagServerDeclaration()
    {
        $processed = $this->processConfiguration([
            'config' => [
                'application_name' => 'foobar',
                'connections' => [
                    'production' => [
                        'host' => 'foo.com',
                    ],
                ],
            ],
        ]);

        $connection = $processed['config']['connections']['production'];

        $this->assertArrayHasKey('servers', $connection);
        $this->assertEquals('foo.com', $connection['servers'][0]['host']);
    }

    public function testCanUnifyUnKeyedServerDeclaration()
    {
        $processed = $this->processConfiguration([
            'config' => [
                'application_name' => 'foobar',
                'connections' => [
                    'production' => [
                        [
                            'host' => 'foo.com',
                        ],
                        [
                            'host' => 'bar.com',
                        ],
                    ],
                ],
            ],
        ]);

        $connection = $processed['config']['connections']['production'];

        $this->assertArrayHasKey('servers', $connection);
        $this->assertEquals('foo.com', $connection['servers'][0]['host']);
        $this->assertEquals('bar.com', $connection['servers'][1]['host']);
    }

    public function testCanUnifyFullServerDeclaration()
    {
        $processed = $this->processConfiguration([
            'config' => [
                'application_name' => 'foobar',
                'connections' => [
                    'production' => [
                        'servers' => [
                            [
                                'host' => 'foo.com',
                            ],
                            [
                                'host' => 'bar.com',
                            ],
                        ],
                    ],
                ],
            ],
        ]);

        $connection = $processed['config']['connections']['production'];

        $this->assertArrayHasKey('servers', $connection);
        $this->assertEquals('foo.com', $connection['servers'][0]['host']);
        $this->assertEquals('bar.com', $connection['servers'][1]['host']);
    }

    public function testCanProperlyMergePaths()
    {
        $processed = $this->processConfiguration(
            [
                'paths' => [
                    'php' => '/foo/php',
                    'composer' => '/foo/composer',
                    'foo' => '/bar',
                ],
            ],
            [
                'paths' => [
                    'php' => '/bar/php',
                    'bar' => '/bar/baz',
                ],
            ]
        );

        $this->assertEquals([
            'php' => '/bar/php',
            'composer' => '/foo/composer',
            'foo' => '/bar',
            'bar' => '/bar/baz',
        ], $processed['paths']);
    }

    public function testCanConfigureEventInHooks()
    {
        $configuration = $this->processConfiguration([
            'hooks' => [
                'events' => [
                    'before' => [
                        'deploy' => ['echo "foobar"'],
                        'foo' => ['bar'],
                        'baz' => [
                            function ($task) {
                                $task->run('qux');
                            },
                        ],
                    ],
                ],
            ],
        ]);

        $this->assertArrayHasKey('deploy', $configuration['hooks']['events']['before']);
        $this->assertEquals(['echo "foobar"'], $configuration['hooks']['events']['before']['deploy']);
    }

    /**
     * @param array[] ...$config
     *
     * @return array
     */
    protected function processConfiguration(...$config)
    {
        array_unshift($config, [
            'hooks' => [
                'events' => [
                    'before' => [],
                ],
            ],
        ]);

        $processed = $this->processor->processConfiguration(new ConfigurationDefinition(), $config);

        return $processed;
    }
}


text:
{-# LANGUAGE RecordWildCards, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-}
module Aws.SimpleDb.Commands.PutAttributes
where

import           Aws.Response
import           Aws.Signature
import           Aws.SimpleDb.Info
import           Aws.SimpleDb.Metadata
import           Aws.SimpleDb.Model
import           Aws.SimpleDb.Query
import           Aws.SimpleDb.Response
import           Aws.Transaction
import           Aws.Util
import qualified Data.Text             as T
import qualified Data.Text.Encoding    as T

data PutAttributes
    = PutAttributes {
        paItemName :: T.Text
      , paAttributes :: [Attribute SetAttribute]
      , paExpected :: [Attribute ExpectedAttribute]
      , paDomainName :: T.Text
      }
    deriving (Show)

data PutAttributesResponse
    = PutAttributesResponse
    deriving (Show)

putAttributes :: T.Text -> [Attribute SetAttribute] -> T.Text -> PutAttributes
putAttributes item attributes domain = PutAttributes {
                                         paItemName = item
                                       , paAttributes = attributes
                                       , paExpected = []
                                       , paDomainName = domain
                                       }

instance SignQuery PutAttributes where
    type Info PutAttributes = SdbInfo
    signQuery PutAttributes{..}
        = sdbSignQuery $
            [("Action", "PutAttributes"), ("ItemName", T.encodeUtf8 paItemName), ("DomainName", T.encodeUtf8 paDomainName)] ++
            queryList (attributeQuery setAttributeQuery) "Attribute" paAttributes ++
            queryList (attributeQuery expectedAttributeQuery) "Expected" paExpected

instance ResponseConsumer r PutAttributesResponse where
    type ResponseMetadata PutAttributesResponse = SdbMetadata
    responseConsumer _ = sdbResponseConsumer $ sdbCheckResponseType PutAttributesResponse "PutAttributesResponse"

instance Transaction PutAttributes PutAttributesResponse