text:
<?php
namespace DevelSuite\mail;

use DevelSuite\config\dsConfig;

class dsMailerTest extends \PHPUnit_Framework_TestCase {
	public function setUp() {
		// transporttypes available: smtp, sendmail, mail
		dsConfig::write('mailing.default.sender', array("info@develman.de" => "Develman.de"));
		dsConfig::write('mailing.transport', "smtp");
		dsConfig::write('mailing.smtp.hostname', "smtp.develman.de");
		dsConfig::write('mailing.smtp.username', "m0228c6e");
		dsConfig::write('mailing.smtp.password', "3#bofh7g");
	}

	public function testSendmail() {
		$message = \Swift_Message::newInstance("Test - DevelSuite");
		$message->setTo("georg@develman.de");

		$message->setBody("This is a testmail generated by the dsMailerTest of th DevelSuite MVC-Framework", "text/html");
		$message->addPart("This is a testmail generated by the dsMailerTest of th DevelSuite MVC-Framework", "text/plain");

		$mailer = new dsMailer();
		$mailer->setMessage($message);
		$this->assertGreaterThan(0, $mailer->send());
	}
}


text:
'use strict';

var _inherits = require('babel-runtime/helpers/inherits')['default'];

var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];

var RelayQueryVisitor = require('./RelayQueryVisitor');

var emptyFunction = require('fbjs/lib/emptyFunction');

var SERIALIZATION_KEY = '__serializationKey__'; // task #7117200

var validateRelayReadQuery = emptyFunction;

if (process.env.NODE_ENV !== 'production') {
  // Wrap in an IIFE to avoid unwanted function hoisting.
  (function () {
    /**
     * @internal
     *
     * `validateRelayReadQuery` is a `__DEV__`-only validator that checks that a
     * query used to read data from `RelayStore` is well-formed. Validation
     * problems are reported via `console.error`.
     *
     * At the moment, "well-formed" means that the query does not contain
     * duplicate aliases.
     */
    validateRelayReadQuery = function validateRelayReadQuery(queryNode, options) {
      var validator = new RelayStoreReadValidator(options);
      validator.visit(queryNode, {});
    };

    function assertUniqueAlias(field, aliasMap) {
      var serializationKey = field.getSerializationKey();
      if (aliasMap[SERIALIZATION_KEY]) {
        if (aliasMap[SERIALIZATION_KEY] !== serializationKey) {
          console.error('`%s` is used as an alias more than once. Please use unique ' + 'aliases.', field.getApplicationName());
        }
      } else {
        aliasMap[SERIALIZATION_KEY] = serializationKey;
      }
    }

    /**
     * Returns the nested AliasMap for `node`, initializing it to an empty map
     * if it does not already exist.
     */
    function getAliasMap(node, aliasMap) {
      var applicationName = node.getApplicationName();
      if (!aliasMap[applicationName]) {
        aliasMap[applicationName] = {};
      }
      return aliasMap[applicationName];
    }

    var RelayStoreReadValidator = (function (_RelayQueryVisitor) {
      _inherits(RelayStoreReadValidator, _RelayQueryVisitor);

      function RelayStoreReadValidator(options) {
        _classCallCheck(this, RelayStoreReadValidator);

        _RelayQueryVisitor.call(this);
        this._traverseFragmentReferences = options && options.traverseFragmentReferences || false;
      }

      RelayStoreReadValidator.prototype.visitField = function visitField(node, aliasMap) {
        aliasMap = getAliasMap(node, aliasMap);
        assertUniqueAlias(node, aliasMap);

        if (node.isGenerated()) {
          return;
        } else if (node.isScalar()) {
          return;
        } else if (node.isPlural()) {
          this._readPlural(node, aliasMap);
        } else {
          // No special handling needed for connections, edges, page_info etc.
          this._readLinkedField(node, aliasMap);
        }
      };

      RelayStoreReadValidator.prototype.visitFragment = function visitFragment(node, aliasMap) {
        if (this._traverseFragmentReferences || !node.isContainerFragment()) {
          this.traverse(node, aliasMap);
        }
      };

      RelayStoreReadValidator.prototype._readPlural = function _readPlural(node, aliasMap) {
        var _this = this;

        node.getChildren().forEach(function (child) {
          return _this.visit(child, aliasMap);
        });
      };

      RelayStoreReadValidator.prototype._readLinkedField = function _readLinkedField(node, aliasMap) {
        aliasMap = getAliasMap(node, aliasMap);
        this.traverse(node, aliasMap);
      };

      return RelayStoreReadValidator;
    })(RelayQueryVisitor);
  })();
}

module.exports = validateRelayReadQuery;

redpajama_set_name: RedPajamaGithub


text:
/*namespace com.google.zxing.qrcode.encoder {*/

import EncodeHintType from './../../EncodeHintType'
import BitArray from './../../common/BitArray'
import CharacterSetECI from './../../common/CharacterSetECI'
import GenericGF from './../../common/reedsolomon/GenericGF'
import ReedSolomonEncoder from './../../common/reedsolomon/ReedSolomonEncoder'
import ErrorCorrectionLevel from './../decoder/ErrorCorrectionLevel'
import Mode from './../decoder/Mode'
import Version from './../decoder/Version'
import MaskUtil from './MaskUtil'
import ByteMatrix from './ByteMatrix'
import QRCode from './QRCode'
import Exception from './../../Exception'
import ECBlocks from './../decoder/ECBlocks'
import MatrixUtil from './MatrixUtil'
import StringEncoding from './../../util/StringEncoding'
import BlockPair from './BlockPair'

/*import java.io.UnsupportedEncodingException;*/
/*import java.util.ArrayList;*/
/*import java.util.Collection;*/
/*import java.util.Map;*/

/**
 * @author satorux@google.com (Satoru Takabayashi) - creator
 * @author dswitkin@google.com (Daniel Switkin) - ported from C++
 */
export default class Encoder {

  // The original table is defined in the table 5 of JISX0510:2004 (p.19).
  private static ALPHANUMERIC_TABLE = Int32Array.from([
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  // 0x00-0x0f
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  // 0x10-0x1f
      36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,  // 0x20-0x2f
      0,   1,  2,  3,  4,  5,  6,  7,  8,  9, 44, -1, -1, -1, -1, -1,  // 0x30-0x3f
      -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,  // 0x40-0x4f
      25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,  // 0x50-0x5f
  ])

  public static DEFAULT_BYTE_MODE_ENCODING = CharacterSetECI.UTF8.getName()//"ISO-8859-1"
  // TYPESCRIPTPORT: changed to UTF8, the default for js

  private constructor() {}

  // The mask penalty calculation is complicated.  See Table 21 of JISX0510:2004 (p.45) for details.
  // Basically it applies four rules and summate all penalties.
  private static calculateMaskPenalty(matrix: ByteMatrix): number /*int*/ {
    return MaskUtil.applyMaskPenaltyRule1(matrix)
        + MaskUtil.applyMaskPenaltyRule2(matrix)
        + MaskUtil.applyMaskPenaltyRule3(matrix)
        + MaskUtil.applyMaskPenaltyRule4(matrix)
  }

  /**
   * @param content text to encode
   * @param ecLevel error correction level to use
   * @return {@link QRCode} representing the encoded QR code
   * @throws WriterException if encoding can't succeed, because of for example invalid content
   *   or configuration
   */
  // public static encode(content: string, ecLevel: ErrorCorrectionLevel): QRCode /*throws WriterException*/ {
  //   return encode(content, ecLevel, null)
  // }

  public static encode(content: string,
                              ecLevel: ErrorCorrectionLevel,
                              hints: Map<EncodeHintType, any> = null): QRCode /*throws WriterException*/ {

    // Determine what character encoding has been specified by the caller, if any
    let encoding: string = Encoder.DEFAULT_BYTE_MODE_ENCODING
    const hasEncodingHint: boolean = hints !== null && undefined !== hints.get(EncodeHintType.CHARACTER_SET)
    if (hasEncodingHint) {
      encoding = hints.get(EncodeHintType.CHARACTER_SET).toString()
    }

    // Pick an encoding mode appropriate for the content. Note that this will not attempt to use
    // multiple modes / segments even if that were more efficient. Twould be nice.
    const mode: Mode = this.chooseMode(content, encoding)

    // This will store the header information, like mode and
    // length, as well as "header" segments like an ECI segment.
    const headerBits = new BitArray()

    // Append ECI segment if applicable
    if (mode == Mode.BYTE && (hasEncodingHint || Encoder.DEFAULT_BYTE_MODE_ENCODING !== encoding)) {
      const eci = CharacterSetECI.getCharacterSetECIByName(encoding)
      if (eci !== undefined) {
        this.appendECI(eci, headerBits)
      }
    }

    // (With ECI in place,) Write the mode marker
    this.appendModeInfo(mode, headerBits)

    // Collect data within the main segment, separately, to count its size if needed. Don't add it to
    // main payload yet.
    const dataBits = new BitArray()
    this.appendBytes(content, mode, dataBits, encoding)

    let version: Version
    if (hints !== null && undefined !== hints.get(EncodeHintType.QR_VERSION)) {
      const versionNumber = Number.parseInt(hints.get(EncodeHintType.QR_VERSION).toString(), 10)
      version = Version.getVersionForNumber(versionNumber)
      const bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, version)
      if (!this.willFit(bitsNeeded, version, ecLevel)) {
        throw new Exception(Exception.WriterException, "Data too big for requested version")
      }
    } else {
      version = this.recommendVersion(ecLevel, mode, headerBits, dataBits)
    }

    const headerAndDataBits = new BitArray()
    headerAndDataBits.appendBitArray(headerBits)
    // Find "length" of main segment and write it
    const numLetters = mode == Mode.BYTE ? dataBits.getSizeInBytes() : content.length
    this.appendLengthInfo(numLetters, version, mode, headerAndDataBits)
    // Put data together into the overall payload
    headerAndDataBits.appendBitArray(dataBits)

    const ecBlocks: ECBlocks = version.getECBlocksForLevel(ecLevel)
    const numDataBytes = version.getTotalCodewords() - ecBlocks.getTotalECCodewords()

    // Terminate the bits properly.
    this.terminateBits(numDataBytes, headerAndDataBits)

    // Interleave data bits with error correction code.
    const finalBits: BitArray = this.interleaveWithECBytes(headerAndDataBits,
                                               version.getTotalCodewords(),
                                               numDataBytes,
                                               ecBlocks.getNumBlocks())

    const qrCode = new QRCode()

    qrCode.setECLevel(ecLevel)
    qrCode.setMode(mode)
    qrCode.setVersion(version)

    //  Choose the mask pattern and set to "qrCode".
    const dimension = version.getDimensionForVersion()
    const matrix: ByteMatrix = new ByteMatrix(dimension, dimension)
    const maskPattern = this.chooseMaskPattern(finalBits, ecLevel, version, matrix)
    qrCode.setMaskPattern(maskPattern)

