text:
#include "application.h"

#define DEBUG 0
#define PORT 48879
#define MAX_DATA_BYTES 128
#define MAX_I2C_READ_CONTINUOUS_DEVICES 8

// table of action codes
// to do: make this an enum?
#define PIN_MODE                    0x00
#define DIGITAL_WRITE               0x01
#define ANALOG_WRITE                0x02
#define DIGITAL_READ                0x03
#define ANALOG_READ                 0x04
#define REPORTING                   0x05
#define SET_SAMPLE_INTERVAL         0x06
#define INTERNAL_RGB                0x07
#define PING_READ                   0x08

/* NOTE GAP */
// #define SERIAL_BEGIN                0x10
// #define SERIAL_END                  0x11
// #define SERIAL_PEEK                 0x12
// #define SERIAL_AVAILABLE            0x13
// #define SERIAL_WRITE                0x14
// #define SERIAL_READ                 0x15
// #define SERIAL_FLUSH                0x16
/* NOTE GAP */
// #define SPI_BEGIN                   0x20
// #define SPI_END                     0x21
// #define SPI_SET_BIT_ORDER           0x22
// #define SPI_SET_CLOCK               0x23
// #define SPI_SET_DATA_MODE           0x24
// #define SPI_TRANSFER                0x25
// /* NOTE GAP */
#define I2C_CONFIG                  0x30
#define I2C_WRITE                   0x31
#define I2C_READ                    0x32
#define I2C_READ_CONTINUOUS       0x33
#define I2C_REGISTER_NOT_SPECIFIED  0xFF
/* NOTE GAP */
#define SERVO_WRITE                 0x41
#define ACTION_RANGE                0x46

uint8_t bytesToExpectByAction[] = {
  // digital/analog I/O
  2,    // PIN_MODE
  2,    // DIGITAL_WRITE
  2,    // ANALOG_WRITE
  1,    // DIGITAL_READ
  1,    // ANALOG_READ
  2,    // REPORTING
  2,    // SET_SAMPLE_INTERVAL
  3,    // INTERNAL_RGB
  1,    // PING_READ
  // gap from 0x09-0x0f
  0,    // 0x09
  0,    // 0x0a
  0,    // 0x0b
  0,    // 0x0c
  0,    // 0x0d
  0,    // 0x0e
  0,    // 0x0f
  // serial I/O
  2,    // SERIAL_BEGIN
  1,    // SERIAL_END
  1,    // SERIAL_PEEK
  1,    // SERIAL_AVAILABLE
  2,    // SERIAL_WRITE  -- variable length message!
  1,    // SERIAL_READ
  1,    // SERIAL_FLUSH
  // gap from 0x17-0x1f
  0,    // 0x17
  0,    // 0x18
  0,    // 0x19
  0,    // 0x1a
  0,    // 0x1b
  0,    // 0x1c
  0,    // 0x1d
  0,    // 0x1e
  0,    // 0x1f
  // SPI I/O
  0,    // SPI_BEGIN
  0,    // SPI_END
  1,    // SPI_SET_BIT_ORDER
  1,    // SPI_SET_CLOCK
  1,    // SPI_SET_DATA_MODE
  1,    // SPI_TRANSFER
  // gap from 0x26-0x2f
  0,    // 0x26
  0,    // 0x27
  0,    // 0x28
  0,    // 0x29
  0,    // 0x2a
  0,    // 0x2b
  0,    // 0x2c
  0,    // 0x2d
  0,    // 0x2e
  0,    // 0x2f
  // wire I/O
  2,    // I2C_CONFIG
  3,    // I2C_WRITE -- variable length message!
  5,    // I2C_READ
  5,    // I2C_READ_CONTINUOUS
  // gap from 0x34-0x3f
  0,    // 0x34
  0,    // 0x35
  0,    // 0x36
  0,    // 0x37
  0,    // 0x38
  0,    // 0x39
  0,    // 0x3a
  0,    // 0x3b
  0,    // 0x3c
  0,    // 0x3d
  0,    // 0x3e
  0,    // 0x3f
  0,    // 0x40
  // servo
  2,    // SERVO_WRITE
  1,    // SERVO_DETACH
};

TCPServer server = TCPServer(PORT);
TCPClient client;

bool hasAction = false;
bool isConnected = false;

byte analogReporting[20];
byte buffer[MAX_DATA_BYTES];
byte cached[64];
byte i2cRxData[64];
byte pinModeFor[20];
byte portValues[2];
byte reporting[20];

int action, available;
int bytesRead = 0;
int bytesExpecting = 0;
int reporters = 0;

signed int i2cIndex = -1;

// Default delay time between i2c read request and Wire.requestFrom()
unsigned int i2cReadDelayTime = 0;

unsigned long lastms;
unsigned long nowms;
unsigned long sampleInterval = 100;
unsigned long SerialSpeed[] = {
  600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200
};

/* i2c data */
struct I2CDevice {
  byte address;
  int reg;
  byte bytes;
};

/* Track I2C continuous read devices */
I2CDevice i2cDevices[MAX_I2C_READ_CONTINUOUS_DEVICES];

/*
  PWM/Servo support is CONFIRMED available on:

  D0, D1, A0, A1, A4, A5, A6, A7

  Allocate 8 servo objects:
 */
Servo servos[8];
/*
  The Particle devices can only support PWM/Servo on specific pins, so
  based on the pin number, determine the servo index for the allocated
  servo object.
 */
int ToServoIndex(int pin) {
  // D0, D1
  if (pin == 0 || pin == 1) return pin;
  // A0, A1
  if (pin == 10 || pin == 11) return pin - 8;
  // A4, A5, A6, A7
  if (pin >= 14) return pin - 10;
}

void send(int action, int pinOrPort, int pinOrPortValue) {
  uint8_t buf[4];

  // See https://github.com/voodootikigod/voodoospark/issues/20
  // to understand why the send function splits values
  // into two 7-bit bytes before sending.

  buf[0] = action;
  buf[1] = pinOrPort;
  // LSB
  buf[2] = pinOrPortValue & 0x7F;
  // MSB
  buf[3] = pinOrPortValue >> 0x07 & 0x7F;

  server.write(buf, 4);
}

void setup() {

  server.begin();

  #if DEBUG
  Serial.begin(115200);
  #endif

  IPAddress ip = WiFi.localIP();
  static char ipAddress[24] = "";

  // https://community.particle.io/t/network-localip-to-string-to-get-it-via-spark-variable/2581/5
  sprintf(ipAddress, "%d.%d.%d.%d:%d", ip[0], ip[1], ip[2], ip[3], PORT);

  Spark.variable("endpoint", ipAddress, STRING);
}

void readAndReportI2cData(byte address, int theRegister, byte numBytes) {
  byte data;

  #if DEBUG
  Serial.println("-------------- I2C Read and Report Data");
  Serial.print("address: 0x");
  Serial.println(address, HEX);
  Serial.print("register: 0x");
  Serial.println(theRegister, HEX);
  Serial.print("numBytes: ");
  Serial.println(numBytes, DEC);
  #endif

  // allow I2C requests that don't require a register read
  // for example, some devices using an interrupt pin to signify new data available
  // do not always require the register read so upon interrupt you call Wire.requestFrom()
  if (theRegister != I2C_REGISTER_NOT_SPECIFIED) {
    Wire.beginTransmission(address);
    Wire.write((byte)theRegister);
    Wire.endTransmission();
    // do not set a value of 0
    if (i2cReadDelayTime > 0) {
      // delay is necessary for some devices such as WiiNunchuck
      delayMicroseconds(i2cReadDelayTime);
    }
  } else {
    theRegister = 0xFF;  // fill the register with an impossible value
  }

  Wire.requestFrom(address, numBytes);  // all bytes are returned in requestFrom

  #if DEBUG
  // check to be sure correct number of bytes were returned by device
  if (numBytes < Wire.available()) {
    Serial.println("I2C: Too many bytes received");
  } else if (numBytes > Wire.available()) {
    Serial.println("I2C: Too few bytes received");
  }
  #endif

  i2cRxData[0] = 0x77;
  i2cRxData[1] = numBytes;
  i2cRxData[2] = address;
  i2cRxData[3] = theRegister & 0x7F;
  i2cRxData[4] = theRegister >> 0x07 & 0x7F;

  #if DEBUG
  Serial.print("Number of Bytes: ");
  Serial.println(numBytes, DEC);
  Serial.print("Address: ");
  Serial.println(address, HEX);
  Serial.print("Register: ");
  Serial.println(theRegister, HEX);
  #endif

  for (int i = 0; i < numBytes && Wire.available(); i++) {
    data = Wire.read();

    #if DEBUG
    Serial.print("Data[");
    Serial.print(i, DEC);
    Serial.print("]: 0x");
    Serial.println(data, HEX);
    #endif

    i2cRxData[5 + i] = data;
  }

  // send address, register and received bytes
  server.write(i2cRxData, numBytes + 5);
}

/*
 * Original pulseIn Function for the Spark Core - Version 0.1.1 (Beta)
 * Copyright (2014) Timothy Brown - See: pulsein.license
 *
 * Due to the current timeout issues with Spark Cloud
 * this will return after 10 seconds, even if the
 * input pulse hasn't finished.
 *
 * Input: Trigger Pin, Trigger State
 * Output: Pulse Length in Microseconds (10uS to 10S)
 *
 * Copyright (2015) Rick Waldron (Modifications for improved accuracy on with a Photon)
 * See LICENSE-MIT
 *
 */

unsigned long pulseIn(uint16_t pin, uint8_t state) {
  #if (PLATFORM_ID == 0)  // Core
    STM32_Pin_Info* PIN_MAP = HAL_Pin_Map(); // Pointer required for highest access speed
  #endif

  // Cache the target's peripheral mask to speed up the loops.
  GPIO_TypeDef* portMask = (PIN_MAP[pin].gpio_peripheral);
  // Cache the target's GPIO pin mask to speed up the loops.
  uint16_t pinMask = (PIN_MAP[pin].gpio_pin);
  unsigned long numloops = 0;
  // This has to be extremely short, because we dont want to block the process
  // for longer than is really appropriate
  unsigned long maxloops = 500000;

  // Wait for the pin to enter target state while keeping track of the timeout.
  while (GPIO_ReadInputDataBit(portMask, pinMask) != state) {
    if (numloops++ == maxloops) {
      Serial.println("Timed out, never equaled state");
      return 0;
    }
  }

  unsigned long us = micros();
  unsigned long width;

  while (GPIO_ReadInputDataBit(portMask, pinMask) == state) {
    if (numloops++ == maxloops) {
      return 0;
    }

    width = micros() - us;
  }

  return width;
}

