text:
// I2Cdev library collection - Main I2C device class
// Abstracts bit and byte I2C R/W functions into a convenient class
// 6/9/2012 by Jeff Rowberg <jeff@rowberg.net>
//
// Changelog:
//     2012-06-09 - fix major issue with reading > 32 bytes at a time with Arduino Wire
//                - add compiler warnings when using outdated or IDE or limited I2Cdev implementation
//     2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums)
//     2011-10-03 - added automatic Arduino version detection for ease of use
//     2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications
//     2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x)
//     2011-08-03 - added optional timeout parameter to read* methods to easily change from default
//     2011-08-02 - added support for 16-bit registers
//                - fixed incorrect Doxygen comments on some methods
//                - added timeout value for read operations (thanks mem @ Arduino forums)
//     2011-07-30 - changed read/write function structures to return success or byte counts
//                - made all methods static for multi-device memory savings
//     2011-07-28 - initial release

#include "I2Cdev.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

    #ifdef I2CDEV_IMPLEMENTATION_WARNINGS
        #if ARDUINO < 100
            #warning Using outdated Arduino IDE with Wire library is functionally limiting.
            #warning Arduino IDE v1.0.1+ with I2Cdev Fastwire implementation is recommended.
            #warning This I2Cdev implementation does not support:
            #warning - Repeated starts conditions
            #warning - Timeout detection (some Wire requests block forever)
        #elif ARDUINO == 100
            #warning Using outdated Arduino IDE with Wire library is functionally limiting.
            #warning Arduino IDE v1.0.1+ with I2Cdev Fastwire implementation is recommended.
            #warning This I2Cdev implementation does not support:
            #warning - Repeated starts conditions
            #warning - Timeout detection (some Wire requests block forever)
        #elif ARDUINO > 100
            /*
            #warning Using current Arduino IDE with Wire library is functionally limiting.
            #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation is recommended.
            #warning This I2Cdev implementation does not support:
            #warning - Timeout detection (some Wire requests block forever)
            */
        #endif
    #endif

#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

    #error The I2CDEV_BUILTIN_FASTWIRE implementation is known to be broken right now. Patience, Iago!

#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE

    #ifdef I2CDEV_IMPLEMENTATION_WARNINGS
        #warning Using I2CDEV_BUILTIN_NBWIRE implementation may adversely affect interrupt detection.
        #warning This I2Cdev implementation does not support:
        #warning - Repeated starts conditions
    #endif

    // NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
    // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
    // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
    TwoWire Wire;

#endif

/** Default constructor.
 */
I2Cdev::I2Cdev() {
}

/** Read a single bit from an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitNum Bit position to read (0-7)
 * @param data Container for single bit value
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout) {
    uint8_t b;
    uint8_t count = readByte(devAddr, regAddr, &b, timeout);
    *data = b & (1 << bitNum);
    return count;
}

/** Read a single bit from a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitNum Bit position to read (0-15)
 * @param data Container for single bit value
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout) {
    uint16_t b;
    uint8_t count = readWord(devAddr, regAddr, &b, timeout);
    *data = b & (1 << bitNum);
    return count;
}

/** Read multiple bits from an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitStart First bit position to read (0-7)
 * @param length Number of bits to read (not more than 8)
 * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) {
    // 01101001 read byte
    // 76543210 bit numbers
    //    xxx   args: bitStart=4, length=3
    //    010   masked
    //   -> 010 shifted
    uint8_t count, b;
    if ((count = readByte(devAddr, regAddr, &b, timeout)) != 0) {
        uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
        b &= mask;
        b >>= (bitStart - length + 1);
        *data = b;
    }
    return count;
}

/** Read multiple bits from a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitStart First bit position to read (0-15)
 * @param length Number of bits to read (not more than 16)
 * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (1 = success, 0 = failure, -1 = timeout)
 */
int8_t I2Cdev::readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout) {
    // 1101011001101001 read byte
    // fedcba9876543210 bit numbers
    //    xxx           args: bitStart=12, length=3
    //    010           masked
    //           -> 010 shifted
    uint8_t count;
    uint16_t w;
    if ((count = readWord(devAddr, regAddr, &w, timeout)) != 0) {
        uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1);
        w &= mask;
        w >>= (bitStart - length + 1);
        *data = w;
    }
    return count;
}

/** Read single byte from an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param data Container for byte value read from device
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout) {
    return readBytes(devAddr, regAddr, 1, data, timeout);
}

/** Read single word from a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param data Container for word value read from device
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout) {
    return readWords(devAddr, regAddr, 1, data, timeout);
}

/** Read multiple bytes from an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr First register regAddr to read from
 * @param length Number of bytes to read
 * @param data Buffer to store read data in
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Number of bytes read (-1 indicates failure)
 */
int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print("I2C (0x");
        Serial.print(devAddr, HEX);
        Serial.print(") reading ");
        Serial.print(length, DEC);
        Serial.print(" bytes from 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif

    int8_t count = 0;
    uint32_t t1 = millis();

    #if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)

        #if (ARDUINO < 100)
            // Arduino v00xx (before v1.0), Wire library

            // I2C/TWI subsystem uses internal buffer that breaks with large data requests
            // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
            // smaller chunks instead of all at once
            for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
                Wire.beginTransmission(devAddr);
                Wire.send(regAddr);
                Wire.endTransmission();
                Wire.beginTransmission(devAddr);
                Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));

                for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
                    data[count] = Wire.receive();
                    #ifdef I2CDEV_SERIAL_DEBUG
                        Serial.print(data[count], HEX);
                        if (count + 1 < length) Serial.print(" ");
                    #endif
                }

                Wire.endTransmission();
            }
        #elif (ARDUINO == 100)
            // Arduino v1.0.0, Wire library
            // Adds standardized write() and read() stream methods instead of send() and receive()

            // I2C/TWI subsystem uses internal buffer that breaks with large data requests
            // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
            // smaller chunks instead of all at once
            for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
                Wire.beginTransmission(devAddr);
                Wire.write(regAddr);
                Wire.endTransmission();
                Wire.beginTransmission(devAddr);
                Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));

                for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
                    data[count] = Wire.read();
                    #ifdef I2CDEV_SERIAL_DEBUG
                        Serial.print(data[count], HEX);
                        if (count + 1 < length) Serial.print(" ");
                    #endif
                }

                Wire.endTransmission();
            }
        #elif (ARDUINO > 100)
            // Arduino v1.0.1+, Wire library
            // Adds official support for repeated start condition, yay!

            // I2C/TWI subsystem uses internal buffer that breaks with large data requests
            // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
            // smaller chunks instead of all at once
            for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
                Wire.beginTransmission(devAddr);
                Wire.write(regAddr);
                Wire.endTransmission();
                Wire.beginTransmission(devAddr);
                Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));

                for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
                    data[count] = Wire.read();
                    #ifdef I2CDEV_SERIAL_DEBUG
                        Serial.print(data[count], HEX);
                        if (count + 1 < length) Serial.print(" ");
                    #endif
                }

                Wire.endTransmission();
            }
        #endif

    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
        // Fastwire library (STILL UNDER DEVELOPMENT, NON-FUNCTIONAL!)

        // no loop required for fastwire
        uint8_t status = Fastwire::readBuf(devAddr, regAddr, data, length);
        if (status == 0) {
            count = length; // success
        } else {
            count = -1; // error
        }

    #endif

    // check for timeout
    if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout

    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(". Done (");
        Serial.print(count, DEC);
        Serial.println(" read).");
    #endif

    return count;
}

/** Read multiple words from a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr First register regAddr to read from
 * @param length Number of words to read
 * @param data Buffer to store read data in
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Number of words read (0 indicates failure)
 */
int8_t I2Cdev::readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print("I2C (0x");
        Serial.print(devAddr, HEX);
        Serial.print(") reading ");
        Serial.print(length, DEC);
        Serial.print(" words from 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif

    int8_t count = 0;
    uint32_t t1 = millis();

    #if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)

        #if (ARDUINO < 100)
            // Arduino v00xx (before v1.0), Wire library

            // I2C/TWI subsystem uses internal buffer that breaks with large data requests
            // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
            // smaller chunks instead of all at once
            for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
                Wire.beginTransmission(devAddr);
                Wire.send(regAddr);
                Wire.endTransmission();
                Wire.beginTransmission(devAddr);
                Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes

                bool msb = true; // starts with MSB, then LSB
                for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
                    if (msb) {
                        // first byte is bits 15-8 (MSb=15)
                        data[count] = Wire.receive() << 8;
                    } else {
                        // second byte is bits 7-0 (LSb=0)
                        data[count] |= Wire.receive();
                        #ifdef I2CDEV_SERIAL_DEBUG
                            Serial.print(data[count], HEX);
                            if (count + 1 < length) Serial.print(" ");
                        #endif
                        count++;
                    }
                    msb = !msb;
                }

                Wire.endTransmission();
            }
        #elif (ARDUINO == 100)
            // Arduino v1.0.0, Wire library
            // Adds standardized write() and read() stream methods instead of send() and receive()

            // I2C/TWI subsystem uses internal buffer that breaks with large data requests
            // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
            // smaller chunks instead of all at once
            for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
                Wire.beginTransmission(devAddr);
                Wire.write(regAddr);
                Wire.endTransmission();
                Wire.beginTransmission(devAddr);
                Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes

                bool msb = true; // starts with MSB, then LSB
                for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
                    if (msb) {
                        // first byte is bits 15-8 (MSb=15)
                        data[count] = Wire.read() << 8;
                    } else {
                        // second byte is bits 7-0 (LSb=0)
                        data[count] |= Wire.read();
                        #ifdef I2CDEV_SERIAL_DEBUG
                            Serial.print(data[count], HEX);
                            if (count + 1 < length) Serial.print(" ");
                        #endif
                        count++;
                    }
                    msb = !msb;
                }

                Wire.endTransmission();
            }
        #elif (ARDUINO > 100)
            // Arduino v1.0.1+, Wire library
            // Adds official support for repeated start condition, yay!

            // I2C/TWI subsystem uses internal buffer that breaks with large data requests
            // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
            // smaller chunks instead of all at once
            for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
                Wire.beginTransmission(devAddr);
                Wire.write(regAddr);
                Wire.endTransmission();
                Wire.beginTransmission(devAddr);
                Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes

                bool msb = true; // starts with MSB, then LSB
                for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
                    if (msb) {
                        // first byte is bits 15-8 (MSb=15)
                        data[count] = Wire.read() << 8;
                    } else {
                        // second byte is bits 7-0 (LSb=0)
                        data[count] |= Wire.read();
                        #ifdef I2CDEV_SERIAL_DEBUG
                            Serial.print(data[count], HEX);
                            if (count + 1 < length) Serial.print(" ");
                        #endif
                        count++;
                    }
                    msb = !msb;
                }

                Wire.endTransmission();
            }
        #endif

    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
        // Fastwire library (STILL UNDER DEVELOPMENT, NON-FUNCTIONAL!)

        // no loop required for fastwire
        uint16_t intermediate[(uint8_t)length];
        uint8_t status = Fastwire::readBuf(devAddr, regAddr, (uint8_t *)intermediate, (uint8_t)(length * 2));
        if (status == 0) {
            count = length; // success
            for (uint8_t i = 0; i < length; i++) {
                data[i] = (intermediate[2*i] << 8) | intermediate[2*i + 1];
            }
        } else {
            count = -1; // error
        }

    #endif

    if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout

    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(". Done (");
        Serial.print(count, DEC);
        Serial.println(" read).");
    #endif

    return count;
}