    // Build the matrix and set it to "qrCode".
    MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix)
    qrCode.setMatrix(matrix)

    return qrCode
  }

  /**
   * Decides the smallest version of QR code that will contain all of the provided data.
   *
   * @throws WriterException if the data cannot fit in any version
   */
  private static recommendVersion(ecLevel: ErrorCorrectionLevel,
                                          mode: Mode,
                                          headerBits: BitArray,
                                          dataBits: BitArray): Version /*throws WriterException*/ {
    // Hard part: need to know version to know how many bits length takes. But need to know how many
    // bits it takes to know version. First we take a guess at version by assuming version will be
    // the minimum, 1:
    const provisionalBitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, Version.getVersionForNumber(1))
    const provisionalVersion = this.chooseVersion(provisionalBitsNeeded, ecLevel)

    // Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
    const bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion)
    return this.chooseVersion(bitsNeeded, ecLevel)
  }

  private static calculateBitsNeeded(mode: Mode,
                                        headerBits: BitArray,
                                        dataBits: BitArray,
                                        version: Version): number /*int*/ {
    return headerBits.getSize() + mode.getCharacterCountBits(version) + dataBits.getSize()
  }

  /**
   * @return the code point of the table used in alphanumeric mode or
   *  -1 if there is no corresponding code in the table.
   */
  public static getAlphanumericCode(code: number /*int*/): number /*int*/ {
    if (code < Encoder.ALPHANUMERIC_TABLE.length) {
      return Encoder.ALPHANUMERIC_TABLE[code]
    }
    return -1
  }

  // public static chooseMode(content: string): Mode {
  //   return chooseMode(content, null);
  // }

  /**
   * Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
   * if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
   */
  public static chooseMode(content: string, encoding: string = null): Mode {
    if (CharacterSetECI.SJIS.getName() === encoding && this.isOnlyDoubleByteKanji(content)) {
      // Choose Kanji mode if all input are double-byte characters
      return Mode.KANJI
    }
    let hasNumeric: boolean = false
    let hasAlphanumeric: boolean = false
    for (let i = 0, length = content.length; i < length; ++i) {
      const c: string = content.charAt(i)
      if (Encoder.isDigit(c)) {
        hasNumeric = true
      } else if (this.getAlphanumericCode(c.charCodeAt(0)) != -1) {
        hasAlphanumeric = true
      } else {
        return Mode.BYTE
      }
    }
    if (hasAlphanumeric) {
      return Mode.ALPHANUMERIC
    }
    if (hasNumeric) {
      return Mode.NUMERIC
    }
    return Mode.BYTE
  }

  private static isOnlyDoubleByteKanji(content: string): boolean {
    let bytes: Uint8Array
    try {
      bytes = StringEncoding.encode(content, CharacterSetECI.SJIS.getName())//content.getBytes("Shift_JIS")
    } catch (ignored/*: UnsupportedEncodingException*/) {
      return false
    }
    const length = bytes.length
    if (length % 2 != 0) {
      return false
    }
    for (let i = 0; i < length; i += 2) {
      const byte1 = bytes[i] & 0xFF
      if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {
        return false
      }
    }
    return true
  }

  private static chooseMaskPattern(bits: BitArray,
                                       ecLevel: ErrorCorrectionLevel,
                                       version: Version,
                                       matrix: ByteMatrix): number /*int*/ /*throws WriterException*/ {

    let minPenalty = Number.MAX_SAFE_INTEGER;  // Lower penalty is better.
    let bestMaskPattern = -1
    // We try all mask patterns to choose the best one.
    for (let maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
      MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix)
      let penalty = this.calculateMaskPenalty(matrix)
      if (penalty < minPenalty) {
        minPenalty = penalty
        bestMaskPattern = maskPattern
      }
    }
    return bestMaskPattern
  }

  private static chooseVersion(numInputBits: number /*int*/, ecLevel: ErrorCorrectionLevel): Version /*throws WriterException*/ {
    for (let versionNum = 1; versionNum <= 40; versionNum++) {
      const version = Version.getVersionForNumber(versionNum)
      if (Encoder.willFit(numInputBits, version, ecLevel)) {
        return version
      }
    }
    throw new Exception(Exception.WriterException, "Data too big")
  }

  /**
   * @return true if the number of input bits will fit in a code with the specified version and
   * error correction level.
   */
  private static willFit(numInputBits: number /*int*/, version: Version, ecLevel: ErrorCorrectionLevel): boolean {
      // In the following comments, we use numbers of Version 7-H.
      // numBytes = 196
      const numBytes = version.getTotalCodewords()
      // getNumECBytes = 130
      const ecBlocks = version.getECBlocksForLevel(ecLevel)
      const numEcBytes = ecBlocks.getTotalECCodewords()
      // getNumDataBytes = 196 - 130 = 66
      const numDataBytes = numBytes - numEcBytes
      const totalInputBytes = (numInputBits + 7) / 8
      return numDataBytes >= totalInputBytes
  }

  /**
   * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
   */
  public static terminateBits(numDataBytes: number /*int*/, bits: BitArray): void /*throws WriterException*/ {
    const capacity = numDataBytes * 8;
    if (bits.getSize() > capacity) {
      throw new Exception(Exception.WriterException, "data bits cannot fit in the QR Code" + bits.getSize() + " > " +
          capacity)
    }
    for (let i = 0; i < 4 && bits.getSize() < capacity; ++i) {
      bits.appendBit(false)
    }
    // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
    // If the last byte isn't 8-bit aligned, we'll add padding bits.
    const numBitsInLastByte = bits.getSize() & 0x07;
    if (numBitsInLastByte > 0) {
      for (let i = numBitsInLastByte; i < 8; i++) {
        bits.appendBit(false)
      }
    }
    // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
    const numPaddingBytes = numDataBytes - bits.getSizeInBytes()
    for (let i = 0; i < numPaddingBytes; ++i) {
      bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8)
    }
    if (bits.getSize() != capacity) {
      throw new Exception(Exception.WriterException, "Bits size does not equal capacity")
    }
  }

  /**
   * Get number of data bytes and number of error correction bytes for block id "blockID". Store
   * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
   * JISX0510:2004 (p.30)
   */
  public static getNumDataBytesAndNumECBytesForBlockID(numTotalBytes: number /*int*/,
                                                        numDataBytes: number /*int*/,
                                                        numRSBlocks: number /*int*/,
                                                        blockID: number /*int*/,
                                                        numDataBytesInBlock: Int32Array,
                                                        numECBytesInBlock: Int32Array): void /*throws WriterException*/ {
    if (blockID >= numRSBlocks) {
      throw new Exception(Exception.WriterException, "Block ID too large")
    }
    // numRsBlocksInGroup2 = 196 % 5 = 1
    const numRsBlocksInGroup2 = numTotalBytes % numRSBlocks
    // numRsBlocksInGroup1 = 5 - 1 = 4
    const numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2
    // numTotalBytesInGroup1 = 196 / 5 = 39
    const numTotalBytesInGroup1 = Math.floor(numTotalBytes / numRSBlocks)
    // numTotalBytesInGroup2 = 39 + 1 = 40
    const numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1
    // numDataBytesInGroup1 = 66 / 5 = 13
    const numDataBytesInGroup1 = Math.floor(numDataBytes / numRSBlocks)
    // numDataBytesInGroup2 = 13 + 1 = 14
    const numDataBytesInGroup2 = numDataBytesInGroup1 + 1
    // numEcBytesInGroup1 = 39 - 13 = 26
    const numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1
    // numEcBytesInGroup2 = 40 - 14 = 26
    const numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2
    // Sanity checks.
    // 26 = 26
    if (numEcBytesInGroup1 !== numEcBytesInGroup2) {
      throw new Exception(Exception.WriterException, "EC bytes mismatch")
    }
    // 5 = 4 + 1.
    if (numRSBlocks !== numRsBlocksInGroup1 + numRsBlocksInGroup2) {
      throw new Exception(Exception.WriterException, "RS blocks mismatch")
    }
    // 196 = (13 + 26) * 4 + (14 + 26) * 1
    if (numTotalBytes !==
        ((numDataBytesInGroup1 + numEcBytesInGroup1) *
            numRsBlocksInGroup1) +
            ((numDataBytesInGroup2 + numEcBytesInGroup2) *
                numRsBlocksInGroup2)) {
      throw new Exception(Exception.WriterException, "Total bytes mismatch")
    }

    if (blockID < numRsBlocksInGroup1) {
      numDataBytesInBlock[0] = numDataBytesInGroup1
      numECBytesInBlock[0] = numEcBytesInGroup1
    } else {
      numDataBytesInBlock[0] = numDataBytesInGroup2
      numECBytesInBlock[0] = numEcBytesInGroup2
    }
  }

  /**
   * Interleave "bits" with corresponding error correction bytes. On success, store the result in
   * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
   */
  public static interleaveWithECBytes(bits: BitArray,
                                        numTotalBytes: number /*int*/,
                                        numDataBytes: number /*int*/,
                                        numRSBlocks: number /*int*/): BitArray /*throws WriterException*/ {

    // "bits" must have "getNumDataBytes" bytes of data.
    if (bits.getSizeInBytes() !== numDataBytes) {
      throw new Exception(Exception.WriterException, "Number of bits and data bytes does not match")
    }

    // Step 1.  Divide data bytes into blocks and generate error correction bytes for them. We'll
    // store the divided data bytes blocks and error correction bytes blocks into "blocks".
    let dataBytesOffset = 0
    let maxNumDataBytes = 0
    let maxNumEcBytes = 0

    // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
    const blocks = new Array<BlockPair>()//new Array<BlockPair>(numRSBlocks)

    for (let i = 0; i < numRSBlocks; ++i) {
      const numDataBytesInBlock: Int32Array = new Int32Array(1)
      const numEcBytesInBlock: Int32Array = new Int32Array(1)
      Encoder.getNumDataBytesAndNumECBytesForBlockID(
          numTotalBytes, numDataBytes, numRSBlocks, i,
          numDataBytesInBlock, numEcBytesInBlock)

      const size = numDataBytesInBlock[0]
      const dataBytes = new Uint8Array(size)
      bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size);
      const ecBytes: Uint8Array = Encoder.generateECBytes(dataBytes, numEcBytesInBlock[0])
      blocks.push(new BlockPair(dataBytes, ecBytes))

      maxNumDataBytes = Math.max(maxNumDataBytes, size)
      maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.length)
      dataBytesOffset += numDataBytesInBlock[0]
    }
    if (numDataBytes != dataBytesOffset) {
      throw new Exception(Exception.WriterException, "Data bytes does not match offset")
    }

    const result = new BitArray()

    // First, place data blocks.
    for (let i = 0; i < maxNumDataBytes; ++i) {
      for (const block of blocks) {
        const dataBytes = block.getDataBytes()
        if (i < dataBytes.length) {
          result.appendBits(dataBytes[i], 8)
        }
      }
    }
    // Then, place error correction blocks.
    for (let i = 0; i < maxNumEcBytes; ++i) {
      for (const block of blocks) {
        const ecBytes = block.getErrorCorrectionBytes()
        if (i < ecBytes.length) {
          result.appendBits(ecBytes[i], 8)
        }
      }
    }
    if (numTotalBytes != result.getSizeInBytes()) {  // Should be same.
      throw new Exception("WriterException", "Interleaving error: " + numTotalBytes + " and " +
          result.getSizeInBytes() + " differ.")
    }

    return result
  }

  public static generateECBytes(dataBytes: Uint8Array, numEcBytesInBlock: number /*int*/): Uint8Array {
    const numDataBytes = dataBytes.length
    const toEncode: Int32Array = new Int32Array(numDataBytes + numEcBytesInBlock)//int[numDataBytes + numEcBytesInBlock]
    for (let i = 0; i < numDataBytes; i++) {
      toEncode[i] = dataBytes[i] & 0xFF
    }
    new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock)

    const ecBytes = new Uint8Array(numEcBytesInBlock)
    for (let i = 0; i < numEcBytesInBlock; i++) {
      ecBytes[i] = /*(byte) */toEncode[numDataBytes + i]
    }
    return ecBytes
  }

  /**
   * Append mode info. On success, store the result in "bits".
   */
  public static appendModeInfo(mode: Mode, bits: BitArray): void {
    bits.appendBits(mode.getBits(), 4)
  }

  /**
   * Append length info. On success, store the result in "bits".
   */
  public static appendLengthInfo(numLetters: number /*int*/, version: Version, mode: Mode, bits: BitArray): void /*throws WriterException*/ {
    const numBits = mode.getCharacterCountBits(version)
    if (numLetters >= (1 << numBits)) {
      throw new Exception(Exception.WriterException, numLetters + " is bigger than " + ((1 << numBits) - 1))
    }
    bits.appendBits(numLetters, numBits)
  }

  /**
   * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
   */
  public static appendBytes(content: string,
                          mode: Mode,
                          bits: BitArray,
                          encoding: string): void /*throws WriterException*/ {
    switch (mode) {
      case Mode.NUMERIC:
        Encoder.appendNumericBytes(content, bits)
        break
      case Mode.ALPHANUMERIC:
        Encoder.appendAlphanumericBytes(content, bits)
        break
      case Mode.BYTE:
        Encoder.append8BitBytes(content, bits, encoding)
        break
      case Mode.KANJI:
        Encoder.appendKanjiBytes(content, bits)
        break
      default:
        throw new Exception(Exception.WriterException, "Invalid mode: " + mode)
    }
  }

  private static getDigit(singleCharacter: string): number {
      return singleCharacter.charCodeAt(0) - 48
  }

  private static isDigit(singleCharacter: string): boolean {
    const cn = Encoder.getDigit(singleCharacter)
    return cn >= 0 && cn <= 9
  }

  public static appendNumericBytes(content: string, bits: BitArray): void {
    const length = content.length
    let i = 0
    while (i < length) {
      const num1 = Encoder.getDigit(content.charAt(i))
      if (i + 2 < length) {
        // Encode three numeric letters in ten bits.
        const num2 = Encoder.getDigit(content.charAt(i + 1))
        const num3 = Encoder.getDigit(content.charAt(i + 2))
        bits.appendBits(num1 * 100 + num2 * 10 + num3, 10)
        i += 3
      } else if (i + 1 < length) {
        // Encode two numeric letters in seven bits.
        const num2 = Encoder.getDigit(content.charAt(i + 1))
        bits.appendBits(num1 * 10 + num2, 7);
        i += 2
      } else {
        // Encode one numeric letter in four bits.
        bits.appendBits(num1, 4)
        i++
      }
    }
  }

  public static appendAlphanumericBytes(content: string, bits: BitArray): void /*throws WriterException*/ {
    const length = content.length
    let i = 0
    while (i < length) {
      const code1 = Encoder.getAlphanumericCode(content.charCodeAt(i))
      if (code1 == -1) {
        throw new Exception(Exception.WriterException)
      }
      if (i + 1 < length) {
        const code2 = Encoder.getAlphanumericCode(content.charCodeAt(i + 1))
        if (code2 == -1) {
          throw new Exception(Exception.WriterException)
        }
        // Encode two alphanumeric letters in 11 bits.
        bits.appendBits(code1 * 45 + code2, 11);
        i += 2
      } else {
        // Encode one alphanumeric letter in six bits.
        bits.appendBits(code1, 6)
        i++
      }
    }
  }

  public static append8BitBytes(content: string, bits: BitArray, encoding: string): void
      /*throws WriterException*/ {
    let bytes: Uint8Array
    try {
      bytes = StringEncoding.encode(content, encoding)
    } catch (uee/*: UnsupportedEncodingException*/) {
      throw new Exception(Exception.WriterException, uee)
    }
    for (let i = 0, length = bytes.length; i != length; i++) {
      const b = bytes[i]
      bits.appendBits(b, 8)
    }
  }

  public static appendKanjiBytes(content: string, bits: BitArray): void /*throws WriterException*/ {
    let bytes: Uint8Array
    try {
      bytes = StringEncoding.encode(content, CharacterSetECI.SJIS.getName())
    } catch (uee/*: UnsupportedEncodingException*/) {
      throw new Exception(Exception.WriterException, uee)
    }
    const length = bytes.length
    for (let i = 0; i < length; i += 2) {
      const byte1 = bytes[i] & 0xFF
      const byte2 = bytes[i + 1] & 0xFF
      const code = ((byte1 << 8) & 0xFFFFFFFF) | byte2
      let subtracted = -1
      if (code >= 0x8140 && code <= 0x9ffc) {
        subtracted = code - 0x8140
      } else if (code >= 0xe040 && code <= 0xebbf) {
        subtracted = code - 0xc140
      }
      if (subtracted === -1) {
        throw new Exception(Exception.WriterException, "Invalid byte sequence")
      }
      const encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
      bits.appendBits(encoded, 13)
    }
  }

  private static appendECI(eci: CharacterSetECI, bits: BitArray): void {
    bits.appendBits(Mode.ECI.getBits(), 4)
    // This is correct for values up to 127, which is all we need now.
    bits.appendBits(eci.getValue(), 8)
  }

}