unsigned long pingRead(int pin) {
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
  delayMicroseconds(2);
  digitalWrite(pin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pin, LOW);

  pinMode(pin, INPUT);

  unsigned long duration = pulseIn(pin, HIGH);

  return duration;
}

void cacheBuffer(int byteCount, int cacheLength) {
  // Copy the expected bytes into the cache and shift
  // the unused bytes to the beginning of the buffer
  #if DEBUG
  Serial.print("Cached: ");
  #endif

  for (int k = 0; k < byteCount; k++) {
    // Cache the bytes that we're expecting for
    // this action.
    if (k < cacheLength) {
      cached[k] = buffer[k];

      #if DEBUG
      Serial.print("0x");
      Serial.print(cached[k], HEX);
      Serial.print(", ");
      #endif
    }

    // Shift the unused buffer to the front
    buffer[k] = buffer[k + cacheLength];
  }

  #if DEBUG
  Serial.println("");
  #endif
}

void report() {
  if (isConnected) {

    #if DEBUG
    Serial.println("--------------REPORTING");
    #endif

    int pin;
    int pinValue;
    int i;

    for (int k = 0; k < 2; k++) {
      bool shouldSend = false;
      // D0-D7
      // portValues[0] = 0;
      // A0-A7
      // portValues[1] = 0;
      portValues[k] = 0;

      for (i = 0; i < 8; i++) {
        pin = (k * 10) + i;

        if (reporting[pin] == 1) {
          shouldSend = true;
          pinValue = digitalRead(pin);

          if (pinValue) {
            portValues[k] = (portValues[k] | pinValue) << i;
          }
        }
      }

      if (shouldSend) {
        #if DEBUG
        Serial.print("Reporting: ");
        Serial.print(k, DEC);
        Serial.println(portValues[k], DEC);
        #endif

        send(REPORTING, k, portValues[k]);
      }
    }

    for (i = 10; i < 18; i++) {
      if (analogReporting[i] == 1) {
        int adc = analogRead(i);

        #if DEBUG
        Serial.print("Analog Reporting: ");
        Serial.print(i, DEC);
        Serial.print(": ");
        Serial.println(adc, DEC);
        #endif

        send(ANALOG_READ, i, adc);
        delay(1);
      }
    }

    // Report I2C_READ_CONTINUOUS devices
    if (i2cIndex != -1) {
      for (i = 0; i <= i2cIndex; i++) {
        readAndReportI2cData(i2cDevices[i].address, i2cDevices[i].reg, i2cDevices[i].bytes);
      }
    }
  }
}

void restore() {
  #if DEBUG
  Serial.println("--------------RESTORING");
  #endif

  hasAction = false;
  isConnected = false;

  reporters = 0;
  bytesRead = 0;
  bytesExpecting = 0;

  i2cIndex = -1;
  lastms = 0;
  nowms = 0;
  sampleInterval = 100;

  memset(&analogReporting[0], 0, 20);
  memset(&buffer[0], 0, MAX_DATA_BYTES);
  memset(&cached[0], 0, 64);
  memset(&i2cRxData[0], 0, 64);
  memset(&pinModeFor[0], 0, 20);
  memset(&portValues[0], 0, 2);
  memset(&reporting[0], 0, 20);

  for (int i = 0; i < 8; i++) {
    if (servos[i].attached()) {
      servos[i].detach();
    }
  }

  // Restore defaults.
  for (int i = 0; i < 8; i++) {
    pinMode(i, OUTPUT);
    pinMode(i + 10, INPUT);

    pinModeFor[i] = 1;
    pinModeFor[i + 10] = 0;
  }
}

void processInput() {
  int pin, mode, val, type, speed, address, reg, stop, len, k, i, delayTime, dataLength;
  int byteCount = bytesRead;

  unsigned long us;

  #if DEBUG
  Serial.println("--------------PROCESSING");
  #endif

  // Only check if buffer[0] is possibly an action
  // when there is no action in progress.
  if (hasAction == false) {
    if (buffer[0] < ACTION_RANGE) {
      action = buffer[0];
      bytesExpecting = bytesToExpectByAction[action] + 1;
      hasAction = true;

      #if DEBUG
      Serial.print("Bytes Read: ");
      Serial.println(bytesRead, DEC);
      Serial.print("Bytes Required: ");
      Serial.println(bytesExpecting, DEC);
      Serial.print("Bytes Remaining: ");
      Serial.println(bytesRead - bytesExpecting, DEC);
      #endif
    }
  }

  if ((bytesRead - bytesExpecting) < 0) {
    hasAction = false;
    bytesExpecting = 0;

    #if DEBUG
    Serial.println("Not Enough Bytes.");
    #endif
    return;
  }

  // When the first byte of buffer is an action and
  // enough bytes are read, begin processing the action.
  if (hasAction && bytesRead >= bytesExpecting) {

    cacheBuffer(byteCount, bytesExpecting);
    byteCount -= bytesExpecting;

    #if DEBUG
    Serial.print("ACTION: 0x");
    Serial.println(action, HEX);
    #endif

    // Proceed with action processing
    switch (action) {
      case PIN_MODE:  // pinMode
        pin = cached[1];
        mode = cached[2];
        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin);
        Serial.print("MODE: ");
        Serial.println(mode, HEX);
        #endif

        if (pinModeFor[pin] != mode) {

          if (pinModeFor[pin] == 0x04) {
            servos[ToServoIndex(pin)].detach();
          }

          pinModeFor[pin] = mode;

          // The following modes were derived
          // from uses in core-firmware.
          if (mode == 0x00) {
            // INPUT
            pinMode(pin, INPUT_PULLDOWN);
          }
          if (mode == 0x01) {
            // OUTPUT
            pinMode(pin, OUTPUT);
          }
          if (mode == 0x02) {
            // ANALOG INPUT
            pinMode(pin, INPUT);
          }
          if (mode == 0x03) {
            // ANALOG (PWM) OUTPUT
            pinMode(pin, OUTPUT);
          }
          if (mode == 0x04) {
            // SERVO
            pinMode(pin, OUTPUT);
            servos[ToServoIndex(pin)].attach(pin);
          }
        }
        break;

      case DIGITAL_WRITE:  // digitalWrite
        pin = cached[1];
        val = cached[2];
        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin, DEC);
        Serial.print("VALUE: ");
        Serial.println(val, HEX);
        #endif
        digitalWrite(pin, val);
        break;

      case ANALOG_WRITE:  // analogWrite
        pin = cached[1];
        val = cached[2];
        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin, DEC);
        Serial.print("VALUE: ");
        Serial.println(val, HEX);
        #endif
        analogWrite(pin, val);
        break;

      case DIGITAL_READ:  // digitalRead
        pin = cached[1];
        val = digitalRead(pin);
        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin, DEC);
        Serial.print("VALUE: ");
        Serial.println(val, HEX);
        #endif
        send(0x03, pin, val);
        break;

      case ANALOG_READ:  // analogRead
        pin = cached[1];
        val = analogRead(pin);
        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin, DEC);
        Serial.print("VALUE: ");
        Serial.println(val, HEX);
        #endif
        send(0x04, pin, val);
        break;

      case PING_READ:
        pin = cached[1];
        us = pingRead(pin);

        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin, DEC);
        Serial.print("VALUE: ");
        Serial.println(us, DEC);
        #endif

        byte duration[6];

        duration[0] = PING_READ;
        duration[1] = pin;
        duration[2] = (us >> 24) & 0xFF;
        duration[3] = (us >> 16) & 0xFF;
        duration[4] = (us >> 8) & 0xFF;
        duration[5] = us & 0xFF;

        #if DEBUG
        for (int di = 0; di < 6; di++) {
          Serial.print(duration[di]);Serial.print(" ");
        }
        #endif

        server.write(duration, 6);
        break;

      case REPORTING: // Add pin to
        pin = cached[1];
        val = cached[2];

        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin, DEC);
        Serial.print("TYPE: ");
        Serial.println(val, DEC);
        #endif

        if (analogReporting[pin] == 0 || reporting[pin] == 0) {
          reporters++;
        }

        if (val == 2) {
          analogReporting[pin] = 1;
        } else {
          reporting[pin] = 1;
        }
        break;

      case SET_SAMPLE_INTERVAL: // set the sampling interval in ms
        sampleInterval = cached[1] + (cached[2] << 7);

        #if DEBUG
        Serial.print("SET_SAMPLE_INTERVAL (2 bytes): ");
        Serial.println(sampleInterval, DEC);
        #endif

        // Lower than ~100ms will likely crash the device,
        // but
        if (sampleInterval < 20) {
          sampleInterval = 20;
        }
        break;

      // // Serial API
      // case SERIAL_BEGIN:  // serial.begin
      //   type = cached[1];
      //   speed = cached[2];
      //   if (type == 0) {
      //     Serial.begin(SerialSpeed[speed]);
      //   } else {
      //     Serial1.begin(SerialSpeed[speed]);
      //   }
      //   break;

      // case SERIAL_END:  // serial.end
      //   type = cached[1];
      //   if (type == 0) {
      //     Serial.end();
      //   } else {
      //     Serial1.end();
      //   }
      //   break;

      // case SERIAL_PEEK:  // serial.peek
      //   type = cached[1];
      //   if (type == 0) {
      //     val = Serial.peek();
      //   } else {
      //     val = Serial1.peek();
      //   }
      //   send(0x07, type, val);
      //   break;

      // case SERIAL_AVAILABLE:  // serial.available()
      //   type = cached[1];
      //   if (type == 0) {
      //     val = Serial.available();
      //   } else {
      //     val = Serial1.available();
      //   }
      //   send(0x07, type, val);
      //   break;

      // case SERIAL_WRITE:  // serial.write
      //   type = cached[1];
      //   len = cached[2];

      //   for (i = 0; i < len; i++) {
      //     if (type == 0) {
      //       Serial.write(client.read());
      //     } else {
      //       Serial1.write(client.read());
      //     }
      //   }
      //   break;

      // case SERIAL_READ: // serial.read
      //   type = cached[1];
      //   if (type == 0) {
      //     val = Serial.read();
      //   } else {
      //     val = Serial1.read();
      //   }
      //   send(0x16, type, val);
      //   break;

      // case SERIAL_FLUSH: // serial.flush
      //   type = cached[1];
      //   if (type == 0) {
      //     Serial.flush();
      //   } else {
      //     Serial1.flush();
      //   }
      //   break;

      // SPI API
      // case SPI_BEGIN:  // SPI.begin
      //   SPI.begin();
      //   break;

      // case SPI_END:  // SPI.end
      //   SPI.end();
      //   break;

      // case SPI_SET_BIT_ORDER:  // SPI.setBitOrder
      //   type = cached[1];
      //   SPI.setBitOrder((type ? MSBFIRST : LSBFIRST));
      //   break;

      // case SPI_SET_CLOCK:  // SPI.setClockDivider
      //   val = cached[1];
      //   if (val == 0) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV2);
      //   } else if (val == 1) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV4);
      //   } else if (val == 2) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV8);
      //   } else if (val == 3) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV16);
      //   } else if (val == 4) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV32);
      //   } else if (val == 5) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV64);
      //   } else if (val == 6) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV128);
      //   } else if (val == 7) {
      //     SPI.setClockDivider(SPI_CLOCK_DIV256);
      //   }
      //   break;

      // case SPI_SET_DATA_MODE:  // SPI.setDataMode
      //   val = cached[1];
      //   if (val == 0) {
      //     SPI.setDataMode(SPI_MODE0);
      //   } else if (val == 1) {
      //     SPI.setDataMode(SPI_MODE1);
      //   } else if (val == 2) {
      //     SPI.setDataMode(SPI_MODE2);
      //   } else if (val == 3) {
      //     SPI.setDataMode(SPI_MODE3);
      //   }
      //   break;

      // case SPI_TRANSFER:  // SPI.transfer
      //   val = cached[1];
      //   val = SPI.transfer(val);
      //   server.write(0x24);
      //   server.write(val);
      //   break;

      // Wire API
      case I2C_CONFIG:
        delayTime = cached[1] + (cached[2] << 7);

        #if DEBUG
        Serial.print("delayTime: ");
        Serial.println(delayTime, DEC);
        #endif

        if (delayTime > 0) {
          i2cReadDelayTime = delayTime;
        }

        pinModeFor[0] = 0x06;
        pinModeFor[1] = 0x06;

        if (!Wire.isEnabled()) {
          #if DEBUG
          Serial.println("******* Enable I2C ******");
          #endif

          Wire.begin();
        }

        break;

      case I2C_WRITE:
        address = cached[1];
        dataLength = cached[2] + (cached[3] << 7);

        #if DEBUG
        Serial.print("address: ");
        Serial.println(address, HEX);
        Serial.print("data length: ");
        Serial.println(dataLength, DEC);
        #endif

        cacheBuffer(byteCount, dataLength);
        byteCount -= dataLength;

        Wire.beginTransmission(address);
        for (byte i = 0; i < dataLength; i += 2) {
          val = cached[i] + (cached[i + 1] << 7);

          #if DEBUG
          Serial.print("data[");
          Serial.print(i, DEC);
          Serial.print("]: 0x");
          Serial.print(val, HEX);
          Serial.print(", ");
          #endif

          Wire.write(val);
        }

        #if DEBUG
        Serial.println("");
        #endif

        Wire.endTransmission();
        delayMicroseconds(70);
        break;

      case I2C_READ:
      case I2C_READ_CONTINUOUS:
        address = cached[1];
        reg = cached[2] + (cached[3] << 7);  // register
        val = cached[4] + (cached[5] << 7);  // bytes to read

        #if DEBUG
        Serial.print("address: ");
        Serial.println(address, HEX);
        Serial.print("register: ");
        Serial.println(reg, HEX);
        Serial.print("data: ");
        Serial.println(val);
        #endif

        // reg was a dummy
        if (reg == 0xFF) {
          reg = (int)I2C_REGISTER_NOT_SPECIFIED;
          #if DEBUG
          Serial.println("I2C_REGISTER_NOT_SPECIFIED");
          #endif
        }

        if (action == I2C_READ_CONTINUOUS) {
          if ((i2cIndex + 1) > MAX_I2C_READ_CONTINUOUS_DEVICES) {
            // TODO: need to add an error protocol.
            // For now, it's unlikely that this will be an issue.
          }
          i2cIndex++;
          i2cDevices[i2cIndex].address = address;
          i2cDevices[i2cIndex].reg = reg;
          i2cDevices[i2cIndex].bytes = val;
        } else {
          readAndReportI2cData(address, reg, val);
        }

        break;

      case SERVO_WRITE:
        pin = cached[1];
        val = cached[2];
        #if DEBUG
        Serial.print("PIN: ");
        Serial.println(pin);
        Serial.print("WRITING TO SERVO: ");
        Serial.println(val);
        #endif
        servos[ToServoIndex(pin)].write(val);
        break;

      case INTERNAL_RGB:
        byte red;
        byte green;
        byte blue;
        red = cached[1];
        green = cached[2];
        blue = cached[3];
        #if DEBUG
        Serial.println("WRITING TO INTERNAL RGB LED.");
        Serial.print("Red: ");
        Serial.println(red);
        Serial.print("Green: ");
        Serial.println(green);
        Serial.print("Blue: ");
        Serial.println(blue);
        #endif
        RGB.control(true);
        RGB.color(red, green, blue);
        break;

      default: // noop
        break;
    } // <-- This is the end of the switch

    memset(&cached[0], 0, 64);

    #if DEBUG
    Serial.print("Unprocessed Bytes: ");
    Serial.println(byteCount, DEC);
    #endif

    // Reset hasAction flag (no longer needed for this opertion)
    // action and byte read expectation flags
    hasAction = false;
    bytesExpecting = 0;

    // If there were leftover bytes available,
    // call processInput. This mechanism will
    // continue until the buffer is exhausted.

    bytesRead = byteCount;

    if (byteCount > 2) {
      #if DEBUG
      Serial.println("Calling processInput ");
      #endif

      processInput();
    } else {
      #if DEBUG
      Serial.println("RETURN TO LOOP!");
      #endif
    }
  }
}