/** write a single bit in an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to write to
 * @param bitNum Bit position to write (0-7)
 * @param value New bit value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) {
    uint8_t b;
    readByte(devAddr, regAddr, &b);
    b = (data != 0) ? (b | (1 << bitNum)) : (b & ~(1 << bitNum));
    return writeByte(devAddr, regAddr, b);
}

/** write a single bit in a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to write to
 * @param bitNum Bit position to write (0-15)
 * @param value New bit value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) {
    uint16_t w;
    readWord(devAddr, regAddr, &w);
    w = (data != 0) ? (w | (1 << bitNum)) : (w & ~(1 << bitNum));
    return writeWord(devAddr, regAddr, w);
}

/** Write multiple bits in an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to write to
 * @param bitStart First bit position to write (0-7)
 * @param length Number of bits to write (not more than 8)
 * @param data Right-aligned value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) {
    //      010 value to write
    // 76543210 bit numbers
    //    xxx   args: bitStart=4, length=3
    // 00011100 mask byte
    // 10101111 original value (sample)
    // 10100011 original & ~mask
    // 10101011 masked | value
    uint8_t b;
    if (readByte(devAddr, regAddr, &b) != 0) {
        uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
        data <<= (bitStart - length + 1); // shift data into correct position
        data &= mask; // zero all non-important bits in data
        b &= ~(mask); // zero all important bits in existing byte
        b |= data; // combine data with existing byte
        return writeByte(devAddr, regAddr, b);
    } else {
        return false;
    }
}

/** Write multiple bits in a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to write to
 * @param bitStart First bit position to write (0-15)
 * @param length Number of bits to write (not more than 16)
 * @param data Right-aligned value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) {
    //              010 value to write
    // fedcba9876543210 bit numbers
    //    xxx           args: bitStart=12, length=3
    // 0001110000000000 mask byte
    // 1010111110010110 original value (sample)
    // 1010001110010110 original & ~mask
    // 1010101110010110 masked | value
    uint16_t w;
    if (readWord(devAddr, regAddr, &w) != 0) {
        uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
        data <<= (bitStart - length + 1); // shift data into correct position
        data &= mask; // zero all non-important bits in data
        w &= ~(mask); // zero all important bits in existing word
        w |= data; // combine data with existing word
        return writeWord(devAddr, regAddr, w);
    } else {
        return false;
    }
}

/** Write single byte to an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register address to write to
 * @param data New byte value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data) {
    return writeBytes(devAddr, regAddr, 1, &data);
}

/** Write single word to a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr Register address to write to
 * @param data New word value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data) {
    return writeWords(devAddr, regAddr, 1, &data);
}

/** Write multiple bytes to an 8-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr First register address to write to
 * @param length Number of bytes to write
 * @param data Buffer to copy new data from
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print("I2C (0x");
        Serial.print(devAddr, HEX);
        Serial.print(") writing ");
        Serial.print(length, DEC);
        Serial.print(" bytes to 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif
    uint8_t status = 0;
    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
        Wire.beginTransmission(devAddr);
        Wire.send((uint8_t) regAddr); // send address
    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
        Wire.beginTransmission(devAddr);
        Wire.write((uint8_t) regAddr); // send address
    #endif
    for (uint8_t i = 0; i < length; i++) {
        #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
            Wire.send((uint8_t) data[i]);
        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
            Wire.write((uint8_t) data[i]);
        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
            status = Fastwire::write(devAddr, regAddr, data[i]);
            Serial.println(status);
        #endif
        #ifdef I2CDEV_SERIAL_DEBUG
            Serial.print(data[i], HEX);
            if (i + 1 < length) Serial.print(" ");
        #endif
    }
    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
        Wire.endTransmission();
    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
        status = Wire.endTransmission();
    #endif
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.println(". Done.");
    #endif
    return status == 0;
}

/** Write multiple words to a 16-bit device register.
 * @param devAddr I2C slave device address
 * @param regAddr First register address to write to
 * @param length Number of words to write
 * @param data Buffer to copy new data from
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t* data) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print("I2C (0x");
        Serial.print(devAddr, HEX);
        Serial.print(") writing ");
        Serial.print(length, DEC);
        Serial.print(" words to 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif
    uint8_t status = 0;
    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
        Wire.beginTransmission(devAddr);
        Wire.send(regAddr); // send address
    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
        Wire.beginTransmission(devAddr);
        Wire.write(regAddr); // send address
    #endif
    for (uint8_t i = 0; i < length * 2; i++) {
        #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
            Wire.send((uint8_t)(data[i++] >> 8)); // send MSB
            Wire.send((uint8_t)data[i]);          // send LSB
        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
            Wire.write((uint8_t)(data[i++] >> 8)); // send MSB
            Wire.write((uint8_t)data[i]);          // send LSB
        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
            status = Fastwire::write(devAddr, regAddr, (uint8_t)(data[i++] >> 8));
            status = Fastwire::write(devAddr, regAddr + 1, (uint8_t)data[i]);
        #endif
        #ifdef I2CDEV_SERIAL_DEBUG
            Serial.print(data[i], HEX);
            if (i + 1 < length) Serial.print(" ");
        #endif
    }
    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
        Wire.endTransmission();
    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
        status = Wire.endTransmission();
    #endif
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.println(". Done.");
    #endif
    return status == 0;
}

/** Default timeout value for read operations.
 * Set this to 0 to disable timeout detection.
 */
uint16_t I2Cdev::readTimeout = I2CDEV_DEFAULT_READ_TIMEOUT;

#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    /*
    FastWire 0.2
    This is a library to help faster programs to read I2C devices.
    Copyright(C) 2011 Francesco Ferrara
    occhiobello at gmail dot com
    */

    boolean Fastwire::waitInt() {
        int l = 250;
        while (!(TWCR & (1 << TWINT)) && l-- > 0);
        return l > 0;
    }

    void Fastwire::setup(int khz, boolean pullup) {
        TWCR = 0;
        #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
            // activate internal pull-ups for twi (PORTC bits 4 & 5)
            // as per note from atmega8 manual pg167
            if (pullup) PORTC |= ((1 << 4) | (1 << 5));
            else        PORTC &= ~((1 << 4) | (1 << 5));
        #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
            // activate internal pull-ups for twi (PORTC bits 0 & 1)
            if (pullup) PORTC |= ((1 << 0) | (1 << 1));
            else        PORTC &= ~((1 << 0) | (1 << 1));
        #else
            // activate internal pull-ups for twi (PORTD bits 0 & 1)
            // as per note from atmega128 manual pg204
            if (pullup) PORTD |= ((1 << 0) | (1 << 1));
            else        PORTD &= ~((1 << 0) | (1 << 1));
        #endif

        TWSR = 0; // no prescaler => prescaler = 1
        TWBR = ((16000L / khz) - 16) / 2; // change the I2C clock rate
        TWCR = 1 << TWEN; // enable twi module, no interrupt
    }

    byte Fastwire::write(byte device, byte address, byte value) {
        byte twst, retry;

        retry = 2;
        do {
            TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
            if (!waitInt()) return 1;
            twst = TWSR & 0xF8;
            if (twst != TW_START && twst != TW_REP_START) return 2;

            TWDR = device & 0xFE; // send device address without read bit (1)
            TWCR = (1 << TWINT) | (1 << TWEN);
            if (!waitInt()) return 3;
            twst = TWSR & 0xF8;
        } while (twst == TW_MT_SLA_NACK && retry-- > 0);
        if (twst != TW_MT_SLA_ACK) return 4;

        TWDR = address; // send data to the previously addressed device
        TWCR = (1 << TWINT) | (1 << TWEN);
        if (!waitInt()) return 5;
        twst = TWSR & 0xF8;
        if (twst != TW_MT_DATA_ACK) return 6;

        TWDR = value; // send data to the previously addressed device
        TWCR = (1 << TWINT) | (1 << TWEN);
        if (!waitInt()) return 7;
        twst = TWSR & 0xF8;
        if (twst != TW_MT_DATA_ACK) return 8;

        return 0;
    }

    byte Fastwire::readBuf(byte device, byte address, byte *data, byte num) {
        byte twst, retry;

        retry = 2;
        do {
            TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
            if (!waitInt()) return 16;
            twst = TWSR & 0xF8;
            if (twst != TW_START && twst != TW_REP_START) return 17;

            TWDR = device & 0xfe; // send device address to write
            TWCR = (1 << TWINT) | (1 << TWEN);
            if (!waitInt()) return 18;
            twst = TWSR & 0xF8;
        } while (twst == TW_MT_SLA_NACK && retry-- > 0);
        if (twst != TW_MT_SLA_ACK) return 19;

        TWDR = address; // send data to the previously addressed device
        TWCR = (1 << TWINT) | (1 << TWEN);
        if (!waitInt()) return 20;
        twst = TWSR & 0xF8;
        if (twst != TW_MT_DATA_ACK) return 21;

        /***/

        retry = 2;
        do {
            TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
            if (!waitInt()) return 22;
            twst = TWSR & 0xF8;
            if (twst != TW_START && twst != TW_REP_START) return 23;

            TWDR = device | 0x01; // send device address with the read bit (1)
            TWCR = (1 << TWINT) | (1 << TWEN);
            if (!waitInt()) return 24;
            twst = TWSR & 0xF8;
        } while (twst == TW_MR_SLA_NACK && retry-- > 0);
        if (twst != TW_MR_SLA_ACK) return 25;

        for(uint8_t i = 0; i < num; i++) {
            if (i == num - 1)
               TWCR = (1 << TWINT) | (1 << TWEN);
            else
                TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
            if (!waitInt()) return 26;
            twst = TWSR & 0xF8;
            if (twst != TW_MR_DATA_ACK && twst != TW_MR_DATA_NACK) return twst;
            data[i] = TWDR;
        }

        return 0;
   }