text:
package net.floodlightcontroller.packet;

import java.nio.ByteBuffer;

/**
 * This class is a Rapid Spanning Tree Protocol
 * Bridge Protocol Data Unit
 * @author alexreimers
 */
public class BPDU extends BasePacket {
    public enum BPDUType {
        CONFIG,
        TOPOLOGY_CHANGE;
    }

    private final long destMac = 0x0180c2000000L; // 01-80-c2-00-00-00

    // TODO - check this for RSTP
    private LLC llcHeader;
    private short protocolId = 0;
    private byte version = 0;
    private byte type;
    private byte flags;
    private byte[] rootBridgeId;
    private int rootPathCost;
    private byte[] senderBridgeId; // switch cluster MAC
    private short portId; // port it was transmitted from
    private short messageAge; // 256ths of a second
    private short maxAge; // 256ths of a second
    private short helloTime; // 256ths of a second
    private short forwardDelay; // 256ths of a second

    public BPDU(BPDUType type) {
        rootBridgeId = new byte[8];
        senderBridgeId = new byte[8];

        llcHeader = new LLC();
        llcHeader.setDsap((byte) 0x42);
        llcHeader.setSsap((byte) 0x42);
        llcHeader.setCtrl((byte) 0x03);

        switch(type) {
            case CONFIG:
                this.type = 0x0;
                break;
            case TOPOLOGY_CHANGE:
                this.type = (byte) 0x80; // 1000 0000
                break;
            default:
                this.type = 0;
                break;
        }
    }

    @Override
    public byte[] serialize() {
        byte[] data;
        // TODO check these
        if (type == 0x0) {
            // config
            data = new byte[38];
        } else {
            // topology change
            data = new byte[7]; // LLC + TC notification
        }

        ByteBuffer bb = ByteBuffer.wrap(data);
        // Serialize the LLC header
        byte[] llc = llcHeader.serialize();
        bb.put(llc, 0, llc.length);
        bb.putShort(protocolId);
        bb.put(version);
        bb.put(type);

        if (type == 0x0) {
            bb.put(flags);
            bb.put(rootBridgeId, 0, rootBridgeId.length);
            bb.putInt(rootPathCost);
            bb.put(senderBridgeId, 0, senderBridgeId.length);
            bb.putShort(portId);
            bb.putShort(messageAge);
            bb.putShort(maxAge);
            bb.putShort(helloTime);
            bb.putShort(forwardDelay);
        }

        return data;
    }

    @Override
    public IPacket deserialize(byte[] data, int offset, int length) {
        ByteBuffer bb = ByteBuffer.wrap(data, offset, length);

        // LLC header
        llcHeader.deserialize(data, offset, 3);

        this.protocolId = bb.getShort();
        this.version = bb.get();
        this.type = bb.get();

        // These fields only exist if it's a configuration BPDU
        if (this.type == 0x0) {
            this.flags = bb.get();
            bb.get(rootBridgeId, 0, 6);
            this.rootPathCost = bb.getInt();
            bb.get(this.senderBridgeId, 0, 6);
            this.portId = bb.getShort();
            this.messageAge = bb.getShort();
            this.maxAge = bb.getShort();
            this.helloTime = bb.getShort();
            this.forwardDelay = bb.getShort();
        }
        // TODO should we set other fields to 0?

        return this;
    }

    public long getDestMac() {
        return destMac;
    }
}


text:
module Shoulda
  module Matchers
    module ActionController
      # The `respond_with` matcher tests that an action responds with a certain
      # status code.
      #
      # You can specify that the status should be a number:
      #
      #     class PostsController < ApplicationController
      #       def index
      #         render status: 403
      #       end
      #     end
      #
      #     # RSpec
      #     describe PostsController do
      #       describe 'GET #index' do
      #         before { get :index }
      #
      #         it { should respond_with(403) }
      #       end
      #     end
      #
      #     # Minitest (Shoulda)
      #     class PostsControllerTest < ActionController::TestCase
      #       context 'GET #index' do
      #         setup { get :index }
      #
      #         should respond_with(403)
      #       end
      #     end
      #
      # You can specify that the status should be within a range of numbers:
      #
      #     class PostsController < ApplicationController
      #       def destroy
      #         render status: 508
      #       end
      #     end
      #
      #     # RSpec
      #     describe PostsController do
      #       describe 'DELETE #destroy' do
      #         before { delete :destroy }
      #
      #         it { should respond_with(500..600) }
      #       end
      #     end
      #
      #     # Minitest (Shoulda)
      #     class PostsControllerTest < ActionController::TestCase
      #       context 'DELETE #destroy' do
      #         setup { delete :destroy }
      #
      #         should respond_with(500..600)
      #       end
      #     end
      #
      # Finally, you can specify that the status should be a symbol:
      #
      #     class PostsController < ApplicationController
      #       def show
      #         render status: :locked
      #       end
      #     end
      #
      #     # RSpec
      #     describe PostsController do
      #       describe 'GET #show' do
      #         before { get :show }
      #
      #         it { should respond_with(:locked) }
      #       end
      #     end
      #
      #     # Minitest (Shoulda)
      #     class PostsControllerTest < ActionController::TestCase
      #       context 'GET #show' do
      #         setup { get :show }
      #
      #         should respond_with(:locked)
      #       end
      #     end
      #
      # @return [RespondWithMatcher]
      #
      def respond_with(status)
        RespondWithMatcher.new(status)
      end

      # @private
      class RespondWithMatcher
        def initialize(status)
          @status = symbol_to_status_code(status)
        end

        def matches?(controller)
          @controller = controller
          correct_status_code? || correct_status_code_range?
        end

        def failure_message
          "Expected #{expectation}"
        end

        def failure_message_when_negated
          "Did not expect #{expectation}"
        end

        def description
          "respond with #{@status}"
        end

        protected

        def correct_status_code?
          response_code == @status
        end

        def correct_status_code_range?
          @status.is_a?(Range) &&
            @status.include?(response_code)
        end

        def response_code
          @controller.response.response_code
        end

        def symbol_to_status_code(potential_symbol)
          case potential_symbol
          when :success  then 200
          when :redirect then 300..399
          when :missing  then 404
          when :error    then 500..599
          when Symbol
            if defined?(::Rack::Utils::SYMBOL_TO_STATUS_CODE)
              ::Rack::Utils::SYMBOL_TO_STATUS_CODE[potential_symbol]
            else
              ::ActionController::Base::SYMBOL_TO_STATUS_CODE[potential_symbol]
            end
          else
            potential_symbol
          end
        end

        def expectation
          "response to be a #{@status}, but was #{response_code}"
        end
      end
    end
  end
end


text:
import Evented from '@ember/object/evented';
import Service from '@ember/service';

export default Service.extend(Evented, {
    publish() {
        return this.trigger(...arguments);
    },
    subscribe() {
        return this.on(...arguments);
    },
    unsubscribe() {
        return this.off(...arguments);
    }
});


text:
function getUniqueId(id) {
    if (!id || _.contains(idList, id)) id = getUniqueId(uniqueIdCounter++);
    return idList.push(id), id;
}