void loop() {
  if (client.connected()) {

    if (!isConnected) {
      restore();
      #if DEBUG
      Serial.println("--------------CONNECTED");
      #endif
    }

    isConnected = true;

    // Process incoming bytes first
    available = client.available();

    if (available > 0) {

      int received = 0;

      #if DEBUG
      Serial.println("--------------BUFFERING AVAILABLE BYTES");
      Serial.print("Byte Offset: ");
      Serial.println(bytesRead, DEC);
      #endif

      // Move all available bytes into the buffer,
      // this avoids building up back pressure in
      // the client byte stream.
      for (int i = 0; i < available && i < MAX_DATA_BYTES - bytesRead; i++) {
        buffer[bytesRead++] = client.read();
        received++;
      }

      #if DEBUG
      Serial.print("Bytes Received: ");
      Serial.println(received, DEC);

      Serial.print("Bytes In Buffer: ");
      Serial.println(bytesRead, DEC);

      for (int i = 0; i < bytesRead; i++) {
        Serial.print(i, DEC);
        Serial.print(":0x");
        Serial.print(buffer[i], HEX);
        Serial.print(", ");
      }
      Serial.println("");
      #endif

      processInput();
    }

    // Reporting must be limited to every ~100ms
    // Otherwise the device becomes unreliable and
    // exhibits a higher crash frequency.
    nowms = millis();
    if (nowms - lastms > sampleInterval && (reporters > 0 || i2cIndex > -1)) {
      // possible just assign the value of nowms?
      lastms += sampleInterval;
      report();
    }
  } else {
    // Upon disconnection, restore init state.
    if (isConnected) {
      restore();
    }

    // If no client is yet connected, check for a new connection
    client = server.available();
  }
}


text:
package com.elven.danmaku.sample;

import com.elven.danmaku.core.graphics.fx.EffectFactory;
import com.elven.danmaku.core.graphics.texture.TextureLoader;
import com.elven.danmaku.core.stage.StageController;
import com.elven.danmaku.core.system.Vector2D;

public class PichuunEffectFactory implements EffectFactory {

	private StageController stage;
	private TextureLoader loader;

	public PichuunEffectFactory(StageController stage, TextureLoader loader) {
		this.stage = stage;
		this.loader = loader;
	}

	@Override
	public void createEffect(Vector2D position) {
		Pichuun pichuun = new Pichuun(stage, stage.getPlayer().getPosition(), 80, loader);
		pichuun.install();
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Inodata\FloraBundle\Admin;

use Doctrine\ORM\EntityRepository;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;

class CollectionAdmin extends Admin
{
    protected $baseRouteName = 'collection';
    protected $baseRoutePattern = 'inodata/flora/collection';

    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('collector', 'genemu_jqueryselect2_entity', [
                'required'      => false,
                'empty_value'   => '',
                'class'         => 'Inodata\FloraBundle\Entity\Employee',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->where('u.jobPosition = \'Collector\'');
                },
                'attr'          => [
                    'class'       => 'inodata_collector_list span5',
                    'placeholder' => 'Selecciona un cobrador',
                    'enabled'     => 'enabled',],
            ]);
    }