#endif

#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
    // NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
    // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
    // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html

    /*
    call this version 1.0

    Offhand, the only funky part that I can think of is in nbrequestFrom, where the buffer
    length and index are set *before* the data is actually read. The problem is that these
    are variables local to the TwoWire object, and by the time we actually have read the
    data, and know what the length actually is, we have no simple access to the object's
    variables. The actual bytes read *is* given to the callback function, though.

    The ISR code for a slave receiver is commented out. I don't have that setup, and can't
    verify it at this time. Save it for 2.0!

    The handling of the read and write processes here is much like in the demo sketch code:
    the process is broken down into sequential functions, where each registers the next as a
    callback, essentially.

    For example, for the Read process, twi_read00 just returns if TWI is not yet in a
    ready state. When there's another interrupt, and the interface *is* ready, then it
    sets up the read, starts it, and registers twi_read01 as the function to call after
    the *next* interrupt. twi_read01, then, just returns if the interface is still in a
    "reading" state. When the reading is done, it copies the information to the buffer,
    cleans up, and calls the user-requested callback function with the actual number of
    bytes read.

    The writing is similar.

    Questions, comments and problems can go to Gene@Telobot.com.

    Thumbs Up!
    Gene Knight

    */

    uint8_t TwoWire::rxBuffer[NBWIRE_BUFFER_LENGTH];
    uint8_t TwoWire::rxBufferIndex = 0;
    uint8_t TwoWire::rxBufferLength = 0;

    uint8_t TwoWire::txAddress = 0;
    uint8_t TwoWire::txBuffer[NBWIRE_BUFFER_LENGTH];
    uint8_t TwoWire::txBufferIndex = 0;
    uint8_t TwoWire::txBufferLength = 0;

    //uint8_t TwoWire::transmitting = 0;
    void (*TwoWire::user_onRequest)(void);
    void (*TwoWire::user_onReceive)(int);

    static volatile uint8_t twi_transmitting;
    static volatile uint8_t twi_state;
    static uint8_t twi_slarw;
    static volatile uint8_t twi_error;
    static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
    static volatile uint8_t twi_masterBufferIndex;
    static uint8_t twi_masterBufferLength;
    static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
    static volatile uint8_t twi_rxBufferIndex;
    //static volatile uint8_t twi_Interrupt_Continue_Command;
    static volatile uint8_t twi_Return_Value;
    static volatile uint8_t twi_Done;
    void (*twi_cbendTransmissionDone)(int);
    void (*twi_cbreadFromDone)(int);

    void twi_init() {
        // initialize state
        twi_state = TWI_READY;

        // activate internal pull-ups for twi
        // as per note from atmega8 manual pg167
        sbi(PORTC, 4);
        sbi(PORTC, 5);

        // initialize twi prescaler and bit rate
        cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits
        cbi(TWSR, TWPS1);

        /* twi bit rate formula from atmega128 manual pg 204
        SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
        note: TWBR should be 10 or higher for master mode
        It is 72 for a 16mhz Wiring board with 100kHz TWI */

        TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register
        // enable twi module, acks, and twi interrupt

        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

        /* TWEN - TWI Enable Bit
        TWIE - TWI Interrupt Enable
        TWEA - TWI Enable Acknowledge Bit
        TWINT - TWI Interrupt Flag
        TWSTA - TWI Start Condition
        */
    }

    typedef struct {
        uint8_t address;
        uint8_t* data;
        uint8_t length;
        uint8_t wait;
        uint8_t i;
    } twi_Write_Vars;

    twi_Write_Vars *ptwv = 0;
    static void (*fNextInterruptFunction)(void) = 0;

    void twi_Finish(byte bRetVal) {
        if (ptwv) {
            free(ptwv);
            ptwv = 0;
        }
        twi_Done = 0xFF;
        twi_Return_Value = bRetVal;
        fNextInterruptFunction = 0;
    }

    uint8_t twii_WaitForDone(uint16_t timeout) {
        uint32_t endMillis = millis() + timeout;
        while (!twi_Done && (timeout == 0 || millis() < endMillis)) continue;
        return twi_Return_Value;
    }

    void twii_SetState(uint8_t ucState) {
        twi_state = ucState;
    }

    void twii_SetError(uint8_t ucError) {
        twi_error = ucError ;
    }

    void twii_InitBuffer(uint8_t ucPos, uint8_t ucLength) {
        twi_masterBufferIndex = 0;
        twi_masterBufferLength = ucLength;
    }

    void twii_CopyToBuf(uint8_t* pData, uint8_t ucLength) {
        uint8_t i;
        for (i = 0; i < ucLength; ++i) {
            twi_masterBuffer[i] = pData[i];
        }
    }

    void twii_CopyFromBuf(uint8_t *pData, uint8_t ucLength) {
        uint8_t i;
        for (i = 0; i < ucLength; ++i) {
            pData[i] = twi_masterBuffer[i];
        }
    }

    void twii_SetSlaRW(uint8_t ucSlaRW) {
        twi_slarw = ucSlaRW;
    }

    void twii_SetStart() {
        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
    }

    void twi_write01() {
        if (TWI_MTX == twi_state) return; // blocking test
        twi_transmitting = 0 ;
        if (twi_error == 0xFF)
            twi_Finish (0);    // success
        else if (twi_error == TW_MT_SLA_NACK)
            twi_Finish (2);    // error: address send, nack received
        else if (twi_error == TW_MT_DATA_NACK)
            twi_Finish (3);    // error: data send, nack received
        else
            twi_Finish (4);    // other twi error
        if (twi_cbendTransmissionDone) return twi_cbendTransmissionDone(twi_Return_Value);
        return;
    }

    void twi_write00() {
        if (TWI_READY != twi_state) return; // blocking test
        if (TWI_BUFFER_LENGTH < ptwv -> length) {
            twi_Finish(1); // end write with error 1
            return;
        }
        twi_Done = 0x00; // show as working
        twii_SetState(TWI_MTX); // to transmitting
        twii_SetError(0xFF); // to No Error
        twii_InitBuffer(0, ptwv -> length); // pointer and length
        twii_CopyToBuf(ptwv -> data, ptwv -> length); // get the data
        twii_SetSlaRW((ptwv -> address << 1) | TW_WRITE); // write command
        twii_SetStart(); // start the cycle
        fNextInterruptFunction = twi_write01; // next routine
        return twi_write01();
    }

    void twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait) {
        uint8_t i;
        ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
        ptwv -> address = address;
        ptwv -> data = data;
        ptwv -> length = length;
        ptwv -> wait = wait;
        fNextInterruptFunction = twi_write00;
        return twi_write00();
    }

    void twi_read01() {
        if (TWI_MRX == twi_state) return; // blocking test
        if (twi_masterBufferIndex < ptwv -> length) ptwv -> length = twi_masterBufferIndex;
        twii_CopyFromBuf(ptwv -> data, ptwv -> length);
        twi_Finish(ptwv -> length);
        if (twi_cbreadFromDone) return twi_cbreadFromDone(twi_Return_Value);
        return;
    }

    void twi_read00() {
        if (TWI_READY != twi_state) return; // blocking test
        if (TWI_BUFFER_LENGTH < ptwv -> length) twi_Finish(0); // error return
        twi_Done = 0x00; // show as working
        twii_SetState(TWI_MRX); // reading
        twii_SetError(0xFF); // reset error
        twii_InitBuffer(0, ptwv -> length - 1); // init to one less than length
        twii_SetSlaRW((ptwv -> address << 1) | TW_READ); // read command
        twii_SetStart(); // start cycle
        fNextInterruptFunction = twi_read01;
        return twi_read01();
    }

    void twi_readFrom(uint8_t address, uint8_t* data, uint8_t length) {
        uint8_t i;

        ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
        ptwv -> address = address;
        ptwv -> data = data;
        ptwv -> length = length;
        fNextInterruptFunction = twi_read00;
        return twi_read00();
    }

    void twi_reply(uint8_t ack) {
        // transmit master read ready signal, with or without ack
        if (ack){
            TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
        } else {
            TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
        }
    }

    void twi_stop(void) {
        // send stop condition
        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);

        // wait for stop condition to be exectued on bus
        // TWINT is not set after a stop condition!
        while (TWCR & _BV(TWSTO)) {
            continue;
        }

        // update twi state
        twi_state = TWI_READY;
    }

    void twi_releaseBus(void) {
        // release bus
        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);

        // update twi state
        twi_state = TWI_READY;
    }

    SIGNAL(TWI_vect) {
        switch (TW_STATUS) {
            // All Master
            case TW_START:     // sent start condition
            case TW_REP_START: // sent repeated start condition
                // copy device address and r/w bit to output register and ack
                TWDR = twi_slarw;
                twi_reply(1);
                break;

            // Master Transmitter
            case TW_MT_SLA_ACK:  // slave receiver acked address
            case TW_MT_DATA_ACK: // slave receiver acked data
                // if there is data to send, send it, otherwise stop
                if (twi_masterBufferIndex < twi_masterBufferLength) {
                    // copy data to output register and ack
                    TWDR = twi_masterBuffer[twi_masterBufferIndex++];
                    twi_reply(1);
                } else {
                    twi_stop();
                }
                break;

            case TW_MT_SLA_NACK:  // address sent, nack received
                twi_error = TW_MT_SLA_NACK;
                twi_stop();
                break;

            case TW_MT_DATA_NACK: // data sent, nack received
                twi_error = TW_MT_DATA_NACK;
                twi_stop();
                break;

            case TW_MT_ARB_LOST: // lost bus arbitration
                twi_error = TW_MT_ARB_LOST;
                twi_releaseBus();
                break;

            // Master Receiver
            case TW_MR_DATA_ACK: // data received, ack sent
                // put byte into buffer
                twi_masterBuffer[twi_masterBufferIndex++] = TWDR;

            case TW_MR_SLA_ACK:  // address sent, ack received
                // ack if more bytes are expected, otherwise nack
                if (twi_masterBufferIndex < twi_masterBufferLength) {
                    twi_reply(1);
                } else {
                    twi_reply(0);
                }
                break;

            case TW_MR_DATA_NACK: // data received, nack sent
                // put final byte into buffer
                twi_masterBuffer[twi_masterBufferIndex++] = TWDR;

            case TW_MR_SLA_NACK: // address sent, nack received
                twi_stop();
                break;

        // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case

        // Slave Receiver (NOT IMPLEMENTED YET)
        /*
            case TW_SR_SLA_ACK:   // addressed, returned ack
            case TW_SR_GCALL_ACK: // addressed generally, returned ack
            case TW_SR_ARB_LOST_SLA_ACK:   // lost arbitration, returned ack
            case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
                // enter slave receiver mode
                twi_state = TWI_SRX;

                // indicate that rx buffer can be overwritten and ack
                twi_rxBufferIndex = 0;
                twi_reply(1);
                break;

            case TW_SR_DATA_ACK:       // data received, returned ack
            case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
                // if there is still room in the rx buffer
                if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
                    // put byte in buffer and ack
                    twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
                    twi_reply(1);
                } else {
                    // otherwise nack
                    twi_reply(0);
                }
                break;

            case TW_SR_STOP: // stop or repeated start condition received
                // put a null char after data if there's room
                if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
                    twi_rxBuffer[twi_rxBufferIndex] = 0;
                }

                // sends ack and stops interface for clock stretching
                twi_stop();

                // callback to user defined callback
                twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);

                // since we submit rx buffer to "wire" library, we can reset it
                twi_rxBufferIndex = 0;

                // ack future responses and leave slave receiver state
                twi_releaseBus();
                break;

            case TW_SR_DATA_NACK:       // data received, returned nack
            case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
                // nack back at master
                twi_reply(0);
                break;

            // Slave Transmitter
            case TW_ST_SLA_ACK:          // addressed, returned ack
            case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
                // enter slave transmitter mode
                twi_state = TWI_STX;

                // ready the tx buffer index for iteration
                twi_txBufferIndex = 0;

                // set tx buffer length to be zero, to verify if user changes it
                twi_txBufferLength = 0;

                // request for txBuffer to be filled and length to be set
                // note: user must call twi_transmit(bytes, length) to do this
                twi_onSlaveTransmit();

                // if they didn't change buffer & length, initialize it
                if (0 == twi_txBufferLength) {
                    twi_txBufferLength = 1;
                    twi_txBuffer[0] = 0x00;
                }

                // transmit first byte from buffer, fall through

            case TW_ST_DATA_ACK: // byte sent, ack returned
                // copy data to output register
                TWDR = twi_txBuffer[twi_txBufferIndex++];

                // if there is more to send, ack, otherwise nack
                if (twi_txBufferIndex < twi_txBufferLength) {
                    twi_reply(1);
                } else {
                    twi_reply(0);
                }
                break;

            case TW_ST_DATA_NACK: // received nack, we are done
            case TW_ST_LAST_DATA: // received ack, but we are done already!
                // ack future responses
                twi_reply(1);
                // leave slave receiver state
                twi_state = TWI_READY;
                break;
            */

            // all
            case TW_NO_INFO:   // no state information
                break;

            case TW_BUS_ERROR: // bus error, illegal stop/start
                twi_error = TW_BUS_ERROR;
                twi_stop();
                break;
        }

        if (fNextInterruptFunction) return fNextInterruptFunction();
    }

    TwoWire::TwoWire() { }

    void TwoWire::begin(void) {
        rxBufferIndex = 0;
        rxBufferLength = 0;

        txBufferIndex = 0;
        txBufferLength = 0;

        twi_init();
    }

    void TwoWire::beginTransmission(uint8_t address) {
        //beginTransmission((uint8_t)address);

        // indicate that we are transmitting
        twi_transmitting = 1;

        // set address of targeted slave
        txAddress = address;

        // reset tx buffer iterator vars
        txBufferIndex = 0;
        txBufferLength = 0;
    }

    uint8_t TwoWire::endTransmission(uint16_t timeout) {
        // transmit buffer (blocking)
        //int8_t ret =
        twi_cbendTransmissionDone = NULL;
        twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
        int8_t ret = twii_WaitForDone(timeout);

        // reset tx buffer iterator vars
        txBufferIndex = 0;
        txBufferLength = 0;

        // indicate that we are done transmitting
        // twi_transmitting = 0;
        return ret;
    }

    void TwoWire::nbendTransmission(void (*function)(int)) {
        twi_cbendTransmissionDone = function;
        twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
        return;
    }

    void TwoWire::send(uint8_t data) {
        if (twi_transmitting) {
            // in master transmitter mode
            // don't bother if buffer is full
            if (txBufferLength >= NBWIRE_BUFFER_LENGTH) {
                return;
            }

            // put byte in tx buffer
            txBuffer[txBufferIndex] = data;
            ++txBufferIndex;

            // update amount in buffer
            txBufferLength = txBufferIndex;
        } else {
            // in slave send mode
            // reply to master
            //twi_transmit(&data, 1);
        }
    }

    uint8_t TwoWire::receive(void) {
        // default to returning null char
        // for people using with char strings
        uint8_t value = 0;

        // get each successive byte on each call
        if (rxBufferIndex < rxBufferLength) {
            value = rxBuffer[rxBufferIndex];
            ++rxBufferIndex;
        }

        return value;
    }

    uint8_t TwoWire::requestFrom(uint8_t address, int quantity, uint16_t timeout) {
        // clamp to buffer length
        if (quantity > NBWIRE_BUFFER_LENGTH) {
            quantity = NBWIRE_BUFFER_LENGTH;
        }

        // perform blocking read into buffer
        twi_cbreadFromDone = NULL;
        twi_readFrom(address, rxBuffer, quantity);
        uint8_t read = twii_WaitForDone(timeout);

        // set rx buffer iterator vars
        rxBufferIndex = 0;
        rxBufferLength = read;

        return read;
    }

    void TwoWire::nbrequestFrom(uint8_t address, int quantity, void (*function)(int)) {
        // clamp to buffer length
        if (quantity > NBWIRE_BUFFER_LENGTH) {
            quantity = NBWIRE_BUFFER_LENGTH;
        }

        // perform blocking read into buffer
        twi_cbreadFromDone = function;
        twi_readFrom(address, rxBuffer, quantity);
        //uint8_t read = twii_WaitForDone();

        // set rx buffer iterator vars
        //rxBufferIndex = 0;
        //rxBufferLength = read;

        rxBufferIndex = 0;
        rxBufferLength = quantity; // this is a hack

        return; //read;
    }

    uint8_t TwoWire::available(void) {
        return rxBufferLength - rxBufferIndex;
    }