function Sync(model, method, opts) {
    var prefix = model.config.adapter.prefix ? model.config.adapter.prefix : "default", regex = new RegExp("^(" + prefix + ")\\-(\\d+)$");
    if (method === "read") if (opts.parse) {
        var list = [];
        _.each(TAP.listProperties(), function(prop) {
            var match = prop.match(regex);
            match !== null && list.push(TAP.getObject(prop));
        }), model.reset(list);
        var maxId = _.max(_.pluck(list, "id"));
        model.maxId = (_.isFinite(maxId) ? maxId : 0) + 1;
    } else {
        var obj = TAP.getObject(prefix + "-" + model.get("id"));
        model.set(obj);
    } else method === "create" || method === "update" ? TAP.setObject(prefix + "-" + model.get("id"), model.toJSON() || {}) : method === "delete" && (TAP.removeProperty(prefix + "-" + model.get("id")), model.clear());
}

var Alloy = require("alloy"), _ = require("alloy/underscore")._, TAP = Ti.App.Properties, idList = [], uniqueIdCounter = 1;

module.exports.sync = Sync, module.exports.beforeModelCreate = function(config) {
    return config = config || {}, config.columns = config.columns || {}, config.defaults = config.defaults || {}, config.columns.id = "Int", config.defaults.id = getUniqueId(), config;
};


text:
FOUNDATION_EXPORT double Pods_Bangumi_M_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Bangumi_M_TestsVersionString[];


text:
namespace display {

namespace {

class DisplayComparator {
 public:
  explicit DisplayComparator(const Display& display)
      : display_id_(display.id()) {}

  bool operator()(const Display& display) const {
    return display.id() == display_id_;
  }

 private:
  int64_t display_id_;
};

}  // anonymous namespace

DisplayChangeNotifier::DisplayChangeNotifier() {}

DisplayChangeNotifier::~DisplayChangeNotifier() {}

void DisplayChangeNotifier::AddObserver(DisplayObserver* obs) {
  observer_list_.AddObserver(obs);
}

void DisplayChangeNotifier::RemoveObserver(DisplayObserver* obs) {
  observer_list_.RemoveObserver(obs);
}

void DisplayChangeNotifier::NotifyDisplaysChanged(
    const std::vector<Display>& old_displays,
    const std::vector<Display>& new_displays) {
  bool did_remove_displays = false;
  // Display present in old_displays but not in new_displays has been removed.
  for (auto old_it = old_displays.begin(); old_it != old_displays.end();
       ++old_it) {
    if (std::find_if(new_displays.begin(), new_displays.end(),
                     DisplayComparator(*old_it)) == new_displays.end()) {
      did_remove_displays = true;
      for (DisplayObserver& observer : observer_list_)
        observer.OnDisplayRemoved(*old_it);
    }
  }

  if (did_remove_displays) {
    for (DisplayObserver& observer : observer_list_)
      observer.OnDidRemoveDisplays();
  }

  // Display present in new_displays but not in old_displays has been added.
  // Display present in both might have been modified.
  for (auto new_it = new_displays.begin(); new_it != new_displays.end();
       ++new_it) {
    auto old_it = std::find_if(old_displays.begin(), old_displays.end(),
                               DisplayComparator(*new_it));

    if (old_it == old_displays.end()) {
      for (DisplayObserver& observer : observer_list_)
        observer.OnDisplayAdded(*new_it);
      continue;
    }

    uint32_t metrics = DisplayObserver::DISPLAY_METRIC_NONE;

    if (new_it->bounds() != old_it->bounds())
      metrics |= DisplayObserver::DISPLAY_METRIC_BOUNDS;

    if (new_it->rotation() != old_it->rotation())
      metrics |= DisplayObserver::DISPLAY_METRIC_ROTATION;

    if (new_it->work_area() != old_it->work_area())
      metrics |= DisplayObserver::DISPLAY_METRIC_WORK_AREA;

    if (new_it->device_scale_factor() != old_it->device_scale_factor())
      metrics |= DisplayObserver::DISPLAY_METRIC_DEVICE_SCALE_FACTOR;

    if (new_it->color_spaces() != old_it->color_spaces())
      metrics |= DisplayObserver::DISPLAY_METRIC_COLOR_SPACE;

    if (metrics != DisplayObserver::DISPLAY_METRIC_NONE) {
      for (DisplayObserver& observer : observer_list_)
        observer.OnDisplayMetricsChanged(*new_it, metrics);
    }
  }
}

void DisplayChangeNotifier::NotifyCurrentWorkspaceChanged(
    const std::string& workspace) {
  for (DisplayObserver& observer : observer_list_)
    observer.OnCurrentWorkspaceChanged(workspace);
}

}  // namespace display


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <debug.h>

#include <nuttx/mtd.h>
#include <nuttx/fs/fs.h>
#include <nuttx/fs/ioctl.h>

/****************************************************************************
 * Definitions
 ****************************************************************************/
/* Configuration ************************************************************/
/* Make sure that support for MTD partitions is enabled */

#ifndef CONFIG_MTD_PARTITION
#  error "CONFIG_MTD_PARTITION is required"
#endif

/* The default is to use the RAM MTD device at drivers/mtd/rammtd.c.  But
 * an architecture-specific MTD driver can be used instead by defining
 * CONFIG_EXAMPLES_MTDPART_ARCHINIT.  In this case, the initialization logic
 * will call mtdpart_archinitialize() to obtain the MTD driver instance.
 */

#ifndef CONFIG_EXAMPLES_MTDPART_ARCHINIT

/* Make sure that the RAM MTD driver is enabled */

#  ifndef CONFIG_RAMMTD
#    error "CONFIG_RAMMTD is required without CONFIG_EXAMPLES_MTDPART_ARCHINIT"
#  endif

/* This must exactly match the default configuration in drivers/mtd/rammtd.c */

#  ifndef CONFIG_RAMMTD_ERASESIZE
#    define CONFIG_RAMMTD_ERASESIZE 4096
#  endif

/* Given the ERASESIZE, CONFIG_EXAMPLES_MTDPART_NEBLOCKS will determine the
 * size of the RAM allocation needed.
 */

#  ifndef CONFIG_EXAMPLES_MTDPART_NEBLOCKS
#    define CONFIG_EXAMPLES_MTDPART_NEBLOCKS (32)
#  endif

#  undef MTDPART_BUFSIZE
#  define MTDPART_BUFSIZE \
    (CONFIG_RAMMTD_ERASESIZE * CONFIG_EXAMPLES_MTDPART_NEBLOCKS)

#endif

#ifdef CONFIG_EXAMPLES_MTDPART_NPARTITIONS
#  define CONFIG_EXAMPLES_MTDPART_NPARTITIONS 3
#endif

/* Debug ********************************************************************/
#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_FS)
#  define message    syslog
#  define msgflush()
#else
#  define message    printf
#  define msgflush() fflush(stdout);
#endif

/****************************************************************************
 * Private Types
 ****************************************************************************/

struct mtdpart_filedesc_s
{
  FAR char *name;
  bool deleted;
  size_t len;
  uint32_t crc;
};

/****************************************************************************
 * Private Data
 ****************************************************************************/
/* Pre-allocated simulated flash */

#ifndef CONFIG_EXAMPLES_MTDPART_ARCHINIT
static uint8_t g_simflash[MTDPART_BUFSIZE];
#endif

/****************************************************************************
 * External Functions
 ****************************************************************************/

#ifdef CONFIG_EXAMPLES_MTDPART_ARCHINIT
extern FAR struct mtd_dev_s *mtdpart_archinitialize(void);
#endif

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: mtdpart_main
 ****************************************************************************/