    /**
     * @param Sonata\AdminBundle\Datagrid\ListMapper $listMapper
     *
     * @return void
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        /* TODO: Agregar comentarios */
        $listMapper
            ->addIdentifier('id', null, [
                'label' => 'label.order',
            ])
            ->add('customerAndContact', null, [
                'label' => 'label.customer',
            ])
            ->add('collectionDate', null, [
                'label'  => 'label.collection_date',
                'format' => 'd/M/Y',
            ])
            ->add('orderTotals', null, [
                'label' => 'label.order_total',
            ])
            ->add('_action', 'actions', [
                'label'   => 'label.distribution_actions',
                'actions' => [],
            ]);
    }

    /**
     * @param Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper
     *
     * @return void
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('collector', null, [
                'label' => 'label.collection_collector',
            ], null, [
                'query_builder' => function ($er) {
                    return $er->createQueryBuilder('u')
                        ->where('u.jobPosition = :type ')
                        ->setParameter('type', 'Collector');
                },
            ])
            ->add('id', null, [
                'label' => 'label.distribution_id',
            ])
            ->add('deliveryDate', 'doctrine_orm_date_range', [
                'label' => 'label.collection_filter_date',], null,
                ['widget' => 'single_text', 'attr' => ['class' => 'filter-deliver-date']])
            ->add('status', null, ['label' => 'label.distribution_status'],
                'choice', [
                    'translation_domain' => 'InodataFloraBundle',
                    'expanded'           => false,
                    'multiple'           => false,
                    'choices'            => [
                        'partiallypayment' => 'label.collection_status_pending',
                        'closed'           => 'label.collection_status_paid',],]
            );
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->remove('create');
    }

    public function getTemplate($name)
    {
        switch ($name) {
            case 'list':
                return 'InodataFloraBundle:Collection:list.html.twig';
                break;
            //case 'print':
            //	return 'InodataFloraBundle:Collection:print_distribution.html.twig';
            default:
                return parent::getTemplate($name);
                break;
        }
    }
}


text:
glu.regAdapter('progress', {
    extend : 'field',
    valueBindings:{
        setComponentProperty:function (value, oldValue, options, control) {
            control.updateProgress(value);
        }
    }
});


text:
package org.openqa.selenium.remote.server;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.http.HttpMethod;
import org.openqa.selenium.remote.server.commandhandler.GetLogTypes;
import org.openqa.selenium.remote.server.commandhandler.GetLogsOfType;
import org.openqa.selenium.remote.server.commandhandler.NoHandler;
import org.openqa.selenium.remote.server.commandhandler.NoSessionHandler;
import org.openqa.selenium.remote.server.commandhandler.Status;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;

class AllHandlers {

  private final static Gson GSON = new GsonBuilder().setLenient().serializeNulls().create();
  private final ActiveSessions allSessions;

  private final Map<HttpMethod, ImmutableList<Function<String, CommandHandler>>> additionalHandlers;

  public AllHandlers(ActiveSessions allSessions) {
    this.allSessions = allSessions;

    additionalHandlers = ImmutableMap.of(
        HttpMethod.DELETE, ImmutableList.of(),
        HttpMethod.GET, ImmutableList.of(
            handler("/session/{sessionId}/log/types", GetLogTypes.class),
            handler("/status", Status.class)
        ),
        HttpMethod.POST, ImmutableList.of(
            handler("/session", BeginSession.class),
            handler("/session/{sessionId}/log", GetLogsOfType.class)
        ));
  }

  public CommandHandler match(HttpServletRequest req) {
    String path = Strings.isNullOrEmpty(req.getPathInfo()) ? "/" : req.getPathInfo();

    Optional<? extends CommandHandler> additionalHandler = additionalHandlers.get(HttpMethod.valueOf(req.getMethod()))
        .stream()
        .map(bundle -> bundle.apply(req.getPathInfo()))
        .filter(Objects::nonNull)
        .findFirst();

    if (additionalHandler.isPresent()) {
      return additionalHandler.get();
    }

    // All commands that take a session id expect that as the path fragment immediately after "/session".
    SessionId id = null;
    List<String> fragments = Splitter.on('/').limit(4).splitToList(path);
    if (fragments.size() > 2) {
      if ("session".equals(fragments.get(1))) {
        id = new SessionId(fragments.get(2));
      }
    }

    if (id != null) {
      ActiveSession session = allSessions.get(id);
      if (session == null) {
        return new NoSessionHandler(id);
      }
      return session;
    }

    return new NoHandler();
  }

  private <H extends CommandHandler> Function<String, CommandHandler> handler(
      String template,
      Class<H> handler) {
    UrlTemplate urlTemplate = new UrlTemplate(template);
    return path -> {
      UrlTemplate.Match match = urlTemplate.match(path);
      if (match == null) {
        return null;
      }

      ImmutableSet.Builder<Object> args = ImmutableSet.builder();
      args.add(allSessions);
      args.add(GSON);
      if (match.getParameters().containsKey("sessionId")) {
        SessionId id = new SessionId(match.getParameters().get("sessionId"));
        args.add(id);
        ActiveSession session = allSessions.get(id);
        if (session != null) {
          args.add(session);
        }
      }
      match.getParameters().entrySet().stream()
          .filter(e -> !"sessionId".equals(e.getKey()))
          .forEach(e -> args.add(e.getValue()));

      return create(handler, args.build());
    };
  }

  @VisibleForTesting
  <T extends CommandHandler> T create(Class<T> toCreate, Set<Object> args) {
    Constructor<?> constructor = Stream.of(toCreate.getDeclaredConstructors())
        .peek(c -> c.setAccessible(true))
        .sorted((l, r) -> r.getParameterCount() - l.getParameterCount())
        .filter(c ->
                    Stream.of(c.getParameters())
                        .map(p -> args.stream()
                            .anyMatch(arg -> p.getType().isAssignableFrom(arg.getClass())))
                        .reduce(Boolean::logicalAnd)
                        .orElse(true))
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException("Cannot find constructor to populate"));

    List<Object> parameters = Stream.of(constructor.getParameters())
        .map(p -> args.stream()
            .filter(arg -> p.getType().isAssignableFrom(arg.getClass()))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException(
                "Cannot find match for " + p + " in " + toCreate)))
        .collect(Collectors.toList());

    try {
      Object[] objects = parameters.toArray();
      return (T) constructor.newInstance(objects);
    } catch (ReflectiveOperationException e) {
      throw new IllegalArgumentException("Cannot invoke constructor", e);
    }
  }
}


text:
static NSString *const ALL_ITEMS_ID = @"AllItemsToolbarItem";
static NSString *const CLASS_PREDICATE_FORMAT = @"(self isKindOfClass: %@)";
static NSString *const SEARCH_PREDICATE_FORMAT = @"(name contains[cd] %@ OR description contains[cd] %@)";
static NSString *const SEARCH_AND_CLASS_PREDICATE_FORMAT = @"(name contains[cd] %@ OR description contains[cd] %@) AND (self isKindOfClass: %@)";

@interface ATZPluginWindowController ()
@property (nonatomic, assign) Class selectedPackageClass;
@property (nonatomic, assign) NSView *hoverButtonsContainer;
@end

@implementation ATZPluginWindowController

- (id)init {
    @throw [NSException exceptionWithName:@"There's a better initializer" reason:@"Use -initWithNibName:inBundle:" userInfo:nil];
}

- (id)initWithBundle:(NSBundle *)bundle {
    if (self = [super initWithWindowNibName:@"PluginWindow"]) {
        [[self.window toolbar] setSelectedItemIdentifier:ALL_ITEMS_ID];
        [self addVersionToWindow];

        _filterPredicate = [NSPredicate predicateWithValue:YES];

        @try {
            if ([NSUserNotificationCenter class]) {
                [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
            }
        }
        @catch(NSException *exception) { NSLog(@"I've heard you like exceptions... %@", exception); }
    }
    return self;
}

- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification {
    [self.window makeKeyAndOrderFront:self];
}

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification {
    return YES;
}

#pragma mark - Bindings

- (IBAction)checkboxPressed:(NSButton *)checkbox {
    ATZPackage *package = [self.packages filteredArrayUsingPredicate:self.filterPredicate][[self.tableView rowForView:checkbox]];

    if (package.isInstalled)
        [self removePackage:package andUpdateCheckbox:checkbox];
    else
        [self installPackage:package andUpdateCheckbox:checkbox];
}

- (IBAction)showAllPackagesPressed:(id)sender {
    self.selectedPackageClass = nil;
    [self updatePredicate];
}

- (IBAction)showOnlyPluginsPressed:(id)sender {
    self.selectedPackageClass = [ATZPlugin class];
    [self updatePredicate];
}

- (IBAction)showOnlyColorSchemesPressed:(id)sender {
    self.selectedPackageClass = [ATZColorScheme class];
    [self updatePredicate];
}

- (IBAction)showOnlyTemplatesPressed:(id)sender {
    self.selectedPackageClass = [ATZTemplate class];
    [self updatePredicate];
}

- (IBAction)displayScreenshotPressed:(NSButton *)sender {
    ATZPackage *package = [self.packages filteredArrayUsingPredicate:self.filterPredicate][[self.tableView rowForView:sender]];

    [self displayScreenshot:package.screenshotPath withTitle:package.name];
}

- (IBAction)openPackageWebsitePressed:(NSButton *)sender {
    ATZPackage *package = [self.packages filteredArrayUsingPredicate:self.filterPredicate][[self.tableView rowForView:sender]];

    [self openWebsite:package.website];
}

- (void)controlTextDidChange:(NSNotification *)note {
    [self updatePredicate];
}

- (void)keyDown:(NSEvent *)theEvent {
    if (([theEvent modifierFlags] & NSCommandKeyMask) && [[theEvent characters] characterAtIndex:0] == 'f') {
        [self.window makeFirstResponder:self.searchField];
    } else {
        [super keyDown:theEvent];
    }
}

#pragma mark - Private

- (void)removePackage:(ATZPackage *)package andUpdateCheckbox:(NSButton *)checkbox {
    [self showInstallationIndicators];

    [package removeWithCompletion:^(NSError *failure) {

        NSString *message = failure ? [NSString stringWithFormat:@"%@ failed to uninstall :( Error: %@", package.name, failure.domain] :
                                      [NSString stringWithFormat:@"%@ uninstalled.", package.name];

        [self flashNotice:message];
        [self reloadUIForPackage:package fromCheckbox:checkbox];
    }];
}

- (void)installPackage:(ATZPackage *)package andUpdateCheckbox:(NSButton *)checkbox {
    [self showInstallationIndicators];
    [package installWithProgressMessage:^(NSString *progressMessage) { self.statusLabel.stringValue = progressMessage; }
                             completion:^(NSError *failure) {

        NSString *message = failure ? [NSString stringWithFormat:@"%@ failed to install :( Error: %@", package.name, failure.domain] :
                                      [NSString stringWithFormat:@"%@ installed.", package.name];
        NSLog(@"%@", message);
        [self flashNotice:message];
        [self reloadUIForPackage:package fromCheckbox:checkbox];
    }];
}

- (void)reloadUIForPackage:(ATZPackage *)package fromCheckbox:(NSButton *)checkbox {
    [self hideInstallationIndicators];
    [self reloadCheckbox:checkbox];
    if (package.requiresRestart) [self.restartLabel setHidden:NO];
}

- (void)hideInstallationIndicators {
    [[self progressIndicator] stopAnimation:nil];
    [[self progressIndicator] setHidden:YES];
}

- (void)showInstallationIndicators {
    [[self progressIndicator] setHidden:NO];
    [[self progressIndicator] startAnimation:nil];
}

- (void)reloadCheckbox:(NSButton *)checkbox {
    [self.tableView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:[self.tableView rowForView:checkbox]]
                              columnIndexes:[NSIndexSet indexSetWithIndex:0]];
}

- (void)updatePredicate {
    NSString *searchText = self.searchField.stringValue;
    // filter by type and search field text
    if (self.selectedPackageClass && searchText.length > 0) {
        self.filterPredicate = [NSPredicate predicateWithFormat:SEARCH_AND_CLASS_PREDICATE_FORMAT, searchText, searchText, self.selectedPackageClass];

    // filter by type
    } else if (self.selectedPackageClass) {
        self.filterPredicate = [NSPredicate predicateWithFormat:CLASS_PREDICATE_FORMAT, self.selectedPackageClass];

    // filter by search field text
    } else if (searchText.length > 0) {
        self.filterPredicate = [NSPredicate predicateWithFormat:SEARCH_PREDICATE_FORMAT, searchText, searchText];

    // show all
    } else {
        self.filterPredicate = [NSPredicate predicateWithValue:YES];
    }
}

- (void)reloadPackages {
    ATZDownloader *downloader = [ATZDownloader new];
    [downloader downloadPackageListWithCompletion:^(NSDictionary *packageList, NSError *error) {

        if (error) {
            NSLog(@"Error while downloading packages! %@", error);
            [self flashNotice:[NSString stringWithFormat:@"Download failed: %@", error.domain]];
        } else {
            self.packages = [ATZPackageFactory createPackagesFromDicts:packageList];
            [self updatePackages];
        }
    }];
}

- (void)updatePackages {
    for (ATZPackage *package in self.packages) {

        if (package.isInstalled) {
            NSOperation *updateOperation = [NSBlockOperation blockOperationWithBlock:^{
                [package updateWithProgressMessage:^(NSString *proggressMessage) {

                    [self flashNotice:proggressMessage];

                } completion:^(NSError *failure) {}];
            }];
            [updateOperation addDependency:[[NSOperationQueue mainQueue] operations].lastObject];
            [[NSOperationQueue mainQueue] addOperation:updateOperation];
        }
    }
}

- (void)flashNotice:(NSString *)notice {
    self.statusLabel.stringValue = notice;
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self.statusLabel performSelector:@selector(setStringValue:) withObject:@"" afterDelay:3];
    }];
}

- (void)openWebsite:(NSString *)address {
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:address]];
}

- (void)displayScreenshot:(NSString *)screenshotPath withTitle:(NSString *)title {

    [self.previewPanel.animator setAlphaValue:0.f];
    self.previewPanel.title = title;
    [self retrieveImageViewForScreenshot:screenshotPath completion:^(NSImage *image) {

        self.previewImageView.image = image;
        [NSAnimationContext beginGrouping];

        [self.previewImageView.animator setFrame:(CGRect){ .origin = CGPointMake(0, 0), .size = image.size }];
        CGRect previewPanelFrame = (CGRect){.origin = self.previewPanel.frame.origin, .size = image.size};
        [self.previewPanel setFrame:previewPanelFrame display:NO animate:YES];

        [NSAnimationContext endGrouping];

        [self.previewPanel makeKeyAndOrderFront:self];
        [self.previewPanel.animator setAlphaValue:1.f];

    }];
}

- (void)retrieveImageViewForScreenshot:(NSString *)screenshotPath completion:(void (^)(NSImage *))completion {

    ATZDownloader *downloader = [ATZDownloader new];
    [downloader downloadFileFromPath:screenshotPath completion:^(NSData *responseData, NSError *error) {

        NSImage *image = [[NSImage alloc] initWithData:responseData];
        completion(image);
    }];

}

- (void) addVersionToWindow {
    NSView *windowFrameView = [[self.window contentView] superview];
    NSTextField *label = [[ATZVersionLabel alloc] initWithFrame:NSMakeRect(self.window.frame.size.width - 38, windowFrameView.bounds.size.height - 26, 30, 20)];
    label.autoresizingMask = NSViewMinXMargin | NSViewMinYMargin | NSViewNotSizable;
    [windowFrameView addSubview:label];
}

@end


text:
from __future__ import unicode_literals, absolute_import

class Terms(dict):

    def __init__(self, field_name, terms, execution=None):
        super(Terms, self).__init__()
        self.field_name = field_name
        self.terms = terms
        self.execution = execution
        self["terms"] = self._build_dict()

    def _build_dict(self):
        terms = {
            self.field_name: self.terms
        }
        if self.execution is not None:
            terms["execution"] = self.execution
        return terms


text:
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import BaseLayer from '../base-layer';
import {Model, Program, Geometry} from 'luma.gl';
const glslify = require('glslify');

const ATTRIBUTES = {
  instancePositions: {size: 4, '0': 'x0', '1': 'y0', '2': 'x1', '3': 'y1'},
  instanceColors: {size: 3, '0': 'red', '1': 'green', '2': 'blue'}
};

export default class LineLayer extends BaseLayer {
  /**
   * @classdesc
   * LineLayer
   *
   * @class
   * @param {object} opts
   */
  constructor({
    strokeWidth = 9,
    ...opts
  } = {}) {
    super({
      strokeWidth,
      ...opts
    });
  }

  initializeState() {
    const {gl, attributeManager} = this.state;

    const model = this.createModel(gl);
    model.userData.strokeWidth = this.props.strokeWidth;
    this.setState({model});

    attributeManager.addInstanced(ATTRIBUTES, {
      instancePositions: {update: this.calculateInstancePositions},
      instanceColors: {update: this.calculateInstanceColors}
    });
  }

  willReceiveProps(oldProps, nextProps) {
    super.willReceiveProps(oldProps, nextProps);
    this.state.model.userData.strokeWidth = nextProps.strokeWidth;
  }

  createModel(gl) {
    const positions = [0, 0, 0, 1, 1, 1];

    return new Model({
      program: new Program(gl, {
        vs: glslify('./line-layer-vertex.glsl'),
        fs: glslify('./line-layer-fragment.glsl'),
        id: 'line'
      }),
      geometry: new Geometry({
        id: 'line',
        drawMode: 'LINE_STRIP',
        positions: new Float32Array(positions)
      }),
      isInstanced: true,
      onBeforeRender() {
        this.userData.oldStrokeWidth = gl.getParameter(gl.LINE_WIDTH);
        this.program.gl.lineWidth(this.userData.strokeWidth || 1);
      },
      onAfterRender() {
        this.program.gl.lineWidth(this.userData.oldStrokeWidth || 1);
      }
    });
  }

  calculateInstancePositions(attribute) {
    const {data} = this.props;
    const {value, size} = attribute;
    let i = 0;
    for (const line of data) {
      value[i + 0] = line.position.x0;
      value[i + 1] = line.position.y0;
      value[i + 2] = line.position.x1;
      value[i + 3] = line.position.y1;
      i += size;
    }
  }

  calculateInstanceColors(attribute) {
    const {data} = this.props;
    const {value, size} = attribute;
    let i = 0;
    for (const point of data) {
      value[i + 0] = point.color[0];
      value[i + 1] = point.color[1];
      value[i + 2] = point.color[2];
      i += size;
    }
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>ERROR_*</title>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">

ERROR_*

главная |
типы и определения

Перечислены типы ошибок, возвращаемые функцией GetLastError, известные Far Manager (см. FMSG_ERRORTYPE):

    Константа из winerror.h
    Строковые константы из Far*.lng

    ERROR_INVALID_FUNCTION
    "Некорректная функция"

"Incorrect function"

    ERROR_BAD_COMMAND, ERROR_CALL_NOT_IMPLEMENTED
    "Команда не распознана"

"Command not recognized"

    ERROR_FILE_NOT_FOUND
    "Файл не найден"

"File not found"

    ERROR_PATH_NOT_FOUND
    "Путь не найден"

"Path not found"

    ERROR_TOO_MANY_OPEN_FILES
    "Слишком много открытых
      файлов"

"Too many open files"

    ERROR_ACCESS_DENIED
    "Доступ запрещён"

"Access denied"

    ERROR_NOT_ENOUGH_MEMORY, ERROR_OUTOFMEMORY
    "Недостаточно памяти"

"Not enough memory"

    ERROR_WRITE_PROTECT
    "Попытка записи на
      защищённый от записи диск"

"Cannot write to write protected disk"

    ERROR_NOT_READY
    "Устройство не готово"

"The device is not ready"

    ERROR_NOT_DOS_DISK
    "Доступ к диску невозможен"

"Disk cannot be accessed"

    ERROR_SECTOR_NOT_FOUND
    "Сектор не найден"

"Sector not found"

    ERROR_OUT_OF_PAPER
    "В принтере нет бумаги"

"The printer is out of paper"

    ERROR_WRITE_FAULT
    "Ошибка записи"

"Write fault error"

    ERROR_READ_FAULT
    "Ошибка чтения"

"Read fault error"

    ERROR_GEN_FAILURE
    "Общая ошибка устройства"

"Device general failure"

    ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION
    "Нарушение совместного доступа к файлу"

"File sharing violation"

    ERROR_BAD_NETPATH
    "Сетевой путь не найден"

"The network path was not found"

    ERROR_NETWORK_BUSY
    "Сеть занята"

"The network is busy"

    ERROR_NETWORK_ACCESS_DENIED
    "Сетевой доступ запрещён"

"Network access is denied"

    ERROR_NET_WRITE_FAULT
    "Ошибка записи в сети"

"A write fault occurred on the network"

    ERROR_DRIVE_LOCKED
    "Диск используется или заблокирован другим процессом"

"The disk is in use or locked by another process"

    ERROR_ALREADY_EXISTS
    "Файл или папка уже существует"

"File or folder already exists"

    ERROR_BAD_PATHNAME, ERROR_INVALID_NAME
    "Указанное имя неверно"

"The specified name is invalid"

    ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL
    "Нет места на диске"

"Insufficient disk space"

    ERROR_DIR_NOT_EMPTY
    "Папка не пустая"

"The folder is not empty"

    ERROR_INTERNET_INCORRECT_USER_NAME
    "Неверное имя пользователя"

"Incorrect user name"

    ERROR_INTERNET_INCORRECT_PASSWORD
    "Неверный пароль"

"Incorrect password"

    ERROR_INTERNET_LOGIN_FAILURE
    "Ошибка регистрации"

"Login failure"

    ERROR_INTERNET_CONNECTION_ABORTED
    "Соединение разорвано"

"Connection aborted"

    ERROR_CANCELLED
    "Операция отменена"

"Operation cancelled"

    ERROR_NO_NETWORK
    "Сеть отсутствует"

"No network present"

    ERROR_DEVICE_IN_USE
    "Устройство используется и
      не может быть отсоединено"

"Device is in use and cannot be disconnected"

    ERROR_OPEN_FILES
    "На сетевом диске есть открытые файлы"

"This network connection has open files"

    ERROR_ALREADY_ASSIGNED
    "Имя локального устройства уже использовано"

"The local device name is already in use"

    ERROR_DEVICE_ALREADY_REMEMBERED
    "Имя локального устройства уже находится в профайле пользователя"

"The local device is already in the user profile"

    ERROR_NOT_LOGGED_ON
    "Пользователь не зарегистрирован в сети"

"User has not logged on to the network"

    ERROR_INVALID_PASSWORD
    "Неверный пароль
      пользователя"

"The user password is invalid"

    ERROR_NO_RECOVERY_POLICY
    "Для этой системы
      отсутствует политика надёжного
      восстановления шифрования"

"There is no valid encryption recovery policy configured for
      this system"

    ERROR_ENCRYPTION_FAILED
    "Ошибка при попытке
      шифрования файла"

"The specified file could not be encrypted"

    ERROR_DECRYPTION_FAILED
    "Ошибка при попытке
      расшифровки файла"

"The specified file could not be decrypted"

    ERROR_FILE_NOT_ENCRYPTED
    "Указанный файл не
      зашифрован"

"The specified file is not encrypted"

Смотрите также:

Message


text:
'use strict';

angular.module('directives')
    .directive("hCareActionBtn", function(Authentication, lodash){
        return{
            restrict: "E",
            replace: true,
            link :function(scope, element, atts){
                if(lodash.contains(Authentication.user._role._actions, atts.action)){

                    if(atts.redirectUrl != null && atts.redirectUrl != undefined && atts.redirectUrl != ''){
                        atts.$observe('redirectUrl', function(redirectUrl){
                            var buttonText = '' +
                                '' +
                                '';
                            element.html(buttonText);
                        });
                    }

                    if(atts.clickEvent != null && atts.clickEvent != undefined && atts.clickEvent !='') {
                        var buttonText = "" +
                            "" +
                            "";
                        element.html(buttonText);
                        element.on("click", function () {
                            if(atts.responseMessage != null && atts.responseMessage != undefined && atts.responseMessage !='') {
                                if (confirm(atts.responseMessage)) {
                                    //apply only
                                    scope.$apply(atts.clickEvent);

                                }
                            }
                            else {
                                scope.$apply(atts.clickEvent);
                            }
                        });
                    }

                }
            }
        }
    });


text:
package com.github.phenomics.ontolib.io.obo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;

import com.github.phenomics.ontolib.io.obo.StanzaEntry;
import com.github.phenomics.ontolib.io.obo.StanzaEntrySavedBy;
import com.github.phenomics.ontolib.io.obo.StanzaEntryType;

import de.charite.compbio.ontolib.io.obo.parser.Antlr4OboParser;
import de.charite.compbio.ontolib.io.obo.parser.Antlr4OboParser.HeaderKeyValueContext;
import de.charite.compbio.ontolib.io.obo.parser.Antlr4OboParser.KeyValueSavedByContext;

public class Antlr4OboParserTestStanzaEntrySavedBy extends Antlr4OboParserTestBase {

  @Test
  public void testParseNoModifierNoCommentAsHeaderKeyValue() {
    final String text = "saved-by: user1, user2\n";
    final Antlr4OboParser parser = buildParser(text);
    final HeaderKeyValueContext ctx = parser.headerKeyValue();
    final StanzaEntry stanzaEntry = (StanzaEntry) getOuterListener().getValue(ctx);

    assertEquals(StanzaEntryType.SAVED_BY, stanzaEntry.getType());
    assertNull(stanzaEntry.getTrailingModifier());
    assertNull(stanzaEntry.getComment());
  }

  @Test
  public void testParseNoModifierNoCommentAsKeyValueSavedBy() {
    final String text = "saved-by: user1, user2\n";
    final Antlr4OboParser parser = buildParser(text);
    final KeyValueSavedByContext ctx = parser.keyValueSavedBy();
    final StanzaEntrySavedBy stanzaEntry = (StanzaEntrySavedBy) getOuterListener().getValue(ctx);

    assertEquals(StanzaEntryType.SAVED_BY, stanzaEntry.getType());
    assertEquals("user1, user2", stanzaEntry.getValue());
    assertNull(stanzaEntry.getTrailingModifier());
    assertNull(stanzaEntry.getComment());
  }

  @Test
  public void testParseModifierNoCommentAsKeyValueSavedBy() {
    final String text = "saved-by: user1, user2 {key=value}\n";
    final Antlr4OboParser parser = buildParser(text);
    final KeyValueSavedByContext ctx = parser.keyValueSavedBy();
    final StanzaEntrySavedBy stanzaEntry = (StanzaEntrySavedBy) getOuterListener().getValue(ctx);

    assertEquals(StanzaEntryType.SAVED_BY, stanzaEntry.getType());
    assertEquals("user1, user2", stanzaEntry.getValue());
    assertEquals("TrailingModifier [keyValue=[KeyValue [key=key, value=value]]]",
        stanzaEntry.getTrailingModifier().toString());
    assertNull(stanzaEntry.getComment());
  }

  @Test
  public void testParseNoModifierCommentAsKeyValueSavedBy() {
    final String text = "saved-by: user1, user2 ! comment\n";
    final Antlr4OboParser parser = buildParser(text);
    final KeyValueSavedByContext ctx = parser.keyValueSavedBy();
    final StanzaEntrySavedBy stanzaEntry = (StanzaEntrySavedBy) getOuterListener().getValue(ctx);

    assertEquals(StanzaEntryType.SAVED_BY, stanzaEntry.getType());
    assertEquals("user1, user2", stanzaEntry.getValue());
    assertNull(stanzaEntry.getTrailingModifier());
    assertEquals("comment", stanzaEntry.getComment().toString());
  }

  @Test
  public void testParseModifierCommentAsKeyValueSavedBy() {
    final String text = "saved-by: user1, user2 {key=value} ! comment\n";
    final Antlr4OboParser parser = buildParser(text);
    final KeyValueSavedByContext ctx = parser.keyValueSavedBy();
    final StanzaEntrySavedBy stanzaEntry = (StanzaEntrySavedBy) getOuterListener().getValue(ctx);

    assertEquals(StanzaEntryType.SAVED_BY, stanzaEntry.getType());
    assertEquals("user1, user2", stanzaEntry.getValue());
    assertEquals("TrailingModifier [keyValue=[KeyValue [key=key, value=value]]]",
        stanzaEntry.getTrailingModifier().toString());
    assertEquals("comment", stanzaEntry.getComment());
  }

}


text:
/*
 * Generated by the 'fontello-Inferno' Grunt task.
 */
@font-face {
    font-family: 'fontello';
    src: url('./../../assets/font/fontello.eot?1446328305390');
    src: url('./../../assets/font/fontello.eot?1446328305390#iefix') format('embedded-opentype'),
       url('./../../assets/font/fontello.woff?1446328305390') format('woff'),
       url('./../../assets/font/fontello.ttf?1446328305390') format('truetype'),
       url('./../../assets/font/fontello.svg?1446328305390#fontello') format('svg');
    font-weight: normal;
    font-style: normal;
}

/* Chrome hack: SVG is rendered more smooth in Windozze. 100% magic, uncomment if you need it. */
/* Note, that will break hinting! In other OS-es font will be not as sharp as it could be */
/*
@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
    font-family: 'fontello';
    src: url('../font/fontello.svg#fontello') format('svg');
  }
}
*/

.icon:before {
    font-family: "fontello";
    font-style: normal;
    font-weight: normal;
    speak: none;

    display: inline-block;
    text-decoration: inherit;
    width: 1em;
    text-align: center;
    /* opacity: .8; */

    /* For safety - reset parent styles, that can break glyph codes*/
    font-variant: normal;
    text-transform: none;

    /* fix buttons height, for twitter bootstrap */
    line-height: 1em;

    /* you can be more comfortable with increased icons size */
    /* font-size: 120%; */

    /* Font smoothing. That was taken from TWBS */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;

    /* Uncomment for 3D effect */
    /* text-shadow: 1px 1px 1px rgba(127, 127, 127, 0.3); */
}

.icon--github-circled-alt2:before {
    content: '\e800';
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="coqdoc.css" rel="stylesheet" type="text/css"/>
<title>Table of contents</title>

Symbols: Special symbols

Preface

Welcome

Overview

Logic

Proof Assistants

Functional Programming

Program Verification

Type Systems

Practicalities

System Requirements

Exercises

Chapter Dependencies

Downloading the Coq Files

Note for Instructors

Translations

Basics: Functional Programming in Coq

Introduction

Enumerated Types

Days of the Week

Booleans

Function Types

Numbers

Proof by Simplification

Proof by Rewriting

Proof by Case Analysis

More Exercises

Optional Material

More on Notation

Fixpoints and Structural Recursion

Induction: Proof by Induction

Naming Cases

Proof by Induction

Proofs Within Proofs

More Exercises

Advanced Material

Formal vs. Informal Proof

Lists: Working with Structured Data

Pairs of Numbers

Lists of Numbers

Bags via Lists

Reasoning About Lists

Micro-Sermon

Induction on Lists

SearchAbout

List Exercises, Part 1

List Exercises, Part 2

Options

Dictionaries

Poly: Polymorphism and Higher-Order Functions

Polymorphism

Polymorphic Lists

Polymorphic Pairs

Polymorphic Options

Functions as Data

Higher-Order Functions

Partial Application

Digression: Currying

Filter

Anonymous Functions

Map

Map for options

Fold

Functions For Constructing Functions

The unfold Tactic

Additional Exercises

MoreCoq: More About Coq

The apply Tactic

The apply ... with ... Tactic

The inversion tactic

Using Tactics on Hypotheses

Varying the Induction Hypothesis

Using destruct on Compound Expressions

Review

Additional Exercises

Logic: Logic in Coq

Propositions

Proofs and Evidence

Implications are functions

Defining Propositions

Conjunction (Logical "and")

"Introducing" Conjuctions

"Eliminating" conjunctions

Iff

Disjunction (Logical "or")

Implementing Disjunction

Relating ∧ and ∨ with andb and orb (advanced)

Falsehood

Truth

Negation

Inequality

Prop: Propositions and Evidence

From Boolean Functions to Propositions

Inductively Defined Propositions

Inductively Defined Propositions

Inference Rules

Induction Over Evidence

Inversion on Evidence

inversion revisited

Additional Exercises

Relations

Programming with Propositions Revisited

MoreLogic

More Logic

Existential Quantification

Evidence-carrying booleans.

Additional Exercises

ProofObjects: Working with Explicit Evidence in Coq

Proof Scripts and Proof Objects

Quantification, Implications and Functions

Giving Explicit Arguments to Lemmas and Hypotheses

Programming with Tactics (Optional)

MoreInd: More on Induction

Induction Principles

Induction Hypotheses

More on the induction Tactic

Generalizing Inductions.

Informal Proofs (Advanced)

Informal Proofs by Induction

Optional Material

Induction Principles in Prop

Additional Exercises

Induction Principles for other Logical Propositions

Explicit Proof Objects for Induction

The Coq Trusted Computing Base

Review1: Review Session for First Midterm

General Notes

Expressions and Their Types

Inductive Definitions

Tactics

Proof Objects

Functional Programming

Judging Propositions

More Type Checking

SfLib: Software Foundations Library

From the Coq Standard Library

From Basics.v

From Props.v

From Logic.v

From Later Files

Some useful tactics

Imp: Simple Imperative Programs

Arithmetic and Boolean Expressions

Syntax

Evaluation

Optimization

Coq Automation

Tacticals

Defining New Tactic Notations

The omega Tactic

A Few More Handy Tactics

Evaluation as a Relation

Inference Rule Notation

Equivalence of the Definitions

Computational vs. Relational Definitions

Expressions With Variables

Identifiers

States

Syntax

Evaluation

Commands

Syntax

Examples

Evaluation

Evaluation as a Function (Failed Attempt)

Evaluation as a Relation

Determinism of Evaluation

Reasoning About Imp Programs

Additional Exercises

ImpParser: Lexing and Parsing in Coq

Internals

Lexical Analysis

Parsing

Examples

ImpCEvalFun: Evaluation Function for Imp

Evaluation Function

Equivalence of Relational and Step-Indexed Evaluation

Determinism of Evaluation (Simpler Proof)

Extraction: Extracting ML from Coq

Basic Extraction

Controlling Extraction of Specific Types

A Complete Example

Discussion

Equiv: Program Equivalence

Behavioral Equivalence

Definitions

Examples

The Functional Equivalence Axiom

Properties of Behavioral Equivalence

Behavioral Equivalence is an Equivalence

Behavioral Equivalence is a Congruence

Program Transformations

The Constant-Folding Transformation

Soundness of Constant Folding

Proving That Programs Are Not Equivalent

Extended exercise: Non-deterministic Imp

Doing Without Extensionality (Optional)

Additional Exercises

Hoare: Hoare Logic, Part I

Hoare Logic

Assertions

Hoare Triples

Proof Rules

Hoare Logic: So Far

Hoare Logic Rules (so far)

Exercise: HAVOC

Complete List of Hoare Logic Rules

Hoare2: Hoare Logic, Part II

Decorated Programs

Example: Swapping Using Addition and Subtraction

Example: Simple Conditionals

Example: Reduce to Zero (Trivial Loop)

Example: Division

Finding Loop Invariants

Example: Slow Subtraction

Exercise: Slow Assignment

Exercise: Slow Addition

Example: Parity

Example: Finding Square Roots

Example: Squaring

Exercise: Factorial

Exercise: Min

Exercise: Power Series

Weakest Preconditions (Advanced)

Formal Decorated Programs (Advanced)

Syntax

Extracting Verification Conditions

Examples

Smallstep: Small-step Operational Semantics

A Toy Language

Relations

Values

Strong Progress and Normal Forms

Multi-Step Reduction

Examples

Normal Forms Again

Equivalence of Big-Step and Small-Step Reduction

Additional Exercises

Small-Step Imp

Concurrent Imp

A Small-Step Stack Machine

Review2: Review Session for Second Midterm

General Notes

Definitions

IMP Program Equivalence

Hoare triples

Decorated programs

Auto: More Automation

The auto and eauto tactics

Searching Hypotheses

Types: Type Systems

Typed Arithmetic Expressions

Syntax

Operational Semantics

Normal Forms and Values

Typing

Canonical forms

Progress

Type Preservation

Type Soundness

Aside: the normalize Tactic

Additional Exercises

Stlc: The Simply Typed Lambda-Calculus

The Simply Typed Lambda-Calculus

Overview

Syntax

Operational Semantics

Typing

StlcProp: Properties of STLC

Canonical Forms

Progress

Preservation

Free Occurrences

Substitution

Main Theorem

Type Soundness

Uniqueness of Types

Additional Exercises

Exercise: STLC with Arithmetic

MoreStlc: More on the Simply Typed Lambda-Calculus

Simple Extensions to STLC

Numbers

let-bindings

Pairs

Unit

Sums

Lists

General Recursion

Records

Exercise: Formalizing the Extensions

Examples

Properties of Typing

Sub: Subtyping

Concepts

A Motivating Example

Subtyping and Object-Oriented Languages

The Subsumption Rule

The Subtype Relation

Exercises

Formal Definitions

Core Definitions

Subtyping

Typing

Typing examples

Properties

Inversion Lemmas for Subtyping

Canonical Forms

Progress

Inversion Lemmas for Typing

Context Invariance

Substitution

Preservation

Records, via Products and Top

Exercises

Exercise: Adding Products

This page has been generated by coqdoc


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInspection.IntentionAndQuickFixAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.undo.UndoUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.changeSignature.ChangeSignatureProcessor;
import com.intellij.refactoring.changeSignature.ParameterInfoImpl;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class MethodParameterFix extends IntentionAndQuickFixAction {
  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.MethodReturnFix");

  private final PsiMethod myMethod;
  private final PsiType myParameterType;
  private final int myIndex;
  private final boolean myFixWholeHierarchy;

  public MethodParameterFix(PsiMethod method, PsiType type, int index, boolean fixWholeHierarchy) {
    myMethod = method;
    myParameterType = type;
    myIndex = index;
    myFixWholeHierarchy = fixWholeHierarchy;
  }

  @NotNull
  public String getName() {
    return QuickFixBundle.message("fix.parameter.type.text",
                                  myMethod.getName(),
                                  myParameterType.getCanonicalText() );
  }

  @NotNull
  public String getFamilyName() {
    return QuickFixBundle.message("fix.parameter.type.family");
  }

  public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) {
    return myMethod != null
        && myMethod.isValid()
        && myMethod.getManager().isInProject(myMethod)
        && myParameterType != null
        && !TypeConversionUtil.isNullType(myParameterType)
        && myMethod.getReturnType() != null
        && !Comparing.equal(myParameterType, myMethod.getReturnType());
  }

  public void applyFix(final Project project, final PsiFile file, @Nullable final Editor editor) {
    if (!CodeInsightUtilBase.prepareFileForWrite(myMethod.getContainingFile())) return;
    try {
      PsiMethod method = myMethod;
      if (myFixWholeHierarchy) {
        method = myMethod.findDeepestSuperMethod();
        if (method == null) method = myMethod;
      }

      ChangeSignatureProcessor processor = new ChangeSignatureProcessor(project,
                                                                        method,
                                                                        false, null,
                                                                        method.getName(),
                                                                        method.getReturnType(),
                                                                        getNewParametersInfo());

      if (ApplicationManager.getApplication().isUnitTestMode()) {
        processor.run();
      }
      else {
        processor.run();
      }

      UndoUtil.markPsiFileForUndo(file);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }

  private ParameterInfoImpl[] getNewParametersInfo() throws IncorrectOperationException {
    List<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>();
    PsiParameter[] parameters = myMethod.getParameterList().getParameters();
    PsiElementFactory factory = JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(myMethod.getProject());
    SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, myParameterType);
    PsiParameter newParameter = factory.createParameter(nameInfo.names[0], myParameterType);
    if (myMethod.getContainingClass().isInterface()) {
      PsiUtil.setModifierProperty(newParameter, PsiModifier.FINAL, false);
      }

    for (int i = 0; i < parameters.length; i++) {
      PsiParameter parameter = parameters[i];
      if (i == myIndex) {
        newParameter.setName(parameter.getName());
        parameter = newParameter;
      }
      result.add(new ParameterInfoImpl(i, parameter.getName(), parameter.getType()));
    }
    if (parameters.length == myIndex) {
      result.add(new ParameterInfoImpl(-1, newParameter.getName(), newParameter.getType()));
    }
    return result.toArray(new ParameterInfoImpl[result.size()]);
  }

  public boolean startInWriteAction() {
    return true;
  }

}


text:
package in.srain.cube.request;

import android.text.TextUtils;
import in.srain.cube.cache.CacheManager;
import in.srain.cube.cache.CacheResultType;
import in.srain.cube.concurrent.SimpleTask;
import in.srain.cube.util.CLog;
import in.srain.cube.util.CubeDebug;

import java.net.URI;
import java.net.URISyntaxException;

public class CacheAbleRequest<T> extends RequestBase<T> implements ICacheAbleRequest<T> {

    public static enum ResultType {
        USE_CACHE_NOT_EXPIRED,
        USE_CACHE_ANYWAY,
        USE_CACHE_ON_TIMEOUT,
        USE_DATA_FROM_SERVER,
        USE_CACHE_ON_FAIL,
    }

    protected static final boolean DEBUG = CubeDebug.DEBUG_CACHE;
    protected static final String LOG_TAG = "cube-cache-request";

    private CacheAbleRequestHandler<T> mHandler;

    private T mCacheData;
    private boolean mOutOfDate;
    private String mCacheKey = null;

    private int mTimeout = 0;
    private boolean mHasTimeout = false;
    private boolean mUseCacheAnyway = false;
    private boolean mHasNotified = false;
    protected boolean mForceQueryFromServer = false;

    private String mInitDataPath;
    private boolean mDisableCache = false;
    private long mCacheTime;

    public CacheAbleRequest() {
    }

    public CacheAbleRequest(final CacheAbleRequestHandler<T> handler) {
        setCacheAbleRequestHandler(handler);
    }

    public void setCacheAbleRequestHandler(CacheAbleRequestHandler<T> handler) {
        mHandler = handler;
    }

    public void forceQueryFromServer(boolean force) {
        mForceQueryFromServer = force;
    }

    // ===========================================================
    // Override parent
    // ===========================================================
    @Override
    public void doSendRequest() {
        RequestCacheManager.getInstance().requestCache(this);
    }

    /**
     * Timeout will not be considerate
     *
     * @return
     */
    @Override
    protected T doRequestSync() {
        T data = RequestCacheManager.getInstance().requestCacheSync(this);
        if (data == null) {
            data = RequestManager.getInstance().getRequestProxy(this).requestSync(this);
        }
        return data;
    }

    /**
     * prepare request
     */
    @Override
    protected void prepareRequest() {
        RequestManager.getInstance().getRequestProxy(this).prepareRequest(this);
    }

    // ===========================================================
    // Override Interface
    // ===========================================================
    @Override
    public void setTimeout(int timeOut) {
        mTimeout = timeOut;
    }

    @Override
    public CacheAbleRequest<T> setUseCacheAnyway(boolean use) {
        mUseCacheAnyway = use;
        return this;
    }

    @Override
    public boolean useCacheAnyway() {
        return mUseCacheAnyway;
    }

    @Override
    public void onRequestSuccess(T data) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onRequestSuccess", getCacheKey());
        }
        if (hasBeenCanceled()) {
            return;
        }
        if (null != mHandler) {
            mHandler.onRequestFinish(data);

            // cache data is not available or
            // cache is available and time duration not reach timeout or not always use the cache
            if (mCacheData == null || (!mHasTimeout && !mUseCacheAnyway)) {
                notifyRequestFinish(ResultType.USE_DATA_FROM_SERVER, data, false);
            } else {
                if (DEBUG) {
                    CLog.d(LOG_TAG, "%s, will not notifyRequestFinish", getCacheKey());
                }
            }
        }
    }

    @Override
    public void onRequestFail(FailData failData) {
        RequestManager.getInstance().getRequestProxy(this).onRequestFail(this, failData);
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onRequestFail", getCacheKey());
        }
        if (hasBeenCanceled()) {
            return;
        }
        if (null != mHandler) {
            mHandler.onRequestFail(failData);
            if (mCacheData != null && !cacheIsDisabled() && !mUseCacheAnyway) {
                notifyRequestFinish(ResultType.USE_CACHE_ON_FAIL, mCacheData, true);
            }
        }
    }

    @Override
    public void onNoCacheData(CacheManager cacheManager) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onNoCacheData", getCacheKey());
        }
        if (hasBeenCanceled()) {
            return;
        }
        doQueryFromServer();
        beginTimeout();
    }

    protected void doQueryFromServer() {
        RequestManager.getInstance().getRequestProxy(this).sendRequest(this);
    }

    protected boolean cacheRequestResult() {
        return mForceQueryFromServer || !cacheIsDisabled();
    }

    @Override
    public boolean cacheIsDisabled() {
        if (mForceQueryFromServer) {
            return true;
        }
        return mDisableCache;
    }

    // ===========================================================
    // Implements Interface {@link ICacheAble}
    // ===========================================================
    @Override
    public void onCacheData(CacheResultType cacheResultType, T data, boolean outOfDate) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onQueryFinish, out of date: %s", getCacheKey(), outOfDate);
        }
        if (hasBeenCanceled()) {
            return;
        }
        mCacheData = data;
        mOutOfDate = outOfDate;
        if (mHandler != null) {
            mHandler.onCacheData(data, outOfDate);

            if (mUseCacheAnyway) {
                notifyRequestFinish(ResultType.USE_CACHE_ANYWAY, data, mOutOfDate);
            } else {
                if (!outOfDate) {
                    notifyRequestFinish(ResultType.USE_CACHE_NOT_EXPIRED, data, false);
                }
            }
        }
    }

    @Override
    public long getCacheTime() {
        return mCacheTime;
    }

    @Override
    public String getCacheKey() {
        if (mCacheKey == null) {
            String cacheKey = null;
            String url = getRequestData().getRequestUrl();
            try {
                URI uri = null;
                uri = new URI(url);
                cacheKey = uri.getPath();
                if (cacheKey.startsWith("/")) {
                    cacheKey = cacheKey.substring(1);
                }
                cacheKey = cacheKey.replace("/", "-");
            } catch (URISyntaxException e) {
                if (CubeDebug.DEBUG_REQUEST) {
                    e.printStackTrace();
                }
            }
            if (TextUtils.isEmpty(cacheKey)) {
                throw new RuntimeException("Cache key is null");
            }
            mCacheKey = cacheKey;
        }
        return mCacheKey;
    }

    @Override
    public String getAssertInitDataPath() {
        return mInitDataPath;
    }

    @Override
    public T onDataFromServer(String data) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onDataFromServer", getCacheKey());
        }

        T ret = super.onDataFromServer(data);

        // cache the data
        if (!TextUtils.isEmpty(data) && ret != null && cacheRequestResult()) {
            RequestCacheManager.getInstance().setCacheData(this.getCacheKey(), data);
        }
        return ret;
    }

    @Override
    public T processOriginDataFromServer(JsonData rawData) {
        rawData = RequestManager.getInstance().getRequestProxy(this).processOriginDataFromServer(this, rawData);
        return mHandler.processOriginData(rawData);
    }

    @Override
    public T processRawDataFromCache(JsonData rawData) {
        return mHandler.processOriginData(rawData);
    }

    /**
     * will only notify once
     *
     * @param type
     * @param outOfDate
     */
    private void notifyRequestFinish(ResultType type, T cacheData, boolean outOfDate) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, notifyRequestFinish: %s, %s", getCacheKey(), type, outOfDate);
        }
        if (mHasNotified) {
            return;
        }
        mHasNotified = true;
        mHandler.onCacheAbleRequestFinish(cacheData, type, outOfDate);
    }

    private void timeout() {
        mHasTimeout = true;
        if (mCacheData != null && mHandler != null) {
            notifyRequestFinish(ResultType.USE_CACHE_ON_TIMEOUT, mCacheData, true);
        }
    }

    private void beginTimeout() {
        if (mTimeout > 0 && mCacheData != null) {
            SimpleTask.postDelay(new Runnable() {
                @Override
                public void run() {
                    timeout();
                }
            }, mTimeout);
        }
    }

    @Override
    public CacheAbleRequest<T> setCacheKey(String cacheKey) {
        mCacheKey = cacheKey;
        return this;
    }

    @Override
    public CacheAbleRequest<T> setDisableCache(boolean disable) {
        mDisableCache = disable;
        return this;
    }

    @Override
    public CacheAbleRequest<T> setAssertInitDataPath(String path) {
        mInitDataPath = path;
        return this;
    }

    @Override
    public CacheAbleRequest<T> setCacheTime(long time) {
        mCacheTime = time;
        return this;
    }
}