#endif


text:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

/// <summary>
/// http://stackoverflow.com/questions/11607133/global-mouse-event-handler
/// </summary>
namespace EventHook.Hooks
{
    internal class RawMouseEventArgs : EventArgs
    {
        internal MouseMessages Message { get; set; }
        internal Point Point { get; set; }
        internal uint MouseData { get; set; }
    }

    /// <summary>
    /// The mouse messages.
    /// </summary>
    public enum MouseMessages
    {
        WM_LBUTTONDOWN = 0x0201,
        WM_LBUTTONUP = 0x0202,
        WM_MOUSEMOVE = 0x0200,
        WM_MOUSEWHEEL = 0x020A,
        WM_RBUTTONDOWN = 0x0204,
        WM_RBUTTONUP = 0x0205,
        WM_WHEELBUTTONDOWN = 0x207,
        WM_WHEELBUTTONUP = 0x208,
        WM_XBUTTONDOWN = 0x020B,
        WM_XBUTTONUP = 0x020C
    }

    /// <summary>
    /// The point co-ordinate.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct Point
    {
        public readonly int x;
        public readonly int y;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct MSLLHOOKSTRUCT
    {
        internal Point pt;
        internal readonly uint mouseData;
        internal readonly uint flags;
        internal readonly uint time;
        internal readonly IntPtr dwExtraInfo;
    }

    internal class MouseHook
    {
        private const int WH_MOUSE_LL = 14;
        private static IntPtr _hookId = IntPtr.Zero;

        private readonly LowLevelMouseProc Proc;

        internal MouseHook()
        {
            Proc = HookCallback;
        }

        internal event EventHandler<RawMouseEventArgs> MouseAction = delegate { };

        internal void Start()
        {
            _hookId = SetHook(Proc);
        }

        internal void Stop()
        {
            UnhookWindowsHookEx(_hookId);
        }

        private static IntPtr SetHook(LowLevelMouseProc proc)
        {
            var hook = SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle("user32"), 0);
            if (hook == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            return hook;
        }

        private IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
        {
            MSLLHOOKSTRUCT hookStruct;
            if (nCode < 0)
            {
                return CallNextHookEx(_hookId, nCode, wParam, lParam);
            }

            hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));

            MouseAction(null, new RawMouseEventArgs { Message = (MouseMessages)wParam, Point = hookStruct.pt, MouseData = hookStruct.mouseData });

            return CallNextHookEx(_hookId, nCode, wParam, lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
    }
}

redpajama_set_name: RedPajamaGithub


text:
Adds token matching to nodejs readline and visualizes it by jumping the cursor to it à la emacs.

## Installation