int mtdpart_main(int argc, char *argv[])
{
  FAR struct mtd_dev_s *master;
  FAR struct mtd_dev_s *part[CONFIG_EXAMPLES_MTDPART_NPARTITIONS];
  FAR struct mtd_geometry_s geo;
  FAR uint32_t *buffer;
  char blockname[32];
  char charname[32];
  size_t partsize;
  ssize_t nbytes;
  off_t nblocks;
  off_t offset;
  off_t check;
  off_t sectoff;
  off_t seekpos;
  unsigned int blkpererase;
  int fd;
  int i;
  int j;
  int k;
  int ret;

  /* Create and initialize a RAM MTD FLASH driver instance */

#ifdef CONFIG_EXAMPLES_MTDPART_ARCHINIT
  master = mtdpart_archinitialize();
#else
  master = rammtd_initialize(g_simflash, MTDPART_BUFSIZE);
#endif
  if (!master)
    {
      message("ERROR: Failed to create RAM MTD instance\n");
      msgflush();
      exit(1);
    }

  /* Perform the IOCTL to erase the entire FLASH part */

  ret = master->ioctl(master, MTDIOC_BULKERASE, 0);
  if (ret < 0)
    {
      message("ERROR: MTDIOC_BULKERASE ioctl failed: %d\n", ret);
    }

  /* Initialize to provide an FTL block driver on the MTD FLASH interface.
   *
   * NOTE:  We could just skip all of this FTL and BCH stuff.  We could
   * instead just use the MTD drivers bwrite and bread to perform this
   * test.  Creating the character drivers, however, makes this test more
   * interesting.
   */

  ret = ftl_initialize(0, master);
  if (ret < 0)
    {
      message("ERROR: ftl_initialize /dev/mtdblock0 failed: %d\n", ret);
      msgflush();
      exit(2);
    }

  /* Now create a character device on the block device */

  ret = bchdev_register("/dev/mtdblock0", "/dev/mtd0", false);
  if (ret < 0)
    {
      message("ERROR: bchdev_register /dev/mtd0 failed: %d\n", ret);
      msgflush();
      exit(3);
    }

  /* Get the geometry of the FLASH device */

  ret = master->ioctl(master, MTDIOC_GEOMETRY, (unsigned long)((uintptr_t)&geo));
  if (ret < 0)
    {
      fdbg("ERROR: mtd->ioctl failed: %d\n", ret);
      exit(3);
    }

  message("Flash Geometry:\n");
  message("  blocksize:      %lu\n", (unsigned long)geo.blocksize);
  message("  erasesize:      %lu\n", (unsigned long)geo.erasesize);
  message("  neraseblocks:   %lu\n", (unsigned long)geo.neraseblocks);

  /* Determine the size of each partition.  Make each partition an even
   * multiple of the erase block size (perhaps not using some space at the
   * end of the FLASH).
   */

  blkpererase = geo.erasesize / geo.blocksize;
  nblocks     = (geo.neraseblocks / CONFIG_EXAMPLES_MTDPART_NPARTITIONS) * blkpererase;
  partsize    = nblocks * geo.blocksize;

  message("  No. partitions: %u\n", CONFIG_EXAMPLES_MTDPART_NPARTITIONS);
  message("  Partition size: %lu Blocks (%lu bytes)\n", nblocks, partsize);

  /* Now create MTD FLASH partitions */

  message("Creating partitions\n");

  for (offset = 0, i = 1;
       i <= CONFIG_EXAMPLES_MTDPART_NPARTITIONS;
       offset += nblocks, i++)
    {
      message("  Partition %d. Block offset=%lu, size=%lu\n",
              i, (unsigned long)offset, (unsigned long)nblocks);

      /* Create the partition */

      part[i] = mtd_partition(master, offset, nblocks);
      if (!part[i])
        {
          message("ERROR: mtd_partition failed. offset=%lu nblocks=%lu\n",
                  (unsigned long)offset, (unsigned long)nblocks);
          msgflush();
          exit(4);
        }

      /* Initialize to provide an FTL block driver on the MTD FLASH interface */

      snprintf(blockname, 32, "/dev/mtdblock%d", i);
      snprintf(charname, 32, "/dev/mtd%d", i);

      ret = ftl_initialize(i, part[i]);
      if (ret < 0)
        {
          message("ERROR: ftl_initialize %s failed: %d\n", blockname, ret);
          msgflush();
          exit(5);
        }

      /* Now create a character device on the block device */

      ret = bchdev_register(blockname, charname, false);
      if (ret < 0)
        {
          message("ERROR: bchdev_register %s failed: %d\n", charname, ret);
          msgflush();
          exit(6);
        }
    }

  /* Allocate a buffer */

  buffer = (FAR uint32_t *)malloc(geo.blocksize);
  if (!buffer)
    {
      message("ERROR: failed to allocate a sector buffer\n");
      msgflush();
      exit(7);
    }

  /* Open the master MTD FLASH character driver for writing */

  fd = open("/dev/mtd0", O_WRONLY);
  if (fd < 0)
    {
      message("ERROR: open /dev/mtd0 failed: %d\n", errno);
      msgflush();
      exit(8);
    }

  /* Now write the offset into every block */

  message("Initializing media:\n");

  offset = 0;
  for (i = 0; i < geo.neraseblocks; i++)
    {
      for (j = 0; j < blkpererase; j++)
        {
          /* Fill the block with the offset */

          for (k = 0; k < geo.blocksize / sizeof(uint32_t); k++)
            {
              buffer[k] = offset;
              offset += 4;
            }

          /* And write it using the character driver */

          nbytes = write(fd, buffer, geo.blocksize);
          if (nbytes < 0)
            {
              message("ERROR: write to /dev/mtd0 failed: %d\n", errno);
              msgflush();
              exit(9);
            }
        }
    }

  close(fd);

  /* Now read each partition */

  message("Checking partitions:\n");

  for (offset = 0, i = 1;
       i <= CONFIG_EXAMPLES_MTDPART_NPARTITIONS;
       offset += partsize, i++)
    {
      message("  Partition %d. Byte offset=%lu, size=%lu\n",
              i, (unsigned long)offset, (unsigned long)partsize);

      /* Open the master MTD partition character driver for writing */

      snprintf(charname, 32, "/dev/mtd%d", i);
      fd = open(charname, O_RDWR);
      if (fd < 0)
        {
          message("ERROR: open %s failed: %d\n", charname, errno);
          msgflush();
          exit(10);
        }

      /* Now verify the offset in every block */

      check = offset;
      sectoff = 0;

      for (j = 0; j < nblocks; j++)
        {
#if 0 /* Too much */
          message("  block=%u offset=%lu\n", j, (unsigned long) check);
#endif
          /* Seek to the next read position */

          seekpos = lseek(fd, sectoff, SEEK_SET);
          if (seekpos != sectoff)
            {
              message("ERROR: lseek to offset %ld failed: %d\n",
                      (unsigned long)sectoff, errno);
              msgflush();
              exit(11);
            }

          /* Read the next block into memory */

          nbytes = read(fd, buffer, geo.blocksize);
          if (nbytes < 0)
            {
              message("ERROR: read from %s failed: %d\n", charname, errno);
              msgflush();
              exit(12);
            }
          else if (nbytes == 0)
            {
              message("ERROR: Unexpected end-of file in %s\n", charname);
              msgflush();
              exit(13);
            }
          else if (nbytes != geo.blocksize)
            {
              message("ERROR: Unexpected read size from %s: %ld\n",
                      charname, (unsigned long)nbytes);
              msgflush();
              exit(14);
            }

          /* Since we forced the size of the partition to be an even number
           * of erase blocks, we do not expect to encounter the end of file
           * indication.
           */

         else if (nbytes == 0)
           {
              message("ERROR: Unexpected end of file on %s\n", charname);
              msgflush();
              exit(15);
           }

         /* This is not expected at all */

         else if (nbytes != geo.blocksize)
           {
              message("ERROR: Short read from %s failed: %lu\n",
                      charname, (unsigned long)nbytes);
              msgflush();
              exit(16);
            }

          /* Verfy the offsets in the block */

          for (k = 0; k < geo.blocksize / sizeof(uint32_t); k++)
            {
              if (buffer[k] != check)
                {
                  message("ERROR: Bad offset %lu, expected %lu\n",
                          (long)buffer[k], (long)check);
                  msgflush();
                  exit(17);
                }

              /* Invert the value to indicate that we have verified
               * this value.
               */

              buffer[k] = ~check;
              check += sizeof(uint32_t);
            }

          /* Seek to the next write position */

          seekpos = lseek(fd, sectoff, SEEK_SET);
          if (seekpos != sectoff)
            {
              message("ERROR: lseek to offset %ld failed: %d\n",
                      (unsigned long)sectoff, errno);
              msgflush();
              exit(18);
            }

          /* Now write the block back to FLASH with the modified value */

          nbytes = write(fd, buffer, geo.blocksize);
          if (nbytes < 0)
            {
              message("ERROR: write to %s failed: %d\n", charname, errno);
              msgflush();
              exit(19);
            }
          else if (nbytes != geo.blocksize)
            {
              message("ERROR: Unexpected write size to %s: %ld\n",
                      charname, (unsigned long)nbytes);
              msgflush();
              exit(20);
            }

          /* Get the offset to the next block */

          sectoff += geo.blocksize;
        }

      /* Try reading one more time.  We should get the end of file */

      nbytes = read(fd, buffer, geo.blocksize);
      if (nbytes != 0)
        {
          message("ERROR: Expected end-of-file from %s failed: %d %d\n",
                  charname, nbytes, errno);
          msgflush();
          exit(22);
        }

      close(fd);
    }

  /* Now verify that all of the verifed blocks appear where we thing they
   * should on the device.
   */

  message("Verfying media:\n");

  fd = open("/dev/mtd0", O_RDONLY);
  if (fd < 0)
    {
      message("ERROR: open /dev/mtd0 failed: %d\n", errno);
      msgflush();
      exit(23);
    }

  offset = 0;
  check  = 0;

  for (i = 0; i < nblocks * CONFIG_EXAMPLES_MTDPART_NPARTITIONS; i++)
    {
      /* Read the next block into memory */

      nbytes = read(fd, buffer, geo.blocksize);
      if (nbytes < 0)
        {
          message("ERROR: read from %s failed: %d\n", charname, errno);
          msgflush();
          exit(24);
        }
      else if (nbytes == 0)
        {
          message("ERROR: Unexpected end-of file in %s\n", charname);
          msgflush();
          exit(25);
        }
      else if (nbytes != geo.blocksize)
        {
          message("ERROR: Unexpected read size from %s: %ld\n",
                  charname, (unsigned long)nbytes);
          msgflush();
          exit(26);
        }

      /* Verfy the values in the block */

      for (k = 0; k < geo.blocksize / sizeof(uint32_t); k++)
        {
          if (buffer[k] != ~check)
            {
              message("ERROR: Bad value %lu, expected %lu\n",
                      (long)buffer[k], (long)(~check));
              msgflush();
              exit(27);
            }

          check += sizeof(uint32_t);
        }
    }

  close(fd);

  /* And exit without bothering to clean up */

  message("PASS: Everything looks good\n");
  msgflush();
  return 0;
}


text:
/**
 * @fileoverview 通用浮层配置模块
 * @authors liangdong2
 */
define('lib/common/layer',function(require,exports,module){

	//加载基础对话框
	var $alert = require('mods/dialog/alert');
	var $confirm = require('mods/dialog/confirm');
	var $tip = require('mods/dialog/tip');
	var $loading = require('mods/dialog/loading');

	exports.alert = $alert;
	exports.confirm = $confirm;
	exports.loading = $loading;
	exports.tip = $tip;

});


text:
package com.tinfoilsecurity.apiscanner.api;

public class Report {
  public enum Classification {
    SAFE("safe"), MOSTLY_SAFE("mostly_safe"), BORDERLINE("borderline"), UNSAFE("unsafe"), VERY_UNSAFE("very_unsafe");

    private String text;

    Classification(String text) {
      this.text = text;
    }

    public static Classification fromString(String text) {
      if (text != null) {
        for (Classification c : Classification.values()) {
          if (text.equalsIgnoreCase(c.text)) {
            return c;
          }
        }
      }
      return null;
    }
  }

  private Classification classification;

  public Report(Classification classification) {
    this.classification = classification;
  }

  public Classification getClassification() {
    return classification;
  }
}


text:
package vn.getgreen.view;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import vn.getgreen.imagecache.ImageFetcher;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html.ImageGetter;
import android.view.View;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Picasso.LoadedFrom;
import com.squareup.picasso.Target;

public class URLImageParser implements ImageGetter {
	Context c;
    View container;
    ImageFetcher mImageFetcher;
    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param t
     * @param c
     */
    public URLImageParser(View t, Context c) {
        this.c = c;
        this.container = t;
    }

    public Drawable getDrawable(String source) {
//    	final URLDrawable urlDrawable = new URLDrawable();
//
//    	Picasso.with(c).load(source).into(new Target() {
//
//			@Override
//			public void onPrepareLoad(Drawable arg0) {
//				// TODO Auto-generated method stub
//
//			}
//
//			@Override
//			public void onBitmapLoaded(Bitmap bitmap, LoadedFrom arg1) {
//				Drawable drawable = new BitmapDrawable(c.getResources(),bitmap);
//				urlDrawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
//		                    + drawable.getIntrinsicHeight());
//
//		            // change the reference of the current drawable to the result
//		            // from the HTTP call
//		            urlDrawable.drawable = drawable;
//
//		            // redraw the image by invalidating the container
//		            URLImageParser.this.container.invalidate();
//		            ((TextView)URLImageParser.this.container).setHeight((URLImageParser.this.container.getHeight()
//		            	    + drawable.getIntrinsicHeight()));
//			}
//
//			@Override
//			public void onBitmapFailed(Drawable arg0) {
//				// TODO Auto-generated method stub
//
//			}
//		});
    	URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
            new ImageGetterAsyncTask(urlDrawable);

        asyncTask.execute(source);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable>  {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            // set the correct bound according to the result from HTTP call
        	if(urlDrawable == null || result == null) return;
            urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
                    + result.getIntrinsicHeight());

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();

            ((TextView)URLImageParser.this.container).setHeight((URLImageParser.this.container.getHeight()
            	    + result.getIntrinsicHeight()));
        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
            	Bitmap bitmap = Picasso.with(c).load(urlString).get();
//                InputStream is = fetch(urlString);
                Drawable drawable = new BitmapDrawable(c.getResources(), bitmap);
                drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
                        + drawable.getIntrinsicHeight());
                return drawable;
            } catch (Exception e) {
                return null;
            }
        }

        private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }
    }
}


text:
if [ -z "$POSTGRES_PASSWORD" ]; then
  echo "Warning, postgres password not set, using default"
  export POSTGRES_PASSWORD=password
fi

if [ ! -f /frist.marker ]; then
  touch /frist.marker
  echo "Performing first time postgres setup"
  sed -ri "s/^#?(listen_addresses\s*=\s*)\S+/\1'*'/" "$PGDATA/postgresql.conf"

  mkdir -p "$PGDATA"
  chown -R postgres "$PGDATA"

  chmod g+s /run/postgresql
  chown -R postgres /run/postgresql

  gosu postgres initdb
  pass="PASSWORD '$POSTGRES_PASSWORD'"
  authMethod=md5

  { echo; echo "host all all 0.0.0.0/0 $authMethod"; } >> "$PGDATA/pg_hba.conf"
  gosu postgres pg_ctl -D "$PGDATA" -o "-c listen_addresses=''" -w start

  export POSTGRES_USER=postgres
  export POSTGRES_DB=postgres

  psql --username postgres <<-EOSQL
      ALTER USER "$POSTGRES_USER" WITH SUPERUSER $pass ;
EOSQL

  echo 'PostgreSQL init process complete'
  gosu postgres pg_ctl -D "$PGDATA" -m fast -w stop
else
  echo 'Skipping first time setup as it has already occured once'
fi

gosu postgres postgres &