text:
namespace qmcplusplus
{

OptimizableSPOBuilder::OptimizableSPOBuilder
(ParticleSet& p, PtclPoolType& psets, xmlNodePtr cur) :
  targetPtcl (&p)
{
}

bool
OptimizableSPOBuilder::put (xmlNodePtr cur)
{
  return true;
}

SPOSetBase*
OptimizableSPOBuilder::createSPOSetFromXML(xmlNodePtr cur)
{
  OptimizableSPOSet *spo =  new OptimizableSPOSet();
  return spo;
}

}


text:
ARGoS (Autonomous Robots Go Swarming) is a multi-physics robot simulator. iAnt-ARGoS is an extension to ARGoS that implements the iAnt CPFA algorithm and provides a mechanism for performing experiments with iAnts.

**NOTE:** ARGoS is installed on the CS Linux machines. If you wish to use ARGoS on those machines, you only need to [download and compile](https://github.com/BCLab-UNM/iAnt-ARGoS#2-compiling-and-running-the-iant-cpfa-in-argos) this repository's code.

For more detailed information, please check the [iAnt-ARGoS wiki](https://github.com/BCLab-UNM/iAnt-ARGoS/wiki).

###Quick Start Installation Guide

In order to use the iAnt CPFA in ARGoS, you must first install ARGoS on your system then download and compile the code in this repo to run with ARGoS.

#####1. Installing ARGoS

ARGoS is available for Linux and Macintosh systems. It is currently not supported on Windows. Detailed installation instructions can be found on the [ARGoS Website](http://www.argos-sim.info/user_manual.php).

######Linux Installation

1. [Download](http://www.argos-sim.info/core.php) the appropriate binary package for your Linux system.
2. In Terminal, run the following command in the directory of your installation file:
  * for Ubuntu and KUbuntu:
    ```
    $ sudo dpkg -i argos3_simulator-*.deb
    ```

  * for OpenSuse:
    ```
    $ sudo rpm -i argos3_simulator-*.rpm
    ```

######Macintosh Installation

1. The Mac OSX installation of ARGoS uses the Homebrew Package Manager. If you don't have it, install Homebrew by using the following command in Terminal.
  ```
  $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  ```

2. Obtain the Homebrew Tap for ARGoS using the following command in Terminal.
  ```
  $ brew tap ilpincy/argos3
  ```

3. Once tapped, install ARGoS with the following command in Terminal. ARGoS and its required dependencies will be downloaded and installed using Homebrew.
  ```
  $ brew install bash-completion qt lua argos3
  ```

4. Once installed, you can update ARGoS with the following two commands in Terminal.
  ```
  $ brew update
  $ brew upgrade argos3
  ```

#####2. Compiling and Running the iAnt CPFA in ARGoS

Once ARGoS is installed on your system. You can download the files in this repo, compile them for your system, and run the iAnt CPFA in ARGoS.

1. [Download](https://github.com/BCLab-UNM/iAnt-ARGoS/archive/master.zip) the iAnt-ARGoS files and unzip the folder in a directory of your choice.

2. From the Terminal, use the following commands to compile the iAnt CPFA code:
  ```
  $ cd iAnt-ARGoS-master  # go into the iAnt-ARGoS directory
  $ cd build              # go into the build directory
  $ cmake ..              # setup compilation with cmake
  $ make                  # compile the iAnt CPFA code
  $ cd ..                 # get out of the build directory
  ```

3. Launch ARGoS with the XML configuration file for your system:
  * for Linux systems:
    ```
    $ argos3 -c experiments/iAnt_linux.argos
    ```

  * for Mac systems:
    ```
    $ argos3 -c experiments/iAnt_mac.argos
    ```

###Useful Links

| Description                                 | Website                             |
|:--------------------------------------------|:------------------------------------|
| official ARGoS website and documentation    | http://www.argos-sim.info/          |
| homebrew utility for Mac OSX installations  | http://brew.sh/                     |
| cmake utility information                   | http://www.cmake.org/documentation/ |


text:
require "wsapi.fastcgi"
local ws = require "webservice"

wsapi.fastcgi.run(ws.run)