    npm i readline-matchtoken

## Demo

    npm explore readline-matchtoken && npm run demo

## Usage

```js
var rmt = require('')
  , repl = require('repl');

var r = repl.start({
    prompt: "> ",
    input: process.stdin,
    output: process.stdout
  });

rmt(r.rli);

r.displayPrompt();
```

Although this example starts a `repl`, a [readline
interface](http://nodejs.org/api/readline.html#readline_readline_createinterface_options) is all that is needed for
token matching to be applied.


text:
package com.walkertribe.ian.util;

import java.util.Iterator;

/**
 * An engineering nodes coordinate.
 * @author rjwut
 */
public final class GridCoord implements Comparable<GridCoord> {
    public static final int MAX_X = 5;
    public static final int MAX_Y = 5;
    public static final int MAX_Z = 10;
    public static final int LENGTH = MAX_X * MAX_Y * MAX_Z;

    private static final GridCoord[] COORDS = new GridCoord[LENGTH];

    static {
        for (int x = 0; x < MAX_X; x++) {
            for (int y = 0; y < MAX_Y; y++) {
                for (int z = 0; z < MAX_Z; z++) {
                    GridCoord coord = new GridCoord(x, y, z);
                    COORDS[coord.index] = coord;
                }
            }
        }
    }

    /**
     * Computes the index value for the given coordinates.
     */
    public static int computeIndex(int x, int y, int z) {
        if (x < 0 || x >= MAX_X || y < 0 || y >= MAX_Y || z < 0 || z >= MAX_Z) {
            throw new IllegalArgumentException(
                    "Coordinates out of range: (" + x + "," + y + "," + z + ")"
            );
        }

        return x * MAX_Y * MAX_Z + y * MAX_Z + z;
    }

    /**
     * Returns the GridCoord object that corresponds to the given coordinates.
     */
    public static GridCoord get(int x, int y, int z) {
        return COORDS[computeIndex(x, y, z)];
    }

    /**
     * Returns an Iterator for all GridCoords.
     */
    public static Iterator<GridCoord> iterator() {
        return new Iterator<GridCoord>() {
            private int i = 0;

            @Override
            public boolean hasNext() {
                return i < LENGTH;
            }

            @Override
            public GridCoord next() {
                return COORDS[i++];
            }
        };
    }

    protected int x;
    protected int y;
    protected int z;
    protected int index;

    private GridCoord(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
        index = computeIndex(x, y, z);
    }

    /**
     * The X value of this coordinate.
     */
    public int x() {
        return x;
    }

    /**
     * The Y value of this coordinate.
     */
    public int y() {
        return y;
    }

    /**
     * The Z value of this coordinate.
     */
    public int z() {
        return z;
    }

    /**
     * Returns the index value for this GridCoord.
     */
    public int index() {
        return index;
    }

    /**
     * Returns true if this object is located at the given coordinates.
     */
    public boolean at(int x, int y, int z) {
        return this.x == x && this.y == y && this.z == z;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof GridCoord)) {
            return false;
        }

        return index == ((GridCoord) obj).index;
    }

    @Override
    public int hashCode() {
        return index;
    }

    @Override
    public String toString() {
        return "[" + x + "," + y + "," + z + "]";
    }

    @Override
    public int compareTo(GridCoord o) {
        return index - o.index;
    }
}


text:
package awstasks

import (
	"fmt"

	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/golang/glog"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
	"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
	"k8s.io/kops/upup/pkg/fi/utils"
)

//go:generate fitask -type=Subnet
type Subnet struct {
	Name             *string
	ID               *string
	VPC              *VPC
	AvailabilityZone *string
	CIDR             *string
	Shared           *bool
}

var _ fi.CompareWithID = &Subnet{}

func (e *Subnet) CompareWithID() *string {
	return e.ID
}

func (e *Subnet) Find(c *fi.Context) (*Subnet, error) {
	cloud := c.Cloud.(awsup.AWSCloud)

	request := &ec2.DescribeSubnetsInput{}
	if e.ID != nil {
		request.SubnetIds = []*string{e.ID}
	} else {
		request.Filters = cloud.BuildFilters(e.Name)
	}

	response, err := cloud.EC2().DescribeSubnets(request)
	if err != nil {
		return nil, fmt.Errorf("error listing Subnets: %v", err)
	}
	if response == nil || len(response.Subnets) == 0 {
		return nil, nil
	}

	if len(response.Subnets) != 1 {
		glog.Fatalf("found multiple Subnets matching tags")
	}

	subnet := response.Subnets[0]
	actual := &Subnet{
		ID:               subnet.SubnetId,
		AvailabilityZone: subnet.AvailabilityZone,
		VPC:              &VPC{ID: subnet.VpcId},
		CIDR:             subnet.CidrBlock,
		Name:             findNameTag(subnet.Tags),
		Shared:           e.Shared,
	}

	glog.V(2).Infof("found matching subnet %q", *actual.ID)
	e.ID = actual.ID

	return actual, nil
}

func (e *Subnet) Run(c *fi.Context) error {
	return fi.DefaultDeltaRunMethod(e, c)
}

func (s *Subnet) CheckChanges(a, e, changes *Subnet) error {
	if a == nil {
		if e.VPC == nil {
			return fi.RequiredField("VPC")
		}

		if e.CIDR == nil {
			// TODO: Auto-assign CIDR?
			return fi.RequiredField("CIDR")
		}
	}

	if a != nil {
		if changes.VPC != nil {
			// TODO: Do we want to destroy & recreate the subnet?
			return fi.CannotChangeField("VPC")
		}
		if changes.AvailabilityZone != nil {
			// TODO: Do we want to destroy & recreate the subnet?
			return fi.CannotChangeField("AvailabilityZone")
		}
		if changes.CIDR != nil {
			// TODO: Do we want to destroy & recreate the subnet?
			return fi.CannotChangeField("CIDR")
		}
	}
	return nil
}

func (_ *Subnet) RenderAWS(t *awsup.AWSAPITarget, a, e, changes *Subnet) error {
	shared := fi.BoolValue(e.Shared)
	if shared {
		// Verify the subnet was found
		if a == nil {
			return fmt.Errorf("Subnet with id %q not found", fi.StringValue(e.ID))
		}

		return nil
	}

	if a == nil {
		glog.V(2).Infof("Creating Subnet with CIDR: %q", *e.CIDR)

		request := &ec2.CreateSubnetInput{
			CidrBlock:        e.CIDR,
			AvailabilityZone: e.AvailabilityZone,
			VpcId:            e.VPC.ID,
		}

		response, err := t.Cloud.EC2().CreateSubnet(request)
		if err != nil {
			return fmt.Errorf("error creating subnet: %v", err)
		}

		e.ID = response.Subnet.SubnetId
	}

	return t.AddAWSTags(*e.ID, t.Cloud.BuildTags(e.Name))
}

func subnetSlicesEqualIgnoreOrder(l, r []*Subnet) bool {
	var lIDs []string
	for _, s := range l {
		lIDs = append(lIDs, *s.ID)
	}
	var rIDs []string
	for _, s := range r {
		if s.ID == nil {
			glog.V(4).Infof("Subnet ID not set; returning not-equal: %v", s)
			return false
		}
		rIDs = append(rIDs, *s.ID)
	}
	return utils.StringSlicesEqualIgnoreOrder(lIDs, rIDs)
}

type terraformSubnet struct {
	VPCID            *terraform.Literal `json:"vpc_id"`
	CIDR             *string            `json:"cidr_block"`
	AvailabilityZone *string            `json:"availability_zone"`
	Tags             map[string]string  `json:"tags,omitempty"`
}

func (_ *Subnet) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *Subnet) error {
	cloud := t.Cloud.(awsup.AWSCloud)

	shared := fi.BoolValue(e.Shared)
	if shared {
		// Not terraform owned / managed
		return nil
	}

	tf := &terraformSubnet{
		VPCID:            e.VPC.TerraformLink(),
		CIDR:             e.CIDR,
		AvailabilityZone: e.AvailabilityZone,
		Tags:             cloud.BuildTags(e.Name),
	}

	return t.RenderResource("aws_subnet", *e.Name, tf)
}