text:
using System;
using System.Collections.Generic;
using System.IO;
using ElephantBookStore.Client.Helpers;
using ElephantBookStore.Data.Contracts;
using ElephantBookStore.Data.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace ElephantBookStore.Client.UnitTests.PDFReportGeneratorTests
{
	[TestClass]
	public class GenerateReportFileForCategoryShould
	{
		[TestMethod]
		[ExpectedException(typeof(ArgumentException), "Category is null but no exception is thrown")]
		public void ThrowArgumentException_IfCategoryIsNull_WithMessageContainingCategory()
		{
			try
			{
				PDFReportGenerator.GenerateReportFileForCategory(null, "./../../Test files/Georgi.pdf");
			}
			catch (ArgumentException e)
			{
				Assert.IsTrue(e.Message.Contains("Category"));
				throw e;
			}
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException), "File name is null but no exception is thrown")]
		public void ThrowArgumentException_IfFileNameIsNull_WithMessageContainingFileName()
		{
			var mockedCategory = new Mock<ICategory>();

			try
			{
				PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, null);
			}
			catch (ArgumentException e)
			{
				Assert.IsTrue(e.Message.Contains("File name"));
				throw e;
			}
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException), "File name is invalid but no exception is thrown")]
		public void ThrowArgumentException_IfFileExtensionIsNotPDF()
		{
			var mockedCategory = new Mock<ICategory>();
			var xlsFileName = "./../../Test files/Georgi.xls";

			PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, xlsFileName);
		}

		[TestMethod]
		public void ThrowArgumentExceptionContainingExtension_IfFileExtensionIsNotPDF()
		{
			var mockedCategory = new Mock<ICategory>();
			var xlsFileName = "./../../Test files/Georgi.xls";

			try
			{
				PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, xlsFileName);
			}
			catch (ArgumentException e)
			{
				Assert.IsTrue(e.Message.Contains("File extension"));
				Assert.IsTrue(e.Message.Contains(".pdf"));
			}
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void ThrowArgumentException_IfFileNameContainsInvalidPathCharacters()
		{
			var mockedCategory = new Mock<ICategory>();
			var invalidSymbols = Path.GetInvalidPathChars();
			var fileName = "./../../Test files/Georgi.pdf";
			fileName = fileName.Insert(15, invalidSymbols[0].ToString());

			PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, fileName);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void ThrowArgumentException_IfFileNameContainsInvalidFileNameCharacters()
		{
			var mockedCategory = new Mock<ICategory>();
			var invalidSymbols = Path.GetInvalidFileNameChars();
			var fileName = "./../../Test files/Georgi.pdf";
			fileName = fileName.Insert(15, invalidSymbols[0].ToString());

			PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, fileName);
		}

		[TestMethod]
		public void ThrowArgumentException_Containing_InvalidSymbols_WhenFileNameIsInvalid()
		{
			var mockedCategory = new Mock<ICategory>();
			var invalidSymbols = Path.GetInvalidFileNameChars();
			var fileName = "./../../Test files/Georgi.pdf";
			fileName = fileName.Insert(10, invalidSymbols[0].ToString());

			try
			{
				PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, fileName);
			}
			catch (ArgumentException e)
			{
				Assert.IsTrue(e.Message.Contains("invalid symbols"));
			}
		}

		[TestMethod]
		public void NotThrow_WhenParametersAreBothValid()
		{
			var mockedCategory = new Mock<ICategory>();
			mockedCategory.SetupGet(c => c.Items).Returns(new List<Item>());
			mockedCategory.SetupGet(c => c.ProductType).Returns(new ProductType()
			{
				ProductTypeName = "Gosho"
			});

			var fileName = "./../../Test files/Georgi.pdf";

			PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, fileName);
		}

		[TestMethod]
		public void TraverseCategorysItems()
		{
			var mockedCategory = new Mock<ICategory>();
			mockedCategory.SetupGet(c => c.Items).Returns(new List<Item>()).Verifiable();
			mockedCategory.SetupGet(c => c.ProductType).Returns(new ProductType()
			{
				ProductTypeName = "Gosho"
			});

			var fileName = "./../../Test files/Georgi.pdf";
			PDFReportGenerator.GenerateReportFileForCategory(mockedCategory.Object, fileName);

			Mock.Verify(mockedCategory);
		}
	}
}


text:
package com.leanstacks.ws.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

/**
 * An implementation of Spring Security AuthenticationEntryPoint. Extends the default functionality of
 * BasicAuthenticationEntryPoint. Updates the HTTP Response with HTTP 401 status if authentication fails.
 *
 * @author Matt Warman
 *
 */
public class RestBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response,
            final AuthenticationException authException) throws IOException, ServletException {

        response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    }

}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="process">
        <note>
            Frames file for 'process' based on sentences in financial subcorpus.
            No Verbnet entry, no Framenet entry.  No comparison.
        </note>

        <roleset id="process.01" name="do something to">
            <roles>
                <role descr="processor" n="0"/>
                <role descr="thing processed" n="1"/>
                <role descr="end state" n="2"/>
                <role descr="start state" n="3"/>
            </roles>

            <example name="boring but typical">
                <inflection aspect="ns" form="full" person="third" tense="present" voice="active"/>
                <text>
                    Michael, which *trace* also processes potatoes, still relies on
                    spuds for about a fourth of its sales and nearly half its pretax
                    profit.
                </text>
                <arg n="0">*trace*</arg>
                <arg n="M" f="RCL">which ->  Michael</arg>
                <arg f="DIS" n="M">also</arg>
                <rel>processes</rel>
                <arg n="1">potatoes</arg>
            </example>

            <example name="start and end states">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    John's word processor processed his dissertation from an orderly
                    progression of arguments into "word salad".
                </text>
                <arg n="0">John's word processor</arg>
                <rel>processed</rel>
                <arg n="1">his dissertation</arg>
                <arg n="3">from an orderly progression of arguments</arg>
                <arg n="2">into "word salad"</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%X{contextID}] %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/cogstack-unit-test-log.html</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>cogstack-unit-test-log%d{yyyy-MM-dd}.%i.html</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <!-- or whenever the file size reaches 50MB -->
            <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- keep 1 days' worth of history -->
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <charset>UTF-8</charset>
            <layout class="ch.qos.logback.classic.html.HTMLLayout">
                <pattern>%X{contextID}%d{HH:mm:ss.SSS}%thread%level%logger%line%msg</pattern>
            </layout>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="ROLLING" />
        <appender-ref ref="STDOUT" />
    </root>
</configuration>


text:
from selenium import webdriver
import os
from bs4 import BeautifulSoup
import lxml
import json
import re
import time
from selenium.webdriver.support.ui import Select

def _parse_html(html,result):

	soup = BeautifulSoup(html,'lxml')

	header_table = soup.find(id='headerRowTable')
	header_table_rows = header_table.find_all('tr')

	times = {}

	time_cells = header_table_rows[0].find_all('th')
	for time_cell in time_cells:
		time_id = time_cell['id']
		time_value = time_cell.text
		times[time_id] = time_value
	# time_text = header_table_rows[0].text
	# times[time_id] = time_text

	measures = {}
	for th in header_table_rows[1].find_all('th'):
		id = th['id']
		value = th.text
		measures[id] = value
		# print 'a new measure ' + value

	commodities = {}
	for th in header_table_rows[2].find_all('th'):
		id = th['id']
		value = th.text
		commodities[id]= value
		# print 'a new commodity ' + value

	countries = {}
	trs = soup.find(id='headerColumnTable')
	trs = trs.find_all('tr')
	for tr in trs:
		id = tr.find('th')['id']
		value = tr.text
		countries[id] = value
		# print 'a new country ' + value

	for time_key in times:
		time = times[time_key]
		if time not in result:
			result[time] = {}
		for measure_key in measures:
			measure = measures[measure_key]
			if measure not in result[time]:
				result[time][measure] = {}
			for commodity_key in commodities:
				commodity = commodities[commodity_key]
				if commodity not in result[time][measure]:
					result[time][measure][commodity] = {}

	table = soup.find(id='bodyTD')
	rows = table.find_all('tr')
	for row in rows:
		cells = row.find_all('td')
		for cell in cells:
			features = cell['headers']
			time = times[features[0]]
			measure = measures[features[1]]
			commodity = commodities[features[2]]
			country = countries[features[3]]
			number = cell.text
			result[time][measure][commodity][country]= number
			# print time + '\t' + measure + '\t' + commodity + '\t' + country + '\t' + number

	# return result

# It is important to setup the waiting mechanism properly
# if there is only one URL or link you want to click on a webpage, it is probably OK to simply use the implicit wait
# if there are more than one element or an array of elements you want to retrieve, using an explicity wait is probably the best
# refer waiting mechanisms here: http://selenium-python.readthedocs.org/waits.html
# open up the browser and navigate to the hompage of census.gov

start_time = time.time()
url = 'https://usatrade.census.gov/index.php?do=login'
# set up the webdriver. We use Firefox for tetsing purpose due to its visiability
# during production we may want to use PhantomJS headless webdriver to save system
# resources and speed up the program
browser = webdriver.Firefox()
# phantomjs_path = './phantomjs-2.0.0-windows/bin/phantomjs.exe'
# browser = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull)

# setting up implicit wait mechanism, here, the webdriver will try to fetch the elements
# for up to 10 seconds until
browser.implicitly_wait(10)
browser.get(url)

# locate the input fields and login buttons
user_id = browser.find_element_by_id('struserid')
user_id.send_keys('8BTJY9B')

password = browser.find_element_by_id('pwdfld')
password.send_keys('1730RhodeIsland!')

login_button = browser.find_element_by_id('btnlogin')
login_button.click()

# click on the exports anchor tag
# things may go wrong here because we did "find_elementS", and this function
# treats empty list as a valid result. If the internets is slow and the function
# returns an empty list, our attempt to fetch the element at index = 0 will
# raise out of bound exception
exports = browser.find_elements_by_link_text('Exports')
exports[0].click()

# click on the report link
# report_link = browser.find_element_by_link_text('Report')
# report_link.click()

# table = browser.find_element_by_id('ContentsTable')
# print table.get_attribute('innerHTML')

# options box represents the <div> on the left hand side of the webpage
# it includes all the options like commodity, country etc.
options_box = browser.find_element_by_id('ctl00_RadDimensionsTree')
options_box.find_element_by_link_text('Measures').click()
browser.find_element_by_id('AllSelectImage').click()

# each time you click on something, the web page CHANGES
# Therefore you have to find the options box every time after you have
# clicked something
options_box = browser.find_element_by_id('ctl00_RadDimensionsTree')
options_box.find_element_by_link_text('Commodity').click()
browser.find_element_by_id('ctl00_MainContent_RadMembersTree').\
find_elements_by_tag_name('label')[1].find_elements_by_tag_name('input')[1].click()

options_box = browser.find_element_by_id('ctl00_RadDimensionsTree')
options_box.find_element_by_link_text('Country').click()
browser.find_element_by_id('ctl00_MainContent_RadMembersTree').\
find_elements_by_tag_name('label')[0].find_elements_by_tag_name('input')[1].click()

options_box = browser.find_element_by_id('ctl00_RadDimensionsTree')
options_box.find_element_by_link_text('Time').click()
browser.find_element_by_id('ctl00_MainContent_RadMembersTree').\
find_elements_by_tag_name('label')[0].find_elements_by_tag_name('input')[1].click()

report_link = browser.find_element_by_link_text('Report')
report_link.click()

browser.find_element_by_id('anch_368').click()
browser.find_element_by_link_text('Table display settings...').click()

select = Select(browser.find_element_by_id('TableRowPageSizeLB'))
select.select_by_visible_text('200')

# wrapping = browser.find_element_by_id('WrappingOn').click()

browser.find_element_by_name('TableOptionsGo').click()

# time.sleep(5)
result = {}
count = 0
while (True):
	table = browser.find_element_by_id('ContentsTable').get_attribute('innerHTML')
	_parse_html(table,result)
	# print result
	# break
	try:
		# print browser.find_element_by_id('TablePagination').find_elements_by_tag_name('td')[2].text
		while(True):
			try:
				# print '\t' + browser.find_element_by_id('TablePagination').find_elements_by_tag_name('td')[5].text
				arrow_position = 4 - (count%2)
				browser.find_element_by_id('TablePagination')\
				.find_elements_by_tag_name('td')[arrow_position]\
				.find_element_by_tag_name('a').click()
				table = browser.find_element_by_id('ContentsTable').get_attribute('innerHTML')
				_parse_html(table,result)
			except:
				count = count + 1
				# print 'count = ' + str(count)
				break
		browser.find_element_by_id('TablePagination')\
		.find_elements_by_tag_name('td')[1]\
		.find_element_by_tag_name('a').click()
		# time_hit+=1
		# print 'times down arrow button hit = ' + str(time_hit)
	except:
		print 'total run time = ' + str(time.time()-start_time)
		break

# time.sleep(10)
# browser.close()

with open('data2.json', 'w') as outfile:
    json.dump(result, outfile, indent=4)


text:
var quotes = [
	"'Sorry mom, the mob has spoken.'",
	"'…A little help?'",
	"'So I said to myself: what would God do in this situation?'",
	"'The goggles, they do nothing!'",
	"'And I'm not easily impressed — WOW, A BLUE CAR!'",
	"'Since the beginning of time, man has yearned to destroy the sun.'",
	"'Lisa, I'd like to buy your rock.'",
	"'My son's name is also Bort.'",
	"'We're here! We're queer! We don't want any more bears!'",
	"'There's an angry mob here to see you, sir.'",
	"'It's just like I've always said: Democracy doesn't work.'",
	"'I'd kill you if I had my gun!'",
	"'Freedom! Horrible, horrible freedom!'",
	"'You'll pick many a bean.'",
	"'Stupid like a fox!'",
	"'Maybe there is no moral. Maybe it's just a bunch of stuff that happened.'",
	"'I'm about to convene another meeting… in bed.'",
	"'I see you've played knifey spooney before.'"
];

function generator(){
	var i = Math.floor(Math.random() * quotes.length);
	document.getElementById("quoteText").innerHTML = quotes[i];
}

function tweetQuote(){
	var txt = document.getElementById("quoteText").innerHTML + 'Generate using SimpsonsQuotesGenerator by @usainzg';
	var link = 'http://twitter.com/home?status=' + encodeURIComponent(txt);
	window.open(link, '_blank');
}

window.addEventListener("load", generator());


text:
// Header for C3PaneParentPanel class

#ifndef __C3PANEPARENTPANEL__MULBERRY__
#define __C3PANEPARENTPANEL__MULBERRY__

#include "C3PanePanel.h"
#include "CListener.h"

// Classes
class CBaseView;

class C3PaneParentPanel : public C3PanePanel, public CListener
{
public:
	static C3PaneParentPanel* sCurrentFocus;

					C3PaneParentPanel(JXContainer* enclosure,
								const HSizingOption hSizing, const VSizingOption vSizing,
								const JCoordinate x, const JCoordinate y,
								const JCoordinate w, const JCoordinate h);
	virtual 		~C3PaneParentPanel();

	virtual void	OnCreate();

	virtual void	ListenTo_Message(long msg, void* param);

	virtual bool	HasFocus() const;
	virtual void	Focus();

	virtual void	ResetState() = 0;						// Reset state from prefs
	virtual void	SaveDefaultState() = 0;					// Save state in prefs

protected:
	JXWidgetSet*	mView;
	C3PanePanel*	mCurrent;

			void	MakeToolbars(CBaseView* view);
};

#endif


text:
@interface LBCalendarAppearance : NSObject

typedef NS_ENUM(NSInteger, LBCalendarWeekDayFormat) {
    LBCalendarWeekDayFormatSingle,
    LBCalendarWeekDayFormatShort,
    LBCalendarWeekDayFormatFull
};

@property (assign, nonatomic) BOOL isWeekMode;

// Weekday
@property (assign, nonatomic) LBCalendarWeekDayFormat weekDayFormat;
@property (strong, nonatomic) UIColor *weekDayTextColor;
@property (strong, nonatomic) UIFont *weekDayTextFont;

// Day
@property (strong, nonatomic) UIColor *dayRectangularColorSelected;
@property (strong, nonatomic) UIColor *dayRectangularColorSelectedOtherMonth;
@property (strong, nonatomic) UIColor *dayRectangularColorToday;
@property (strong, nonatomic) UIColor *dayRectangularColorTodayOtherMonth;

@property (strong, nonatomic) UIColor *dayDotColor;
@property (strong, nonatomic) UIColor *dayDotColorSelected;
@property (strong, nonatomic) UIColor *dayDotColorOtherMonth;
@property (strong, nonatomic) UIColor *dayDotColorSelectedOtherMonth;
@property (strong, nonatomic) UIColor *dayDotColorToday;
@property (strong, nonatomic) UIColor *dayDotColorTodayOtherMonth;

@property (strong, nonatomic) UIColor *dayStarColor;
@property (strong, nonatomic) UIColor *dayStarColorSelected;
@property (strong, nonatomic) UIColor *dayStarColorOtherMonth;
@property (strong, nonatomic) UIColor *dayStarColorSelectedOtherMonth;
@property (strong, nonatomic) UIColor *dayStarColorToday;
@property (strong, nonatomic) UIColor *dayStarColorTodayOtherMonth;

@property (strong, nonatomic) UIColor *dayTextColor;
@property (strong, nonatomic) UIColor *dayTextColorSelected;
@property (strong, nonatomic) UIColor *dayTextColorOtherMonth;
@property (strong, nonatomic) UIColor *dayTextColorSelectedOtherMonth;
@property (strong, nonatomic) UIColor *dayTextColorToday;
@property (strong, nonatomic) UIColor *dayTextColorTodayOtherMonth;
@property (strong, nonatomic) UIColor *dateTextColor;

@property (strong, nonatomic) UIFont *dayTextFont;
@property (strong, nonatomic) UIFont *dateTextFont;

@property (assign, nonatomic) CGFloat dayRectangularRatio;
@property (assign, nonatomic) CGFloat dayDotRatio;

- (NSCalendar *)calendar;

- (void)setDayDotColorForAll:(UIColor *)dotColor;
- (void)setDayStarColorForAll:(UIColor *)starColor;
- (void)setDayTextColorForAll:(UIColor *)textColor;

@end


text:
package org.burroloco.config.core;

import au.net.netstorm.boost.gunge.goop.Nvp;

public interface Configs {
    Config moosh(Config config, Nvp... entries);
}


text:
FeaturePromoBubbleOwner::FeaturePromoBubbleOwner() = default;
FeaturePromoBubbleOwner::~FeaturePromoBubbleOwner() = default;


text:
public class RomanNumbers {

	private static int intValues[] = new int[] { 1, 4, 5, 9, 10, 40, 50,
			90, 100, 400, 500, 900, 1000 };

	private static String RomanSymbols = "IVXLCDM";

	private static String getRomanValue(int number) {

		switch (number) {
		case 1:
			return "I";
		case 4:
			return "IV";
		case 5:
			return "V";
		case 9:
			return "IX";
		case 10:
			return "X";
		case 40:
			return "XL";
		case 50:
			return "L";
		case 90:
			return "XC";
		case 100:
			return "C";
		case 400:
			return "CD";
		case 500:
			return "D";
		case 900:
			return "CM";
		case 1000:
			return "M";

		default:
			return "";
		}

	}

	public static String intToRoman(int number) throws RomanNumbersException {
		if(number<=0 || number>=4000) throw new RomanNumbersException("out of range");
		String str = "";

		if (getRomanValue(number).equals("")) {

			for (int i = intValues.length - 1; i >= 0; i--) {

				while (number >= intValues[i] && number != 0) {

					str += getRomanValue(intValues[i]);
					number -= intValues[i];

				}

				if (!getRomanValue(number).equals(""))
					return str + getRomanValue(number);
			}

			return str;

		} else
			return getRomanValue(number);

	}

	private static int getIntValue(String roman) {

		switch (roman) {
		case "I":
			return 1;
		case "IV":
			return 4;
		case "V":
			return 5;
		case "IX":
			return 9;
		case "X":
			return 10;
		case "XL":
			return 40;
		case "L":
			return 50;
		case "XC":
			return 90;
		case "C":
			return 100;
		case "CD":
			return 400;
		case "D":
			return 500;
		case "CM":
			return 900;
		case "M":
			return 1000;

		default:
			return 0;
		}
	}

	public static int romanToInt(String roman) throws RomanNumbersException{
		int returnValue = 0;
		int last = 4000;
		int value = 0;
		if(!isValid(roman)) throw new RomanNumbersException("contains invalid symbols");
		for( int i =0 ; i <roman.length() ; i++){

			int twoSymboledNumber =0;

			if(i+2<=roman.length()){
				twoSymboledNumber = getIntValue(roman.substring(i,i+2));

			}
			if(twoSymboledNumber==0){
				value= getIntValue(roman.substring(i,i+1));

			}
			else{
				value=twoSymboledNumber;
				i++;
			}

			if(value >  last){

				throw new RomanNumbersException("invalid order");
			}
			else{
				returnValue += value;
				last = value;
			}
		}
		return returnValue;

	}

	private static boolean isValid(String roman) {
		for( int i =0 ; i <roman.length() ; i++){

			if(!RomanSymbols.contains(""+roman.charAt(i))) return false;
		}
		return true;
	}

}


text:
import { VariableRef, Description, ContentId } from './common';
// import { GNumber, MathOp } from './math';
import { Event } from './event';
import { DamageEvent } from './damage';

export interface Grunt {
    desc: Description;
    chance: number;
}

export interface Actor {
    id: ContentId;

    name: string;

    // Default description.
    desc: Description;

    // Is this NPC permanently friendly?
    alwaysFriendly: boolean;

    // If this NPC can get angry, is it friendly to start with?
    // If it's friendly to start with, it will get angry on attack.
    startsFriendly?: boolean;

    canTurnFriendly?: boolean;

    health: number;

    attack?: {
        dmgEvent: DamageEvent;
        cooldown?: number;
    };

    grunt?: Array<Grunt>;

    commands?: {
        targeted: Array<{
            trigger: string,
            event: Event,
        }>
    };
}

export interface RawActorData {
    lastAttack?: number;
    lastGrunt?: number;
    isAngry?: boolean;
}

export interface RawActorRef<T extends RawActorData> {
    ref: ContentId;
    data?: T
}


text:
'use strict';

var Level = function(levelId, darkness, monsterSpeed, itemSeed, terrainSeed, playerHealth, monsterHealth, trees, growlCooldown, itemCooldown, itemSwordAmount, itemSwordLifetime, comboInterval, maxFunValue, funTime) {
    this.levelId = levelId;
    this.darkness = darkness;
    this.monsterSpeed = monsterSpeed;
    this.darkness = darkness;
    this.itemSeed = itemSeed;
    this.terrainSeed = terrainSeed;
    this.playerHealth = playerHealth;
    this.monsterHealth = monsterHealth;
    this.trees = trees;
    this.growlCooldown = growlCooldown;
    this.itemCooldown = itemCooldown;
    this.itemSwordAmount = itemSwordAmount;
    this.itemSwordLifetime = itemSwordLifetime;
    this.comboInterval = comboInterval;
    this.maxFunValue = maxFunValue;
    this.funTime = funTime;
};

module.exports = Level;


text:
require 'spec_helper'