func (e *Subnet) TerraformLink() *terraform.Literal {
	shared := fi.BoolValue(e.Shared)
	if shared {
		if e.ID == nil {
			glog.Fatalf("ID must be set, if subnet is shared: %s", e)
		}

		glog.V(4).Infof("reusing existing subnet with id %q", *e.ID)
		return terraform.LiteralFromStringValue(*e.ID)
	}

	return terraform.LiteralProperty("aws_subnet", *e.Name, "id")
}


text:
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { MsalService } from './msal.service';
import { Injectable, Inject } from '@angular/core';
import { Location } from "@angular/common";
import { AuthenticationResult, InteractionType} from "@azure/msal-browser";
import { MsalGuardConfiguration } from './msal.guard.config';
import { MSAL_GUARD_CONFIG } from './constants';
import { concatMap, catchError, map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';

@Injectable()
export class MsalGuard implements CanActivate {
    constructor(
        @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration,
        private authService: MsalService,
        private location: Location,
    ) {}

    /**
     * Builds the absolute url for the destination page
     * @param path Relative path of requested page
     * @returns Full destination url
     */
    getDestinationUrl(path: string): string {
        // Absolute base url for the application (default to origin if base element not present)
        const baseElements = document.getElementsByTagName("base");
        const baseUrl = this.location.normalize(baseElements.length ? baseElements[0].href : window.location.origin);

        // Path of page (including hash, if using hash routing)
        const pathUrl = this.location.prepareExternalUrl(path);

        // Hash location strategy
        if (pathUrl.startsWith("#")) {
            return `${baseUrl}/${pathUrl}`;
        }

        // If using path location strategy, pathUrl will include the relative portion of the base path (e.g. /base/page).
        // Since baseUrl also includes /base, can just concatentate baseUrl + path
        return `${baseUrl}${path}`;
    }

    private loginInteractively(url: string): Observable<boolean> {
        if (this.msalGuardConfig.interactionType === InteractionType.Popup) {
            return this.authService.loginPopup({...this.msalGuardConfig.authRequest})
                .pipe(
                    map((response: AuthenticationResult) => {
                        this.authService.instance.setActiveAccount(response.account);
                        return true;
                    }),
                    catchError(() => of(false))
                );
        }

        const redirectStartPage = this.getDestinationUrl(url);
        this.authService.loginRedirect({
            redirectStartPage,
            scopes: [],
            ...this.msalGuardConfig.authRequest,
        });
        return of(false);
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
        return this.authService.handleRedirectObservable()
            .pipe(
                concatMap(() => {
                    if (!this.authService.instance.getAllAccounts().length) {
                        return this.loginInteractively(state.url);
                    }
                    return of(true);
                }),
                catchError(() => console.log)
            );
    }

}


text:
import pathlib
import tempfile

import anyconfig.api._dump as TT

from anyconfig.api import (
    UnknownProcessorTypeError, UnknownFileTypeError
)

from . import common

class TestCase(common.BaseTestCase):

    def test_dump(self):
        with tempfile.TemporaryDirectory() as tdir:
            for data in self.each_data():
                out = pathlib.Path(tdir) / 'out.json'
                TT.dump(data.inp, out, **data.opts)
                self.assertEqual(
                    out.read_text().strip(),
                    data.exp.strip(),
                    f'{data.datadir!s}, {data.inp_path!s}'
                )

    def test_dump_intentional_failures(self):
        with tempfile.TemporaryDirectory() as tdir:
            for data in self.each_data():
                out = pathlib.Path(tdir) / 'out.json'
                TT.dump(data.inp, out, **data.opts)
                with self.assertRaises(AssertionError):
                    self.assertEqual(out.read_text().strip(), '')

    def test_dump_failure_ac_parser_was_not_given(self):
        for data in self.each_data():
            with self.assertRaises(UnknownFileTypeError):
                TT.dump(data.inp, 'dummy.txt')

    def test_dump_failure_invalid_ac_parser_was_given(self):
        for data in self.each_data():
            with self.assertRaises(UnknownProcessorTypeError):
                TT.dump(data.inp, 'dummy.json', ac_parser='invalid_id')

# vim:sw=4:ts=4:et:


text:
#pragma once
#ifndef OGLPLUS_ERROR_CODE_1405082311_HPP
#define OGLPLUS_ERROR_CODE_1405082311_HPP

#include <oglplus/enumerations.hpp>

namespace oglplus {

/// Error code enumeration
/**
 *  @ingroup enumerations
 *
 *  @glsymbols
 *  @glfunref{GetError}
 */
OGLPLUS_ENUM_CLASS_BEGIN(ErrorCode, GLenum)
#include <oglplus/enums/error_code.ipp>
OGLPLUS_ENUM_CLASS_END(ErrorCode)

#if !OGLPLUS_NO_ENUM_VALUE_NAMES
#include <oglplus/enums/error_code_names.ipp>
#endif

#if !OGLPLUS_ENUM_VALUE_RANGES
#include <oglplus/enums/error_code_range.ipp>
#endif

} // namespace oglplus

#endif // include guard


text:
from cli_app import log

log.Logger()


text:
'use strict';
angular
  .module('com.module.discover')
  .service('CountryData', function() {

  });


text:
require 'warden'
require 'sinatra_warden'

Warden::Manager.serialize_into_session{|user| user.id }
Warden::Manager.serialize_from_session do |id|
  auth_class = defined?(User) ? User : Sinatra::Rider::User
  auth_class.find(id)
end

Warden::Strategies.add(:password) do
  def valid?
    params["username"] || params["password"]
  end

  def authenticate!
    auth_class = defined?(User) ? User : Sinatra::Rider::User
    auth = auth_class.authenticate(params["username"], params["password"])
    auth.nil? ? fail!("Could not log in") : success!(auth)
  end
end

module Sinatra
  module Rider
    module AuthHelpers
      def signed_in?
        !current_user.nil?
      end
    end

    module Authentication
      def self.registered(app)
        app.register Sinatra::Warden
        app.helpers Sinatra::Rider::AuthHelpers
        app.use Rack::Session::Cookie, secret: ENV['SESSION_SECRET'] || "I'm not a businessman. I'm a business, man."
        app.use ::Warden::Manager do |manager|
          manager.default_strategies :password
          manager.failure_app = app
        end

        app.set :auth_template_renderer, :erb
        app.set :auth_success_path, '/'
        app.set :auth_failure_path, '/login'

        app.get '/signup' do
          erb :signup
        end

        app.post '/signup' do
          auth_class = defined?(User) ? User : Sinatra::Rider::User
          auth_class.signup(params)

          env['warden'].authenticate!
          redirect '/'
        end

        app.get '/login' do
          erb :login
        end

        app.post '/login' do
          env['warden'].authenticate!
        end

        app.get '/logout' do
          env['warden'].logout
        end
      end
    end
  end
end


text:
int getUmbrella() {
  return umbrella + umbrella_sub;
}

@__experimental_modules_import Umbrella2;

#include "a1.h"
#include "b1.h"
#include "nested/nested2.h"

int test() {
  return a1 + b1 + nested2;
}

@__experimental_modules_import nested_umbrella.a;

int testNestedUmbrellaA() {
  return nested_umbrella_a;
}

int testNestedUmbrellaBFail() {
  return nested_umbrella_b; // expected-error{{use of undeclared identifier 'nested_umbrella_b'; did you mean 'nested_umbrella_a'?}}
}

@__experimental_modules_import nested_umbrella.b;

int testNestedUmbrellaB() {
  return nested_umbrella_b;
}


text:
redmine_sencha_app
==================

Redmine mobile application using sencha touch


text:
package db_test

import (
	"database/sql"
	"errors"
	"strings"
	"time"

	"github.com/concourse/atc/db"
	"github.com/concourse/atc/db/fakes"
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/pivotal-golang/lager/lagertest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/onsi/gomega/gbytes"
)

var _ = Describe("Explain", func() {
	var (
		logger         *lagertest.TestLogger
		fakeClock      *fakeclock.FakeClock
		underlyingConn *fakes.FakeConn
		explainConn    db.Conn
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("explain")
		fakeClock = fakeclock.NewFakeClock(time.Now())
		underlyingConn = new(fakes.FakeConn)
		explainConn = db.Explain(logger, underlyingConn, fakeClock, 100*time.Millisecond)
	})

	AfterEach(func() {
		err := explainConn.Close()
		Expect(err).NotTo(HaveOccurred())
	})

	It("passes through calls to the underlying connection", func() {
		explainConn.Ping()

		Expect(underlyingConn.PingCallCount()).To(Equal(1))
	})

	It("returns the return values from the underlying connection", func() {
		underlyingConn.PingReturns(errors.New("disaster"))

		err := explainConn.Ping()
		Expect(err).To(MatchError("disaster"))
	})

	Context("when the query takes less time than the timeout", func() {
		var realConn *sql.DB

		BeforeEach(func() {
			postgresRunner.Truncate()

			realConn = postgresRunner.Open()
			realConn.SetMaxOpenConns(2) // +1 for concurrent EXPLAIN
			underlyingConn.QueryStub = func(query string, args ...interface{}) (*sql.Rows, error) {
				return realConn.Query(query, args...)
			}
		})

		AfterEach(func() {
			err := realConn.Close()
			Expect(err).NotTo(HaveOccurred())
		})

		It("does not EXPLAIN the query", func() {
			rows, err := explainConn.Query("SELECT $1::int", 1)
			Expect(err).NotTo(HaveOccurred())

			err = rows.Close()
			Expect(err).NotTo(HaveOccurred())

			Expect(underlyingConn.QueryCallCount()).To(Equal(1))

			query, args := underlyingConn.QueryArgsForCall(0)
			Expect(query).To(Equal("SELECT $1::int"))
			Expect(args).To(Equal(varargs(1)))
		})
	})

	Context("when the query takes more time than the timeout", func() {
		var realConn *sql.DB

		BeforeEach(func() {
			postgresRunner.Truncate()

			realConn = postgresRunner.Open()
			realConn.SetMaxOpenConns(2) // +1 for concurrent EXPLAIN
			underlyingConn.QueryStub = func(query string, args ...interface{}) (*sql.Rows, error) {
				if !strings.HasPrefix(query, "EXPLAIN") {
					fakeClock.Increment(120 * time.Millisecond)
				}

				return realConn.Query(query, args...)
			}

			underlyingConn.QueryRowStub = func(query string, args ...interface{}) *sql.Row {
				if !strings.HasPrefix(query, "EXPLAIN") {
					fakeClock.Increment(120 * time.Millisecond)
				}

				return realConn.QueryRow(query, args...)
			}

			underlyingConn.ExecStub = func(query string, args ...interface{}) (sql.Result, error) {
				if !strings.HasPrefix(query, "EXPLAIN") {
					fakeClock.Increment(120 * time.Millisecond)
				}

				return realConn.Exec(query, args...)
			}
		})

		AfterEach(func() {
			err := realConn.Close()
			Expect(err).NotTo(HaveOccurred())
		})

		Context("when the explain fails", func() {
			BeforeEach(func() {
				underlyingConn.QueryStub = func(query string, args ...interface{}) (*sql.Rows, error) {
					if strings.HasPrefix(query, "EXPLAIN") {
						return nil, errors.New("disaster!")
					} else {
						fakeClock.Increment(120 * time.Millisecond)
						return realConn.Query(query, args...)
					}
				}
			})

			It("logs an error but does not affect the outcome of the original query", func() {
				rows, err := explainConn.Query("SELECT $1::int", 1)
				Expect(err).NotTo(HaveOccurred())

				err = rows.Close()
				Expect(err).NotTo(HaveOccurred())

				Expect(logger).To(gbytes.Say("disaster!"))
			})
		})

		Describe("Query()", func() {
			It("EXPLAINs the query", func() {
				rows, err := explainConn.Query("SELECT $1::int", 1)
				Expect(err).NotTo(HaveOccurred())

				err = rows.Close()
				Expect(err).NotTo(HaveOccurred())

				Expect(underlyingConn.QueryCallCount()).To(Equal(2))

				query, args := underlyingConn.QueryArgsForCall(0)
				Expect(query).To(Equal("SELECT $1::int"))
				Expect(args).To(Equal(varargs(1)))

				query, args = underlyingConn.QueryArgsForCall(1)
				Expect(query).To(Equal("EXPLAIN SELECT $1::int"))
				Expect(args).To(Equal(varargs(1)))
			})

			It("logs the output of the explain", func() {
				rows, err := explainConn.Query("SELECT $1::int", 1)
				Expect(err).NotTo(HaveOccurred())

				err = rows.Close()
				Expect(err).NotTo(HaveOccurred())

				Expect(logger).To(gbytes.Say("Result"))
				Expect(logger).To(gbytes.Say("cost="))
				Expect(logger).To(gbytes.Say("SELECT"))
			})
		})

		Describe("QueryRow()", func() {
			It("EXPLAINs the query", func() {
				var i int
				err := explainConn.QueryRow("SELECT $1::int", 1).Scan(&i)
				Expect(err).NotTo(HaveOccurred())

				Expect(underlyingConn.QueryRowCallCount()).To(Equal(1))
				Expect(underlyingConn.QueryCallCount()).To(Equal(1))

				query, args := underlyingConn.QueryRowArgsForCall(0)
				Expect(query).To(Equal("SELECT $1::int"))
				Expect(args).To(Equal(varargs(1)))

				query, args = underlyingConn.QueryArgsForCall(0)
				Expect(query).To(Equal("EXPLAIN SELECT $1::int"))
				Expect(args).To(Equal(varargs(1)))
			})

			It("logs the output of the explain", func() {
				var i int
				err := explainConn.QueryRow("SELECT $1::int", 1).Scan(&i)
				Expect(err).NotTo(HaveOccurred())

				Expect(logger).To(gbytes.Say("Result"))
				Expect(logger).To(gbytes.Say("cost="))
				Expect(logger).To(gbytes.Say("SELECT"))
			})
		})

		Describe("Exec()", func() {
			It("EXPLAINs the query", func() {
				_, err := explainConn.Exec("SELECT $1::int", 1)
				Expect(err).NotTo(HaveOccurred())

				Expect(underlyingConn.ExecCallCount()).To(Equal(1))
				Expect(underlyingConn.QueryCallCount()).To(Equal(1))

				query, args := underlyingConn.ExecArgsForCall(0)
				Expect(query).To(Equal("SELECT $1::int"))
				Expect(args).To(Equal(varargs(1)))

				query, args = underlyingConn.QueryArgsForCall(0)
				Expect(query).To(Equal("EXPLAIN SELECT $1::int"))
				Expect(args).To(Equal(varargs(1)))
			})

			It("logs the output of the explain", func() {
				_, err := explainConn.Exec("SELECT $1::int", 1)
				Expect(err).NotTo(HaveOccurred())

				Expect(logger).To(gbytes.Say("Result"))
				Expect(logger).To(gbytes.Say("cost="))
				Expect(logger).To(gbytes.Say("SELECT"))
			})
		})
	})
})

func varargs(x ...interface{}) interface{} {
	return x
}


text:
#include "LDAPControl.h"
#include "debug.h"

using namespace std;

LDAPCtrl::LDAPCtrl(const LDAPCtrl& c){
    DEBUG(LDAP_DEBUG_CONSTRUCT,"LDAPCtrl::LDAPCtrl(&)" << endl);
    m_oid=c.m_oid;
    m_data=c.m_data;
    m_isCritical=c.m_isCritical;
}

LDAPCtrl::LDAPCtrl(const char *oid, bool critical, const char* data,
        int length){
    DEBUG(LDAP_DEBUG_CONSTRUCT,"LDAPCtrl::LDAPCtrl()" << endl);
    DEBUG(LDAP_DEBUG_CONSTRUCT | LDAP_DEBUG_PARAMETER,
            "   oid:" << oid << endl << "   critical:" << critical << endl);
    m_oid = oid;
    m_isCritical=critical;
    if (data != 0 && length !=0){
        m_data.assign(data,length);
    }else{
        m_data=string();
    }
}

LDAPCtrl::LDAPCtrl(const string& oid, bool critical, const string& data){
    DEBUG(LDAP_DEBUG_CONSTRUCT,"LDAPCtrl::LDAPCtrl()" << endl);
    DEBUG(LDAP_DEBUG_CONSTRUCT | LDAP_DEBUG_PARAMETER,
            "   oid:" << oid << endl << "   critical:" << critical << endl);
    m_oid=oid;
    m_isCritical=critical;
    m_data=data;
}

LDAPCtrl::LDAPCtrl(const LDAPControl* ctrl){
    DEBUG(LDAP_DEBUG_CONSTRUCT,"LDAPCtrl::LDAPCtrl()" << endl);
    m_oid = string(ctrl->ldctl_oid);
    m_oid = ctrl->ldctl_iscritical ? true : false;
    m_oid = string(ctrl->ldctl_value.bv_val, ctrl->ldctl_value.bv_len );
}

LDAPCtrl::~LDAPCtrl(){
    DEBUG(LDAP_DEBUG_DESTROY,"LDAPCtrl::~LDAPCtrl" << endl);
}

string LDAPCtrl::getOID() const{
    DEBUG(LDAP_DEBUG_TRACE,"LDAPCtrl::getOID()" << endl);
    return m_oid;
}

bool LDAPCtrl::isCritical()const {
    DEBUG(LDAP_DEBUG_TRACE,"LDAPCtrl::isCritical()" << endl);
    return m_isCritical;
}

string LDAPCtrl::getData() const {
    DEBUG(LDAP_DEBUG_TRACE,"LDAPCtrl::getData()" << endl);
    return m_data;
}

LDAPControl* LDAPCtrl::getControlStruct() const {
    DEBUG(LDAP_DEBUG_TRACE,"LDAPCtrl::getControlStruct()" << endl);
    LDAPControl* ret = new LDAPControl;
    ret->ldctl_oid= new char[m_oid.size() + 1];
    m_oid.copy(ret->ldctl_oid,string::npos);
    ret->ldctl_oid[m_oid.size()]=0;
    ret->ldctl_value.bv_len=m_data.size();
    ret->ldctl_value.bv_val= new char[m_data.size()];
    m_data.copy(ret->ldctl_value.bv_val,string::npos);
    ret->ldctl_iscritical = ( m_isCritical ? 1:0);
    return ret;
}

void LDAPCtrl::freeLDAPControlStruct(LDAPControl *ctrl){
    DEBUG(LDAP_DEBUG_TRACE,"LDAPCtrl::freeControlStruct()" << endl);
    delete[] ctrl->ldctl_oid;
    delete[] ctrl->ldctl_value.bv_val;
    delete ctrl;
}


text:
MODULO DE PACIENTES INTERNOS

Inicio

                                <button  class="fluent-button"> Consulta externa</button>
                                <button  class="fluent-button"> Luz y Vida</button>

Operaciones

                                <button  class="fluent-button"> Diagnóstico</button>
                                <button  class="fluent-button"> Farmacia</button>

Operaciones


text:
from __future__ import absolute_import

import sys

from celery.concurrency.base import BasePool
from celery.five import monotonic
from celery.worker import state
from celery.worker import autoscale
from celery.tests.case import AppCase, Mock, patch, sleepdeprived

class Object(object):
    pass

class MockPool(BasePool):
    shrink_raises_exception = False
    shrink_raises_ValueError = False

    def __init__(self, *args, **kwargs):
        super(MockPool, self).__init__(*args, **kwargs)
        self._pool = Object()
        self._pool._processes = self.limit

    def grow(self, n=1):
        self._pool._processes += n

    def shrink(self, n=1):
        if self.shrink_raises_exception:
            raise KeyError('foo')
        if self.shrink_raises_ValueError:
            raise ValueError('foo')
        self._pool._processes -= n

    @property
    def num_processes(self):
        return self._pool._processes