describe 'names_containing_dash' do
  let(:class_msg) { 'class name containing a dash' }
  let(:define_msg) { 'defined type name containing a dash' }

  context 'module named foo-bar' do
    let(:code) { 'class foo-bar { }' }
    let(:path) { 'foo-bar/manifests/init.pp' }

    it 'should only detect a single problem' do
      expect(problems).to have(1).problem
    end

    it 'should create an error' do
      expect(problems).to contain_error(class_msg).on_line(1).in_column(7)
    end
  end

  context 'define named foo-bar' do
    let(:code) { 'define foo::foo-bar { }' }
    let(:path) { 'foo/manifests/foo-bar.pp' }

    it 'should only detect a single problem' do
      expect(problems).to have(1).problem
    end

    it 'should create an error' do
      expect(problems).to contain_error(define_msg).on_line(1).in_column(8)
    end
  end

  context 'class named bar-foo' do
    let(:code) { 'class foo::bar-foo { }' }
    let(:path) { 'foo/manifests/bar-foo.pp' }

    it 'should only detect a single problem' do
      expect(problems).to have(1).problem
    end

    it 'should create an error' do
      expect(problems).to contain_error(class_msg).on_line(1).in_column(7)
    end
  end

  context 'multiple classes' do
    let(:code) do
      <<-END
        class foo::bar_foo { }
        class foo::baz-foo { }
      END
    end

    it 'should create an error' do
      expect(problems).to contain_error(class_msg).on_line(2).in_column(15)
    end
  end
end


text:
package hookstage

import (
	"context"

	"github.com/prebid/openrtb/v17/openrtb2"
)

// ProcessedAuction hooks are invoked after the request is parsed
// and enriched with additional data.
//
// At this stage, account config is available,
// so it can be configured at the account-level execution plan,
// the account-level module config is passed to hooks.
//
// Rejection results in sending an empty BidResponse
// with the NBR code indicating the rejection reason.
type ProcessedAuction interface {
	HandleProcessedAuctionHook(
		context.Context,
		InvocationContext,
		ProcessedAuctionPayload,
	) (HookResult[ProcessedAuctionPayload], error)
}

// ProcessedAuctionPayload consists of the openrtb2.BidRequest object.
// Hooks are allowed to modify openrtb2.BidRequest using mutations.
type ProcessedAuctionPayload struct {
	BidRequest *openrtb2.BidRequest
}


text:
work_dir="$(pwd)"
tools_dir="$(cd "$(dirname "$0")" && pwd)"
source "$tools_dir/common.sh"
logfile="$log_dir/handle_dm.log"

administrators="$(echo "$ADMINISTRATORS" |
                    sed -E -e "s/^[$whitespaces]*,[$whitespaces]*|[$whitespaces]*,[$whitespaces]*$//g" \
                          -e "s/[$whitespaces]*,[$whitespaces]*/|/g")"
if [ "$administrators" = '' ]
then
  exit 1
fi

remove_first_arg() {
  sed -E 's/^[^ ]+ +//'
}

respond() {
  local sender="$1"
  shift
  "$tweet_sh" dm "$sender" "$*" > /dev/null
}

run_user_defined_command() {
  local sender="$1"
  local body="$2"
  log 'Running given command...'
  local command="$(echo "$body" | remove_first_arg)"
  find "$TWEET_BASE_DIR" -type f -name 'on_command*' | while read path
  do
    log 'Processing user defined command...'
    log " command line: \"$path\"  \"$sender\" \"$command\""
    cd "$TWEET_BASE_DIR"
    local handler_result
    handler_result="$("$path" "$sender" "$command" 2>&1)"
    if [ $? = 0 ]
    then
      log "$handler_result"
      log "Successfully processed."
      respond "$sender" "Successfully processed: \"$command\" by \"$(basename "$path")\""
    else
      log 'Failed to process.'
      log "$handler_result"
      respond "$sender" "Failed to run \"$command\" by \"$(basename "$path")\""
    fi
  done
}

do_echo() {
  local sender="$1"
  local body="$2"
  log 'Responding an echo...'
  local tweet_body="$(echo "$body" | remove_first_arg)"
  local result
  result="$(respond "$sender" "$tweet_body")"
  if [ $? = 0 ]
  then
    log "Successfully responded: \"$tweet_body\""
  else
    log "$result"
    log "Failed to respond \"$tweet_body\""
  fi
}

test_response() {
  local sender="$1"
  local body="$2"
  log 'Testing to reply...'
  cd $TWEET_BASE_DIR
  local tweet_body="$(echo "$body" | remove_first_arg | "$responder")"
  local result
  result="$(respond "$sender" "$tweet_body")"
  if [ $? = 0 ]
  then
    log "Successfully responded: \"$tweet_body\""
  else
    log "$result"
    log "Failed to respond \"$tweet_body\""
  fi
}

modify_response() {
  local sender="$1"
  local body="$2"
  local output="$(echo "$body" | "$tools_dir/modify_response.sh" 2>&1)"
  local result=$?
  log "$output"
  respond "$sender" "$(echo "$output" | paste -s -d ', ')"
  if [ $result = 0 ]
  then
    find "$TWEET_BASE_DIR" -type f -name 'on_response_modified*' | while read path
    do
      log "Processing \"$path\"..."
      cd $TWEET_BASE_DIR
      local handler_result
      handler_result="$("$path" 2>&1)"
      if [ $? = 0 ]
      then
        log 'Successfully proceeded.'
      else
        log 'Failed to process.'
        log "$handler_result"
      fi
    done
    respond "$sender" "Response patterns are successfully modified for \"$body\""
  else
    respond "$sender" "Failed to modify response patterns for \"$body\""
  fi
}

modify_monologue() {
  local sender="$1"
  local body="$2"
  local output="$(echo "$body" | "$tools_dir/modify_monologue.sh" 2>&1)"
  local result=$?
  log "$output"
  respond "$sender" "$(echo "$output" | paste -s -d ', ')"
  if [ $result = 0 ]
  then
    find "$TWEET_BASE_DIR" -type f -name 'on_monologue_modified*' | while read path
    do
      log "Processing \"$path\"..."
      cd $TWEET_BASE_DIR
      local handler_result
      handler_result="$("$path" 2>&1)"
      if [ $? = 0 ]
      then
        log 'Successfully proceeded.'
      else
        log 'Failed to process.'
        log "$handler_result"
      fi
    done
    respond "$sender" "Monologue patterns are successfully modified for \"$body\""
  else
    respond "$sender" "Failed to modify monologue patterns for \"$body\""
  fi
}

post() {
  local sender="$1"
  local body="$2"
  log 'Posting new tweet...'
  local output
  output="$("$tweet_sh" post "$body" 2>&1)"
  if [ $? = 0 ]
  then
    log "Successfully posted: \"$body\""
    respond "$sender" "Successfully posted: \"$body\""
  else
    log "$output"
    log "Failed to post \"$body\""
    respond "$sender" "Failed to post \"$body\""
  fi
}

reply_to() {
  local sender="$1"
  local body="$2"
  log 'Replying...'
  local reply_params="$(echo "$body" | sed -E 's/^reply +//i')"
  local reply_target="$(echo "$reply_params" | sed -E 's/^([^ ]+) .*/\1/')"
  local reply_body="$(echo "$reply_params" | sed -E 's/^[^ ]+ //')"
  local output
  output="$("$tweet_sh" reply "$reply_target" "$reply_body" 2>&1)"
  if [ $? = 0 ]
  then
    log "Successfully replied to \"$reply_target\": \"$reply_body\""
    respond "$sender" "Successfully replied: \"$reply_body\" to \"$reply_target\""
  else
    log "$output"
    log "Failed to reply to \"$reply_target\": \"$reply_body\""
    respond "$sender" "Failed to reply \"$reply_body\" to \"$reply_target\""
  fi
}

process_generic_command() {
  local sender="$1"
  local body="$2"
  log "Processing $body..."
  local output
  output="$("$tweet_sh" $body 2>&1)"
  if [ $? = 0 ]
  then
    log "Successfully processed: \"$body\""
    respond "$sender" "Successfully processed: \"$body\""
  else
    log "$output"
    log "Failed to process \"$body\""
    respond "$sender" "Failed to process \"$body\""
  fi
}

handle_search_result() {
  local sender="$1"
  local body="$2"
  log 'Processing a search result...'
  local target="$(echo "$body" | remove_first_arg)"
  local tweet="$("$tweet_sh" fetch "$target")"

  local output
  output="$(echo "$tweet" | env FORCE_PROCESS=yes "$tools_dir/handle_search_result.sh" 2>&1)"
  if [ $? = 0 ]
  then
    log "Successfully processed a search result: \"$target\""
    respond "$sender" "Successfully processed a search result: \"$target\""
  else
    log "$output"
    log "Failed to process a search result \"$target\""
    respond "$sender" "Failed to process a search result \"$target\""
  fi
}

delete_queued_command_for() {
  local target="$1"
  grep -r "$target" "$command_queue_dir" | cut -d ':' -f 1 | uniq | xargs rm -f
}


text:
package com.krillsson.sysapi.core.metrics.windows;

import com.krillsson.sysapi.core.speed.SpeedMeasurementManager;
import com.krillsson.sysapi.core.domain.network.NetworkInterfaceLoad;
import ohmwrapper.Bandwidth;
import ohmwrapper.MonitorManager;
import ohmwrapper.NetworkMonitor;
import ohmwrapper.NicInfo;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;

import java.util.NoSuchElementException;
import java.util.Optional;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;

@Ignore("Currently broken because of UnsatisfiedLinkerError")
public class WindowsNetworkProviderTest {

    DelegatingMonitorManager monitorManager;
    NetworkMonitor networkMonitor;
    HardwareAbstractionLayer hal;
    NetworkIF networkIF;
    NicInfo nicInfo;
    Bandwidth inBandwidth;
    Bandwidth outBandwidth;

    WindowsNetworkMetrics nicProvider;

    @Before
    public void setUp() throws Exception {
        monitorManager = mock(DelegatingMonitorManager.class);
        networkMonitor = mock(NetworkMonitor.class);
        when(monitorManager.getNetworkMonitor()).thenReturn(networkMonitor);
        hal = mock(HardwareAbstractionLayer.class);
        networkIF = mock(NetworkIF.class);
        nicInfo = mock(NicInfo.class);
        inBandwidth = mock(Bandwidth.class);
        outBandwidth = mock(Bandwidth.class);
        when(nicInfo.getInBandwidth()).thenReturn(inBandwidth);
        when(nicInfo.getOutBandwidth()).thenReturn(outBandwidth);
        when(inBandwidth.getValue()).thenReturn(123d);
        when(outBandwidth.getValue()).thenReturn(321d);

        nicProvider = new WindowsNetworkMetrics(hal, mock(SpeedMeasurementManager.class), monitorManager);
    }

    @Test
    public void happyPath() throws Exception {
        when(hal.getNetworkIFs()).thenReturn(new NetworkIF[]{networkIF});
        when(networkIF.getName()).thenReturn("en0");
        when(networkIF.getMacaddr()).thenReturn("01:23:45:67:89:ab");
        when(networkMonitor.getNics()).thenReturn(new NicInfo[]{nicInfo});
        when(nicInfo.getPhysicalAddress()).thenReturn("01:23:45:67:89:AB");

        Optional<NetworkInterfaceLoad> en0Optional = nicProvider.networkInterfaceLoadById("en0");
        NetworkInterfaceLoad en0 = en0Optional.get();
        assertThat(en0.getSpeed().getReceiveBytesPerSecond(), is(123L));
        assertThat(en0.getSpeed().getSendBytesPerSecond(), is(321L));
        verify(monitorManager).update();
    }

    @Test(expected = NoSuchElementException.class)
    public void noAvailableSpeedRecordsReturnsDefaultValues() throws Exception {
        when(hal.getNetworkIFs()).thenReturn(new NetworkIF[0]);
        assertFalse(nicProvider.networkInterfaceLoadById("en0").isPresent());
    }
}