class test_WorkerComponent(AppCase):

    def test_register_with_event_loop(self):
        parent = Mock(name='parent')
        parent.autoscale = True
        parent.consumer.on_task_message = set()
        w = autoscale.WorkerComponent(parent)
        self.assertIsNone(parent.autoscaler)
        self.assertTrue(w.enabled)

        hub = Mock(name='hub')
        w.create(parent)
        w.register_with_event_loop(parent, hub)
        self.assertIn(
            parent.autoscaler.maybe_scale,
            parent.consumer.on_task_message,
        )
        hub.call_repeatedly.assert_called_with(
            parent.autoscaler.keepalive, parent.autoscaler.maybe_scale,
        )

        parent.hub = hub
        hub.on_init = []
        w.instantiate = Mock()
        w.register_with_event_loop(parent, Mock(name='loop'))
        self.assertTrue(parent.consumer.on_task_message)

class test_Autoscaler(AppCase):

    def setup(self):
        self.pool = MockPool(3)

    def test_stop(self):

        class Scaler(autoscale.Autoscaler):
            alive = True
            joined = False

            def is_alive(self):
                return self.alive

            def join(self, timeout=None):
                self.joined = True

        worker = Mock(name='worker')
        x = Scaler(self.pool, 10, 3, worker=worker)
        x._is_stopped.set()
        x.stop()
        self.assertTrue(x.joined)
        x.joined = False
        x.alive = False
        x.stop()
        self.assertFalse(x.joined)

    @sleepdeprived(autoscale)
    def test_body(self):
        worker = Mock(name='worker')
        x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker)
        x.body()
        self.assertEqual(x.pool.num_processes, 3)
        for i in range(20):
            state.reserved_requests.add(i)
        x.body()
        x.body()
        self.assertEqual(x.pool.num_processes, 10)
        self.assertTrue(worker.consumer._update_prefetch_count.called)
        state.reserved_requests.clear()
        x.body()
        self.assertEqual(x.pool.num_processes, 10)
        x._last_action = monotonic() - 10000
        x.body()
        self.assertEqual(x.pool.num_processes, 3)
        self.assertTrue(worker.consumer._update_prefetch_count.called)

    def test_run(self):

        class Scaler(autoscale.Autoscaler):
            scale_called = False

            def body(self):
                self.scale_called = True
                self._is_shutdown.set()

        worker = Mock(name='worker')
        x = Scaler(self.pool, 10, 3, worker=worker)
        x.run()
        self.assertTrue(x._is_shutdown.isSet())
        self.assertTrue(x._is_stopped.isSet())
        self.assertTrue(x.scale_called)

    def test_shrink_raises_exception(self):
        worker = Mock(name='worker')
        x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker)
        x.scale_up(3)
        x._last_action = monotonic() - 10000
        x.pool.shrink_raises_exception = True
        x.scale_down(1)

    @patch('celery.worker.autoscale.debug')
    def test_shrink_raises_ValueError(self, debug):
        worker = Mock(name='worker')
        x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker)
        x.scale_up(3)
        x._last_action = monotonic() - 10000
        x.pool.shrink_raises_ValueError = True
        x.scale_down(1)
        self.assertTrue(debug.call_count)

    def test_update_and_force(self):
        worker = Mock(name='worker')
        x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker)
        self.assertEqual(x.processes, 3)
        x.force_scale_up(5)
        self.assertEqual(x.processes, 8)
        x.update(5, None)
        self.assertEqual(x.processes, 5)
        x.force_scale_down(3)
        self.assertEqual(x.processes, 2)
        x.update(3, None)
        self.assertEqual(x.processes, 3)
        x.force_scale_down(1000)
        self.assertEqual(x.min_concurrency, 0)
        self.assertEqual(x.processes, 0)
        x.force_scale_up(1000)
        x.min_concurrency = 1
        x.force_scale_down(1)

        x.update(max=300, min=10)
        x.update(max=300, min=2)
        x.update(max=None, min=None)

    def test_info(self):
        worker = Mock(name='worker')
        x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker)
        info = x.info()
        self.assertEqual(info['max'], 10)
        self.assertEqual(info['min'], 3)
        self.assertEqual(info['current'], 3)

    @patch('os._exit')
    def test_thread_crash(self, _exit):

        class _Autoscaler(autoscale.Autoscaler):

            def body(self):
                self._is_shutdown.set()
                raise OSError('foo')
        worker = Mock(name='worker')
        x = _Autoscaler(self.pool, 10, 3, worker=worker)

        stderr = Mock()
        p, sys.stderr = sys.stderr, stderr
        try:
            x.run()
        finally:
            sys.stderr = p
        _exit.assert_called_with(1)
        self.assertTrue(stderr.write.call_count)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using System.IO;
using System.Collections;
using ConvertorClass.Containers;
using ConvertorClass;

//Requires NUnit 3. Recommended with NUnit3 Test Adapter.
namespace NUnitTestClass
{
    public class UnitTestClass
    {

        /// <summary>
        /// Defines a set of Tests for AWTTP.
        ///     The Stub raw text begins with data and ends with data. (No empty lines before data)
        /// </summary>

        [TestFixture(), Category("Unit"), Description("Tests AlignedWordsToTableProcessor")]
        public class AWTTPUnitTests
        {
            public static StubTableData STD = new StubTableData();
            public static AlignedWordsToTableProcessor AWTTP = new AlignedWordsToTableProcessor(true);
            public static string[] textFile = STD.rawText.Split(new Char[] { '\n' });
            private const int PRIMARYKEY = 1;
            private const int HEADERLINES = 4;
            private const int MULTILINE = 0;
            private const string DELIMITER = "  "; // *TWO* spaces.

            //[TestFixtureSetUp]
            //public void FixtureSetUp()
            //{
            //    STD = new StubTableData();
            //    AWTTP = new AlignedWordsToTableProcessor(true);
            //    textFile = STD.rawText.Split(new Char[] { '\n' });
            //}

            [Test, Category("Header"), Order(1)]
            public void ProcessHeaderLine1()
            {
                AWTTP.ProcessFirstHeaderLine(textFile[0].Split(new string[] { "  " }, StringSplitOptions.None));
                Assert.AreEqual(STD.headerLine_1, AWTTP.headerList);
                Assert.AreEqual(STD.lineCount_1, AWTTP.lineCountList);
                Assert.AreEqual(STD.greatestHeaderList_1, AWTTP.greatestHeaderWordList);
            }

            [Test, Category("Header"), Order(2)]
            public void ProcessHeaderLine2()
            {
                AWTTP.ProcessHeaderLines(textFile[1].Split(new string[] { "  " }, StringSplitOptions.None));
                Assert.AreEqual(STD.headerLine_2, AWTTP.headerList);
                //TODO: Fix feature that helps reduce alignment error.
                Assert.AreEqual(STD.lineCount_2, AWTTP.lineCountList);
                Assert.AreEqual(STD.greatestHeaderList_2, AWTTP.greatestHeaderWordList);
            }

            [Test, Category("Header"), Order(3)]
            public void ProcessHeaderLine3()
            {
                AWTTP.ProcessHeaderLines(textFile[2].Split(new string[] { "  " }, StringSplitOptions.None));
                Assert.AreEqual(STD.headerLine_3, AWTTP.headerList);
                //TODO: Fix feature that helps reduce alignment error.
                //Assert.AreEqual(STD.lineCount_3, AWTTP.lineCountList);
                //Assert.AreEqual(STD.greatestHeaderList_3, AWTTP.greatestHeaderWordList);
            }

            [Test, Category("Header"), Order(4)]
            public void ProcessHeaderLine4()
            {
                AWTTP.ProcessHeaderLines(textFile[3].Split(new string[] { "  " }, StringSplitOptions.None));
                Assert.AreEqual(STD.headerLine_4, AWTTP.headerList);
                //Assert.AreEqual(STD.lineCount_4, AWTTP.lineCountList);
                //Assert.AreEqual(STD.greatestHeaderList_4, AWTTP.greatestHeaderWordList);
            }

            [Test, Category("Data"), Order(5)]
            public void ProcessDataLine5()
            {
                AWTTP.ProcessDataLine(textFile[4].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_5, AWTTP.dataList );
            }

            [Test, Category("Data"), Order(6)]
            public void ProcessDataLine6789101112()
            {
                AWTTP.ProcessDataLine(textFile[5].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_6, AWTTP.dataList );
                AWTTP.ProcessDataLine(textFile[6].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_7, AWTTP.dataList);
                AWTTP.ProcessDataLine(textFile[7].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_8, AWTTP.dataList);
                AWTTP.ProcessDataLine(textFile[8].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_9, AWTTP.dataList);
                AWTTP.ProcessDataLine(textFile[9].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_10, AWTTP.dataList);
                AWTTP.ProcessDataLine(textFile[10].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_11, AWTTP.dataList);
                AWTTP.ProcessDataLine(textFile[11].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_12, AWTTP.dataList);
            }

            [Test, Category("Data"), Order(7)]
            public void ProcessDataLine13()
            {
                AWTTP.ProcessDataLine(textFile[12].Split(new string[] { "  " }, StringSplitOptions.None), 0, PRIMARYKEY, MULTILINE);
                Assert.AreEqual(STD.dataline_13, AWTTP.dataList );
            }

            [Test, Category("Helper")]
            public void CombineToSASHeaderLine()
            {
                Assert.True(true);
            }

            [Test, Category("Helper")]
            public void PadDataList()
            {
                Assert.True(true);
            }

            [TestFixtureTearDown]
            public void FixtureTearDown()
            {

            }
        }
    }
}