text:
/* @flow */

import type { TokenType } from "./types";
import { isIdentifierStart, isIdentifierChar, isKeyword } from "../util/identifier";
import { types as tt, keywords as keywordTypes } from "./types";
import { types as ct } from "./context";
import { SourceLocation } from "../util/location";
import { lineBreak, lineBreakG, isNewLine, nonASCIIwhitespace } from "../util/whitespace";
import State from "./state";

// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.

export class Token {
  constructor(state) {
    this.type = state.type;
    this.value = state.value;
    this.start = state.start;
    this.end = state.end;
    this.loc = new SourceLocation(state.startLoc, state.endLoc);
  }

  type: TokenType;
  value: any;
  start: number;
  end: number;
  loc: SourceLocation;
}

// ## Tokenizer

function codePointToString(code) {
  // UTF-16 Decoding
  if (code <= 0xFFFF) {
    return String.fromCharCode(code);
  } else {
    return String.fromCharCode(((code - 0x10000) >> 10) + 0xD800, ((code - 0x10000) & 1023) + 0xDC00);
  }
}

export default class Tokenizer {
  constructor(options, input) {
    this.state = new State;
    this.state.init(options, input);
  }

  // Move to the next token

  next() {
    if (!this.isLookahead) {
      this.state.tokens.push(new Token(this.state));
    }

    this.state.lastTokEnd = this.state.end;
    this.state.lastTokStart = this.state.start;
    this.state.lastTokEndLoc = this.state.endLoc;
    this.state.lastTokStartLoc = this.state.startLoc;
    this.nextToken();
  }

  // TODO

  eat(type) {
    if (this.match(type)) {
      this.next();
      return true;
    } else {
      return false;
    }
  }

  // TODO

  match(type) {
    return this.state.type === type;
  }

  // TODO

  isKeyword(word) {
    return isKeyword(word);
  }

  // TODO

  lookahead() {
    let old = this.state;
    this.state = old.clone(true);

    this.isLookahead = true;
    this.next();
    this.isLookahead = false;

    let curr = this.state.clone(true);
    this.state = old;
    return curr;
  }

  // Toggle strict mode. Re-reads the next number or string to please
  // pedantic tests (`"use strict"; 010;` should fail).

  setStrict(strict) {
    this.state.strict = strict;
    if (!this.match(tt.num) && !this.match(tt.string)) return;
    this.state.pos = this.state.start;
    while (this.state.pos < this.state.lineStart) {
      this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
      --this.state.curLine;
    }
    this.nextToken();
  }

  curContext() {
    return this.state.context[this.state.context.length - 1];
  }

  // Read a single token, updating the parser object's token-related
  // properties.

  nextToken() {
    let curContext = this.curContext();
    if (!curContext || !curContext.preserveSpace) this.skipSpace();

    this.state.containsOctal = false;
    this.state.octalPosition = null;
    this.state.start = this.state.pos;
    this.state.startLoc = this.state.curPosition();
    if (this.state.pos >= this.input.length) return this.finishToken(tt.eof);

    if (curContext.override) {
      return curContext.override(this);
    } else {
      return this.readToken(this.fullCharCodeAtPos());
    }
  }

  readToken(code) {
    // Identifier or keyword. '\uXXXX' sequences are allowed in
    // identifiers, so '\' also dispatches to that.
    if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
      return this.readWord();
    } else {
      return this.getTokenFromCode(code);
    }
  }

  fullCharCodeAtPos() {
    let code = this.input.charCodeAt(this.state.pos);
    if (code <= 0xd7ff || code >= 0xe000) return code;

    let next = this.input.charCodeAt(this.state.pos + 1);
    return (code << 10) + next - 0x35fdc00;
  }

  pushComment(block, text, start, end, startLoc, endLoc) {
    let comment = {
      type: block ? "CommentBlock" : "CommentLine",
      value: text,
      start: start,
      end: end,
      loc: new SourceLocation(startLoc, endLoc)
    };

    if (!this.isLookahead) {
      this.state.tokens.push(comment);
      this.state.comments.push(comment);
    }

    this.addComment(comment);
  }

  skipBlockComment() {
    let startLoc = this.state.curPosition();
    let start = this.state.pos, end = this.input.indexOf("*/", this.state.pos += 2);
    if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment");

    this.state.pos = end + 2;
    lineBreakG.lastIndex = start;
    let match;
    while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
      ++this.state.curLine;
      this.state.lineStart = match.index + match[0].length;
    }

    this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  }

  skipLineComment(startSkip) {
    let start = this.state.pos;
    let startLoc = this.state.curPosition();
    let ch = this.input.charCodeAt(this.state.pos += startSkip);
    while (this.state.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
      ++this.state.pos;
      ch = this.input.charCodeAt(this.state.pos);
    }

    this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  }

  // Called at the start of the parse and after every token. Skips
  // whitespace and comments, and.

  skipSpace() {
    loop: while (this.state.pos < this.input.length) {
      let ch = this.input.charCodeAt(this.state.pos);
      switch (ch) {
        case 32: case 160: // ' '
          ++this.state.pos;
          break;

        case 13:
          if (this.input.charCodeAt(this.state.pos + 1) === 10) {
            ++this.state.pos;
          }

        case 10: case 8232: case 8233:
          ++this.state.pos;
          ++this.state.curLine;
          this.state.lineStart = this.state.pos;
          break;

        case 47: // '/'
          switch (this.input.charCodeAt(this.state.pos + 1)) {
            case 42: // '*'
              this.skipBlockComment();
              break;

            case 47:
              this.skipLineComment(2);
              break;

            default:
              break loop;
          }
          break;

        default:
          if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
            ++this.state.pos;
          } else {
            break loop;
          }
      }
    }
  }

  // Called at the end of every token. Sets `end`, `val`, and
  // maintains `context` and `exprAllowed`, and skips the space after
  // the token, so that the next one's `start` will point at the
  // right position.

  finishToken(type, val) {
    this.state.end = this.state.pos;
    this.state.endLoc = this.state.curPosition();
    let prevType = this.state.type;
    this.state.type = type;
    this.state.value = val;

    this.updateContext(prevType);
  }

  // ### Token reading

  // This is the function that is called to fetch the next token. It
  // is somewhat obscure, because it works in character codes rather
  // than characters, and because operator parsing has been inlined
  // into it.
  //
  // All in the name of speed.
  //
  readToken_dot() {
    let next = this.input.charCodeAt(this.state.pos + 1);
    if (next >= 48 && next <= 57) {
      return this.readNumber(true);
    }

    let next2 = this.input.charCodeAt(this.state.pos + 2);
    if (next === 46 && next2 === 46) { // 46 = dot '.'
      this.state.pos += 3;
      return this.finishToken(tt.ellipsis);
    } else {
      ++this.state.pos;
      return this.finishToken(tt.dot);
    }
  }

  readToken_slash() { // '/'
    if (this.state.exprAllowed) {
      ++this.state.pos;
      return this.readRegexp();
    }

    let next = this.input.charCodeAt(this.state.pos + 1);
    if (next === 61) {
      return this.finishOp(tt.assign, 2);
    } else {
      return this.finishOp(tt.slash, 1);
    }
  }

  readToken_mult_modulo(code) { // '%*'
    let type = code === 42 ? tt.star : tt.modulo;
    let width = 1;
    let next = this.input.charCodeAt(this.state.pos + 1);

    if (next === 42 && this.hasPlugin("exponentiationOperator")) { // '*'
      width++;
      next = this.input.charCodeAt(this.state.pos + 2);
      type = tt.exponent;
    }

    if (next === 61) {
      width++;
      type = tt.assign;
    }

    return this.finishOp(type, width);
  }

  readToken_pipe_amp(code) { // '|&'
    let next = this.input.charCodeAt(this.state.pos + 1);
    if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2);
    if (next === 61) return this.finishOp(tt.assign, 2);
    return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1);
  }

  readToken_caret() { // '^'
    let next = this.input.charCodeAt(this.state.pos + 1);
    if (next === 61) {
      return this.finishOp(tt.assign, 2);
    } else {
      return this.finishOp(tt.bitwiseXOR, 1);
    }
  }

  readToken_plus_min(code) { // '+-'
    let next = this.input.charCodeAt(this.state.pos + 1);

    if (next === code) {
      if (next === 45 && this.input.charCodeAt(this.state.pos + 2) === 62 && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) {
        // A `-->` line comment
        this.skipLineComment(3);
        this.skipSpace();
        return this.nextToken();
      }
      return this.finishOp(tt.incDec, 2);
    }

    if (next === 61) {
      return this.finishOp(tt.assign, 2);
    } else {
      return this.finishOp(tt.plusMin, 1);
    }
  }

  readToken_lt_gt(code) { // '<>'
    let next = this.input.charCodeAt(this.state.pos + 1);
    let size = 1;

    if (next === code) {
      size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
      if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(tt.assign, size + 1);
      return this.finishOp(tt.bitShift, size);
    }

    if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
      if (this.inModule) this.unexpected();
      // `<!--`, an XML-style comment that should be interpreted as a line comment
      this.skipLineComment(4);
      this.skipSpace();
      return this.nextToken();
    }

    if (next === 61) {
      size = this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2;
    }

    return this.finishOp(tt.relational, size);
  }

  readToken_eq_excl(code) { // '=!'
    let next = this.input.charCodeAt(this.state.pos + 1);
    if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
    if (code === 61 && next === 62) { // '=>'
      this.state.pos += 2;
      return this.finishToken(tt.arrow);
    }
    return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1);
  }

  getTokenFromCode(code) {
    switch (code) {
      // The interpretation of a dot depends on whether it is followed
      // by a digit or another two dots.
      case 46: // '.'
        return this.readToken_dot();

      // Punctuation tokens.
      case 40: ++this.state.pos; return this.finishToken(tt.parenL);
      case 41: ++this.state.pos; return this.finishToken(tt.parenR);
      case 59: ++this.state.pos; return this.finishToken(tt.semi);
      case 44: ++this.state.pos; return this.finishToken(tt.comma);
      case 91: ++this.state.pos; return this.finishToken(tt.bracketL);
      case 93: ++this.state.pos; return this.finishToken(tt.bracketR);
      case 123: ++this.state.pos; return this.finishToken(tt.braceL);
      case 125: ++this.state.pos; return this.finishToken(tt.braceR);

      case 58:
        if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
          return this.finishOp(tt.doubleColon, 2);
        } else {
          ++this.state.pos;
          return this.finishToken(tt.colon);
        }

      case 63: ++this.state.pos; return this.finishToken(tt.question);
      case 64: ++this.state.pos; return this.finishToken(tt.at);

      case 96: // '`'
        ++this.state.pos;
        return this.finishToken(tt.backQuote);

      case 48: // '0'
        let next = this.input.charCodeAt(this.state.pos + 1);
        if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
        if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
        if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
        // Anything else beginning with a digit is an integer, octal
        // number, or float.
      case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
        return this.readNumber(false);

        // Quotes produce strings.
      case 34: case 39: // '"', "'"
        return this.readString(code);

      // Operators are parsed inline in tiny state machines. '=' (61) is
      // often referred to. `finishOp` simply skips the amount of
      // characters it is given as second argument, and returns a token
      // of the type given by its first argument.

      case 47: // '/'
        return this.readToken_slash();

      case 37: case 42: // '%*'
        return this.readToken_mult_modulo(code);

      case 124: case 38: // '|&'
        return this.readToken_pipe_amp(code);

      case 94: // '^'
        return this.readToken_caret();

      case 43: case 45: // '+-'
        return this.readToken_plus_min(code);

      case 60: case 62: // '<>'
        return this.readToken_lt_gt(code);

      case 61: case 33: // '=!'
        return this.readToken_eq_excl(code);

      case 126: // '~'
        return this.finishOp(tt.prefix, 1);
    }

    this.raise(this.state.pos, `Unexpected character '${codePointToString(code)}'`);
  }

  finishOp(type, size) {
    let str = this.input.slice(this.state.pos, this.state.pos + size);
    this.state.pos += size;
    return this.finishToken(type, str);
  }

  readRegexp() {
    let escaped, inClass, start = this.state.pos;
    for (;;) {
      if (this.state.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
      let ch = this.input.charAt(this.state.pos);
      if (lineBreak.test(ch)) {
        this.raise(start, "Unterminated regular expression");
      }
      if (escaped) {
        escaped = false;
      } else {
        if (ch === "[") {
          inClass = true;
        } else if (ch === "]" && inClass) {
          inClass = false;
        } else if (ch === "/" && !inClass) {
          break;
        }
        escaped = ch === "\\";
      }
      ++this.state.pos;
    }
    let content = this.input.slice(start, this.state.pos);
    ++this.state.pos;
    // Need to use `readWord1` because '\uXXXX' sequences are allowed
    // here (don't ask).
    let mods = this.readWord1();
    if (mods) {
      let validFlags = /^[gmsiyu]*$/;
      if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
    }
    return this.finishToken(tt.regexp, {
      pattern: content,
      flags: mods
    });
  }

  // Read an integer in the given radix. Return null if zero digits
  // were read, the integer value otherwise. When `len` is given, this
  // will return `null` unless the integer has exactly `len` digits.

  readInt(radix, len) {
    let start = this.state.pos, total = 0;
    for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
      let code = this.input.charCodeAt(this.state.pos), val;
      if (code >= 97) {
        val = code - 97 + 10; // a
      } else if (code >= 65) {
        val = code - 65 + 10; // A
      } else if (code >= 48 && code <= 57) {
        val = code - 48; // 0-9
      } else  {
        val = Infinity;
      }
      if (val >= radix) break;
      ++this.state.pos;
      total = total * radix + val;
    }
    if (this.state.pos === start || len != null && this.state.pos - start !== len) return null;

    return total;
  }

  readRadixNumber(radix) {
    this.state.pos += 2; // 0x
    let val = this.readInt(radix);
    if (val == null) this.raise(this.state.start + 2, "Expected number in radix " + radix);
    if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.state.pos, "Identifier directly after number");
    return this.finishToken(tt.num, val);
  }

  // Read an integer, octal integer, or floating-point number.

  readNumber(startsWithDot) {
    let start = this.state.pos, isFloat = false, octal = this.input.charCodeAt(this.state.pos) === 48;
    if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
    let next = this.input.charCodeAt(this.state.pos);
    if (next === 46) { // '.'
      ++this.state.pos;
      this.readInt(10);
      isFloat = true;
      next = this.input.charCodeAt(this.state.pos);
    }
    if (next === 69 || next === 101) { // 'eE'
      next = this.input.charCodeAt(++this.state.pos);
      if (next === 43 || next === 45) ++this.state.pos; // '+-'
      if (this.readInt(10) === null) this.raise(start, "Invalid number");
      isFloat = true;
    }
    if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.state.pos, "Identifier directly after number");

    let str = this.input.slice(start, this.state.pos), val;
    if (isFloat) {
      val = parseFloat(str);
    } else if (!octal || str.length === 1) {
      val = parseInt(str, 10);
    } else if (/[89]/.test(str) || this.state.strict) {
      this.raise(start, "Invalid number");
    } else {
      val = parseInt(str, 8);
    }
    return this.finishToken(tt.num, val);
  }

  // Read a string value, interpreting backslash-escapes.

  readCodePoint() {
    let ch = this.input.charCodeAt(this.state.pos), code;

    if (ch === 123) {
      let codePos = ++this.state.pos;
      code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos);
      ++this.state.pos;
      if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds");
    } else {
      code = this.readHexChar(4);
    }
    return code;
  }

  readString(quote) {
    let out = "", chunkStart = ++this.state.pos;
    for (;;) {
      if (this.state.pos >= this.input.length) this.raise(this.state.start, "Unterminated string constant");
      let ch = this.input.charCodeAt(this.state.pos);
      if (ch === quote) break;
      if (ch === 92) { // '\'
        out += this.input.slice(chunkStart, this.state.pos);
        out += this.readEscapedChar(false);
        chunkStart = this.state.pos;
      } else {
        if (isNewLine(ch)) this.raise(this.state.start, "Unterminated string constant");
        ++this.state.pos;
      }
    }
    out += this.input.slice(chunkStart, this.state.pos++);
    return this.finishToken(tt.string, out);
  }

  // Reads template string tokens.

  readTmplToken() {
    let out = "", chunkStart = this.state.pos;
    for (;;) {
      if (this.state.pos >= this.input.length) this.raise(this.state.start, "Unterminated template");
      let ch = this.input.charCodeAt(this.state.pos);
      if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) { // '`', '${'
        if (this.state.pos === this.state.start && this.match(tt.template)) {
          if (ch === 36) {
            this.state.pos += 2;
            return this.finishToken(tt.dollarBraceL);
          } else {
            ++this.state.pos;
            return this.finishToken(tt.backQuote);
          }
        }
        out += this.input.slice(chunkStart, this.state.pos);
        return this.finishToken(tt.template, out);
      }
      if (ch === 92) { // '\'
        out += this.input.slice(chunkStart, this.state.pos);
        out += this.readEscapedChar(true);
        chunkStart = this.state.pos;
      } else if (isNewLine(ch)) {
        out += this.input.slice(chunkStart, this.state.pos);
        ++this.state.pos;
        switch (ch) {
          case 13:
            if (this.input.charCodeAt(this.state.pos) === 10) ++this.state.pos;
          case 10:
            out += "\n";
            break;
          default:
            out += String.fromCharCode(ch);
            break;
        }
        ++this.state.curLine;
        this.state.lineStart = this.state.pos;
        chunkStart = this.state.pos;
      } else {
        ++this.state.pos;
      }
    }
  }

  // Used to read escaped characters

  readEscapedChar(inTemplate) {
    let ch = this.input.charCodeAt(++this.state.pos);
    ++this.state.pos;
    switch (ch) {
      case 110: return "\n"; // 'n' -> '\n'
      case 114: return "\r"; // 'r' -> '\r'
      case 120: return String.fromCharCode(this.readHexChar(2)); // 'x'
      case 117: return codePointToString(this.readCodePoint()); // 'u'
      case 116: return "\t"; // 't' -> '\t'
      case 98: return "\b"; // 'b' -> '\b'
      case 118: return "\u000b"; // 'v' -> '\u000b'
      case 102: return "\f"; // 'f' -> '\f'
      case 13: if (this.input.charCodeAt(this.state.pos) === 10) ++this.state.pos; // '\r\n'
      case 10: // ' \n'
        this.state.lineStart = this.state.pos;
        ++this.state.curLine;
        return "";
      default:
        if (ch >= 48 && ch <= 55) {
          let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
          let octal = parseInt(octalStr, 8);
          if (octal > 255) {
            octalStr = octalStr.slice(0, -1);
            octal = parseInt(octalStr, 8);
          }
          if (octal > 0) {
            if (!this.state.containsOctal) {
              this.state.containsOctal = true;
              this.state.octalPosition = this.state.pos - 2;
            }
            if (this.state.strict || inTemplate) {
              this.raise(this.state.pos - 2, "Octal literal in strict mode");
            }
          }
          this.state.pos += octalStr.length - 1;
          return String.fromCharCode(octal);
        }
        return String.fromCharCode(ch);
    }
  }

  // Used to read character escape sequences ('\x', '\u', '\U').

  readHexChar(len) {
    let codePos = this.state.pos;
    let n = this.readInt(16, len);
    if (n === null) this.raise(codePos, "Bad character escape sequence");
    return n;
  }

  // Read an identifier, and return it as a string. Sets `this.state.containsEsc`
  // to whether the word contained a '\u' escape.
  //
  // Incrementally adds only escaped chars, adding other chunks as-is
  // as a micro-optimization.

  readWord1() {
    this.state.containsEsc = false;
    let word = "", first = true, chunkStart = this.state.pos;
    while (this.state.pos < this.input.length) {
      let ch = this.fullCharCodeAtPos();
      if (isIdentifierChar(ch, true)) {
        this.state.pos += ch <= 0xffff ? 1 : 2;
      } else if (ch === 92) { // "\"
        this.state.containsEsc = true;

        word += this.input.slice(chunkStart, this.state.pos);
        let escStart = this.state.pos;

        if (this.input.charCodeAt(++this.state.pos) !== 117) { // "u"
          this.raise(this.state.pos, "Expecting Unicode escape sequence \\uXXXX");
        }

        ++this.state.pos;
        let esc = this.readCodePoint();
        if (!(first ? isIdentifierStart : isIdentifierChar)(esc, true)) {
          this.raise(escStart, "Invalid Unicode escape");
        }

        word += codePointToString(esc);
        chunkStart = this.state.pos;
      } else {
        break;
      }
      first = false;
    }
    return word + this.input.slice(chunkStart, this.state.pos);
  }

  // Read an identifier or keyword token. Will check for reserved
  // words when necessary.

  readWord() {
    let word = this.readWord1();
    let type = tt.name;
    if (!this.state.containsEsc && this.isKeyword(word)) {
      type = keywordTypes[word];
    }
    return this.finishToken(type, word);
  }

  braceIsBlock(prevType) {
    if (prevType === tt.colon) {
      let parent = this.curContext();
      if (parent === ct.b_stat || parent === ct.b_expr) {
        return !parent.isExpr;
      }
    }

    if (prevType === tt._return) {
      return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
    }

    if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) {
      return true;
    }

    if (prevType === tt.braceL) {
      return this.curContext() === ct.b_stat;
    }

    return !this.state.exprAllowed;
  }

  updateContext(prevType) {
    let update, type = this.state.type;
    if (type.keyword && prevType === tt.dot) {
      this.state.exprAllowed = false;
    } else if (update = type.updateContext) {
      update.call(this, prevType);
    } else {
      this.state.exprAllowed = type.beforeExpr;
    }
  }
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "K2Node_Tunnel.h"
#include "EdGraph/EdGraphNodeUtils.h" // for FNodeTextCache
#include "K2Node_Composite.generated.h"

UCLASS(MinimalAPI)
class UK2Node_Composite : public UK2Node_Tunnel
{
	GENERATED_UCLASS_BODY()

	// The graph that this composite node is representing
	UPROPERTY()
	class UEdGraph* BoundGraph;

	// Begin UEdGraphNode interface
	BLUEPRINTGRAPH_API virtual void AllocateDefaultPins() override;
	BLUEPRINTGRAPH_API virtual void DestroyNode() override;
	BLUEPRINTGRAPH_API virtual void PostPasteNode() override;
	BLUEPRINTGRAPH_API virtual FText GetTooltipText() const override;
	BLUEPRINTGRAPH_API virtual FLinearColor GetNodeTitleColor() const override;
	BLUEPRINTGRAPH_API virtual FText GetNodeTitle(ENodeTitleType::Type TitleType) const override;
	BLUEPRINTGRAPH_API virtual bool CanUserDeleteNode() const override;
	BLUEPRINTGRAPH_API virtual UObject* GetJumpTargetForDoubleClick() const override;
	BLUEPRINTGRAPH_API virtual void PostPlacedNewNode() override;
	virtual void OnRenameNode(const FString& NewName) override;
	virtual TSharedPtr<class INameValidatorInterface> MakeNameValidator() const override;
	// End UEdGraphNode interface

	// Begin UK2Node interface
	virtual bool DrawNodeAsExit() const override { return false; }
	virtual bool DrawNodeAsEntry() const override { return false; }
	virtual bool NodeCausesStructuralBlueprintChange() const override { return true; }
	// End UK2Node interface

	// Get the entry/exit nodes inside this collapsed graph
	BLUEPRINTGRAPH_API UK2Node_Tunnel* GetEntryNode() const;
	BLUEPRINTGRAPH_API UK2Node_Tunnel* GetExitNode() const;

private:
	/** Rename the BoundGraph to a unique name
		- this is a special case rename: RenameGraphCloseToName() assumes that we are only concurrned with the immediate Outer() scope,
		  but in the case of the BoundGraph we must also look into the Outer of the composite node(a Graph), and make sure no graphs in its SubGraph
		  array are already using the name.  */
	void RenameBoundGraphCloseToName(const FString& Name);

	/** Determine if the name already used by another graph in composite nodes chain */
	bool IsCompositeNameAvailable( const FString& NewName );

	/** Constructing FText strings can be costly, so we cache the node's title */
	FNodeTextCache CachedNodeTitle;
};

redpajama_set_name: RedPajamaGithub


text:
package com.cndsteel.info.bean;

import com.cndsteel.framework.bean.BaseBean;

public class InfoBean extends BaseBean {

	private static final long serialVersionUID = -4492597898273360023L;

	/** 咨询ID **/
	public String msgId;

	/** 标题 **/
	public String title;

	/** 资讯内容 **/
	public String content;

	/** 资讯类别 **/
	public String cateName;

	/** 评论数 **/
	public String replyCount;

	/** 作者 **/
	public String author;

	/** 日期 **/
	public String date;
}


text:
Packages in Tavern are defined using a language called KEGFILE. This is a metalanguage that makes it simple to define both information about a package, as well as installation instructions in a platform agnostic manner.

## Fields
Each package has a set of information about it, each of these values is called a field. These fields are:

* Name - the name of the package
* Author - the name and contact details of the author
* Version - version of the package
* License - the licence of the code
* (optional) Manpage - a documentation page
* (optional) Homepage - a homepage for the package/project

To set these fields (note that comments can be defined by placing a `;` at the beginning of the line:

``` shell
; a comment
name = <package_name>
author = <author_name> <author_email>
version = <version_number>
license = <license_name>s
manpage = <manpage_link>
homepage = <homepage_link>
```

## Commands

Commands are defined in blocks, which are delimted by parentheses. There are 9 commands to use:

1. `$remove <string:path>` removes the file or directory given
2. `$copy <string:from> <string:to>` copies the file, or contents of a directory in 'from' into 'to'
3. `$move <string:from> <string:to>` identical to copy, except it removes the 'from' directory after copying
4. `$download <string:url> <string:dest>` downloads a file from the given url into the specified path
5. `$exec <string:command>` executes the command, should be used carefully as it breaks platform independance normally
6. `$gitclone <string:url> <string:dest>` clones a git repo into the given folder
7. `$gitclean <string:path>` removes the `.git` and `.gitignore` files from a cloned repo
8. `$link <string:file> <number:argc> <string:executor>` creates an executable script in the Everware binary folder that allows a script to be executed from the command line. The command will be the `name` field from your package. The argc is the number of arguments from the command line your program expects. The executor is the program calling your script.
9. `$unlink <string:name>` unlink your package from the Everware binary folder.

There are also some special variables you can use in the arguments to access the filesystem much more easily across operating systems.

1. `$(HOME)` is the home directory, `~/` on Unix and OSX and generally the `C:` on Windows.
2. `$(EVERWARE)` is the Everware directory, `~/everwareio` on Unix and OSX and `C:/EverwareIO` on Windows.
3. `$(PACKAGE)` is the path to your package in the Tavern Storeroom.

There are two blocks that must be present in your package for it to be valid. These are `install` and `uninstall`. They can be defined as below:

``` shell
install = (
    ; clone the git repo into the package directory
    $gitclone https://github.com/some_example_repo.git $(PACKAGE)/src

    ; clean up the repo
    $gitclean $(PACKAGE)/src

    ; create an executable link
    $link $(PACKAGE)/src/some_script_to_execute.rb 3 ruby
)

uninstall = (
    ; remove the package
    $remove $(PACKAGE)

    ; unlink the script
    $unlink the_package_name
)
```

## Naming the Keg

Convention: Name the file `<package_name>.keg`. This makes it way easier to install from a library, trust me. Everything else is up to you.


text:
import { createHash } from "crypto";
import { buffer as getStreamBuffer } from "get-stream";
import * as through2 from "through2";

import { createIntegrity } from "../lib/utils";

import {
	Body,
	DataBody,
	JsonBody,
	StreamBody,
} from "../../index";

async function makeSync< T >( fn: ( ) => PromiseLike< T > )
: Promise< ( ) => T >
{
	try
	{
		const val = await fn( );
		return ( ) => val;
	}
	catch ( err )
	{
		return ( ) => { throw err; };
	}
}

function setHash( body: any, data: string, hashType = "sha256" )
{
	body._integrity = createIntegrity( data, hashType );
}

class IntegrityBody extends Body
{
	constructor(
		data: string | Buffer | NodeJS.ReadableStream | null,
		hashData: string,
		integrityHashType = "sha256"
	)
	{
		super( );

		const hash = createHash( "sha256" );
		hash.update( hashData );
		const v = integrityHashType + "-" + hash.digest( "base64" );

		this.setBody( data, null, v );
	}
}

describe( "body", ( ) =>
{
	describe( "multiple reads", ( ) =>
	{
		it( "throw on multiple reads", async ( ) =>
		{
			const body = new DataBody( "foo" );
			expect( body.bodyUsed ).toBe( false );
			expect( await body.text( ) ).toBe( "foo" );
			expect( body.bodyUsed ).toBe( true );
			expect( await makeSync( ( ) => body.text( ) ) )
				.toThrow( ReferenceError );
		} );
	} );

	describe( "unimplemented", ( ) =>
	{
		it( "throw on unimplemented blob()", async ( ) =>
		{
			const body = new DataBody( "foo" );
			expect( await makeSync( ( ) => ( < any >body ).blob( ) ) )
				.toThrow( );
		} );

		it( "throw on unimplemented formData()", async ( ) =>
		{
			const body = new DataBody( "foo" );
			expect( await makeSync( ( ) => body.formData( ) ) ).toThrow( );
		} );
	} );

	describe( "invalid data", ( ) =>
	{
		it( "handle invalid body type when reading as arrayBuffer",
			async ( ) =>
		{
			const body = new DataBody( < string >< any >1 );
			expect( await makeSync( ( ) => body.arrayBuffer( ) ) )
				.toThrow( "Unknown body data" );
		} );

		it( "handle invalid body type when reading as json", async ( ) =>
		{
			const body = new DataBody( < string >< any >1 );
			expect( await makeSync( ( ) => body.json( ) ) )
				.toThrow( "Unknown body data" );
		} );

		it( "handle invalid body type when reading as text", async ( ) =>
		{
			const body = new DataBody( < string >< any >1 );
			expect( await makeSync( ( ) => body.text( ) ) )
				.toThrow( "Unknown body data" );
		} );

		it( "handle invalid body type when reading as readable", async ( ) =>
		{
			const body = new DataBody( < string >< any >1 );
			expect( await makeSync( ( ) => body.readable( ) ) )
				.toThrow( "Unknown body data" );
		} );
	} );

	describe( "arrayBuffer", ( ) =>
	{
		describe( "without validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new DataBody( null );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( "" );
			} );

			it( "handle string", async ( ) =>
			{
				const body = new DataBody( "foo" );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( "foo" );
			} );

			it( "handle buffer", async ( ) =>
			{
				const body = new DataBody( Buffer.from( "foo" ) );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( "foo" );
			} );

			it( "handle JsonBody", async ( ) =>
			{
				const body = new JsonBody( { foo: "bar" } );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( '{"foo":"bar"}' );
			} );

			it( "handle stream", async ( ) =>
			{
				const stream = through2( );
				stream.end( "foo" );
				const body = new StreamBody( stream );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( "foo" );
			} );
		} );

		describe( "matching validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new IntegrityBody( null, "" );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( "" );
			} );

			it( "handle string", async ( ) =>
			{
				const testData = "foo";
				const body = new IntegrityBody( testData, testData );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( testData );
			} );

			it( "handle buffer", async ( ) =>
			{
				const testData = "foo";
				const body = new IntegrityBody(
					Buffer.from( testData ), testData );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( testData );
			} );

			it( "handle stream", async ( ) =>
			{
				const testData = "foo";
				const stream = through2( );
				stream.end( testData );
				const body = new IntegrityBody( stream, testData );
				const data = Buffer.from( await body.arrayBuffer( ) );
				expect( data.toString( ) ).toBe( testData );
			} );
		} );

		describe( "mismatching validation", ( ) =>
		{
			it( "handle invalid hash type", async ( ) =>
			{
				const body = new IntegrityBody( null, "", "acme-hash" );
				expect( await makeSync( ( ) => body.arrayBuffer( ) ) )
					.toThrow( "not supported" );
			} );

			it( "handle null", async ( ) =>
			{
				const body = new IntegrityBody( null, "" + "x" );
				expect( await makeSync( ( ) => body.arrayBuffer( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle string", async ( ) =>
			{
				const testData = "foo";
				const body = new IntegrityBody( testData, testData + "x" );
				expect( await makeSync( ( ) => body.arrayBuffer( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle buffer", async ( ) =>
			{
				const testData = "foo";
				const body = new IntegrityBody(
					Buffer.from( testData ), testData + "x" );
				expect( await makeSync( ( ) => body.arrayBuffer( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle stream", async ( ) =>
			{
				const testData = "foo";
				const stream = through2( );
				stream.end( testData );
				const body = new IntegrityBody( stream, testData + "x" );
				expect( await makeSync( ( ) => body.arrayBuffer( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );
		} );
	} );

	describe( "json", ( ) =>
	{
		describe( "without validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new DataBody( null );
				expect( await body.json( ) ).toBe( null );
			} );

			it( "handle invalid string", async ( ) =>
			{
				const body = new DataBody( "invalid json" );
				expect( await makeSync( ( ) => body.json( ) ) ).toThrow( );
			} );

			it( "handle valid string", async ( ) =>
			{
				const body = new DataBody( '{"foo":"bar"}' );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );

			it( "handle invalid buffer", async ( ) =>
			{
				const body = new DataBody( Buffer.from( "invalid json" ) );
				expect( await makeSync( ( ) => body.json( ) ) ).toThrow( );
			} );

			it( "handle valid buffer", async ( ) =>
			{
				const body = new DataBody( Buffer.from( '{"foo":"bar"}' ) );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );

			it( "handle valid JsonBody", async ( ) =>
			{
				const body = new JsonBody( { foo: "bar" } );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );

			it( "handle invalid stream", async ( ) =>
			{
				const stream = through2( );
				stream.end( "invalid json" );
				const body = new StreamBody( stream );
				expect( await makeSync( ( ) => body.json( ) ) ).toThrow( );
			} );

			it( "handle valid stream", async ( ) =>
			{
				const stream = through2( );
				stream.end( '{"foo":"bar"}' );
				const body = new StreamBody( stream );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );
		} );

		describe( "matching validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new DataBody( null );
				setHash( body, "" );
				expect( await body.json( ) ).toBe( null );
			} );

			it( "handle string", async ( ) =>
			{
				const testData = '{"foo":"bar"}';
				const body = new DataBody( testData );
				setHash( body, testData );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );

			it( "handle buffer", async ( ) =>
			{
				const testData = '{"foo":"bar"}';
				const body = new DataBody( Buffer.from( testData ) );
				setHash( body, testData );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );

			it( "handle JsonBody", async ( ) =>
			{
				const body = new JsonBody( { foo: "bar" } );
				setHash( body, '{"foo":"bar"}' );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );

			it( "handle stream", async ( ) =>
			{
				const testData = '{"foo":"bar"}';
				const stream = through2( );
				stream.end( testData );
				const body = new StreamBody( stream );
				setHash( body, testData );
				expect( await body.json( ) ).toEqual( { foo: "bar" } );
			} );
		} );

		describe( "mismatching validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new DataBody( null );
				setHash( body, "" + "x" );
				expect( await makeSync( ( ) => body.json( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle string", async ( ) =>
			{
				const testData = '{"foo":"bar"}';
				const body = new DataBody( testData );
				setHash( body, testData + "x" );
				expect( await makeSync( ( ) => body.json( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle buffer", async ( ) =>
			{
				const testData = '{"foo":"bar"}';
				const body = new DataBody( Buffer.from( testData ) );
				setHash( body, testData + "x" );
				expect( await makeSync( ( ) => body.json( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle JsonBody", async ( ) =>
			{
				const body = new JsonBody( { foo: "bar" } );
				setHash( body, '{"foo":"bar"}' + "x" );
				expect( await makeSync( ( ) => body.json( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle stream", async ( ) =>
			{
				const testData = '{"foo":"bar"}';
				const stream = through2( );
				stream.end( testData );
				const body = new StreamBody( stream );
				setHash( body, testData + "x" );
				expect( await makeSync( ( ) => body.json( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );
		} );
	} );

	describe( "text", ( ) =>
	{
		describe( "without validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new DataBody( null );
				expect( await body.text( ) ).toBe( null );
			} );

			it( "handle string", async ( ) =>
			{
				const body = new DataBody( "foo" );
				expect( await body.text( ) ).toBe( "foo" );
			} );

			it( "handle buffer", async ( ) =>
			{
				const body = new DataBody( Buffer.from( "foo" ) );
				expect( await body.text( ) ).toBe( "foo" );
			} );

			it( "handle stream", async ( ) =>
			{
				const stream = through2( );
				stream.end( "foo" );
				const body = new StreamBody( stream );
				expect( await body.text( ) ).toBe( "foo" );
			} );
		} );

		describe( "matching validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new DataBody( null );
				setHash( body, "" );
				expect( await body.text( ) ).toBe( null );
			} );

			it( "handle string", async ( ) =>
			{
				const testData = "foo";
				const body = new DataBody( testData );
				setHash( body, testData );
				expect( await body.text( ) ).toBe( testData );
			} );

			it( "handle buffer", async ( ) =>
			{
				const testData = "foo";
				const body = new DataBody( Buffer.from( testData ) );
				setHash( body, testData );
				expect( await body.text( ) ).toBe( testData );
			} );

			it( "handle stream", async ( ) =>
			{
				const testData = "foo";
				const stream = through2( );
				stream.end( testData );
				const body = new StreamBody( stream );
				setHash( body, testData );
				expect( await body.text( ) ).toBe( testData );
			} );
		} );

		describe( "mismatching validation", ( ) =>
		{
			it( "handle null", async ( ) =>
			{
				const body = new DataBody( null );
				setHash( body, "" + "x" );
				expect( await makeSync( ( ) => body.text( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle string", async ( ) =>
			{
				const testData = "foo";
				const body = new DataBody( testData );
				setHash( body, testData + "x" );
				expect( await makeSync( ( ) => body.text( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle buffer", async ( ) =>
			{
				const testData = "foo";
				const body = new DataBody( Buffer.from( testData ) );
				setHash( body, testData + "x" );
				expect( await makeSync( ( ) => body.text( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );

			it( "handle stream", async ( ) =>
			{
				const testData = "foo";
				const stream = through2( );
				stream.end( testData );
				const body = new StreamBody( stream );
				setHash( body, testData + "x" );
				expect( await makeSync( ( ) => body.text( ) ) )
					.toThrow( "Resource integrity mismatch" );
			} );
		} );
	} );

	describe( "readable", ( ) =>
	{
		it( "handle null", async ( ) =>
		{
			const body = new DataBody( null );
			const data = await getStreamBuffer( await body.readable( ) );
			expect( data.toString( ) ).toBe( "" );
		} );

		it( "handle string", async ( ) =>
		{
			const body = new DataBody( "foo" );
			const data = await getStreamBuffer( await body.readable( ) );
			expect( data.toString( ) ).toBe( "foo" );
		} );

		it( "handle buffer", async ( ) =>
		{
			const body = new DataBody( Buffer.from( "foo" ) );
			const data = await getStreamBuffer( await body.readable( ) );
			expect( data.toString( ) ).toBe( "foo" );
		} );

		it( "handle stream", async ( ) =>
		{
			const stream = through2( );
			stream.end( "foo" );
			const body = new StreamBody( stream );
			const data = await getStreamBuffer( await body.readable( ) );
			expect( data.toString( ) ).toBe( "foo" );
		} );
	} );
} );


text:
namespace KA.ObjectComparator
{
    public class Validate
    {
        public static void NotNull(object obj, string msg = @"Object must not be null.")
        {
            if (obj == null)
            {
                throw new ObjectComparatorException(msg);
            }
        }
    }
}


text:
import sys
import os
import signal

# From https://blog.zhaw.ch/icclab/process-management-in-docker-containers/

def write_stdout(s):
   sys.stdout.write(s)
   sys.stdout.flush()
def write_stderr(s):
   sys.stderr.write(s)
   sys.stderr.flush()
def main():
   while 1:
       write_stdout('READY\n')
       line = sys.stdin.readline()
       write_stdout('This line kills supervisor: ' + line)
       try:
               pidfile = open('/var/run/supervisord.pid','r')
               pid = int(pidfile.readline())
               os.kill(pid, signal.SIGQUIT)
       except Exception as e:
               write_stdout('Could not kill supervisor: ' + e.strerror + '\n')
       write_stdout('RESULT 2\nOK')
if __name__ == '__main__':
   main()
   import sys


text:
DOCUMENTATION = """
module: gluster_volume
short_description: Manage GlusterFS volumes
description:
  - Create, remove, start, stop and tune GlusterFS volumes
version_added: "1.9"
options:
  name:
    required: true
    description:
      - The volume name
  state:
    required: true
    choices: [ 'present', 'absent', 'started', 'stopped' ]
    description:
      - Use present/absent ensure if a volume exists or not,
        use started/stopped to control it's availability.
  cluster:
    required: false
    description:
      - List of hosts to use for probing and brick setup
  host:
    required: false
    description:
      - Override local hostname (for peer probing purposes)
  replicas:
    required: false
    description:
      - Replica count for volume
  stripes:
    required: false
    description:
      - Stripe count for volume
  transport:
    required: false
    choices: [ 'tcp', 'rdma', 'tcp,rdma' ]
    description:
      - Transport type for volume
  brick:
    required: false
    description:
      - Brick path on servers
  start_on_create:
    choices: [ 'yes', 'no']
    required: false
    description:
      - Controls whether the volume is started after creation or not, defaults to yes
  rebalance:
    choices: [ 'yes', 'no']
    required: false
    description:
      - Controls whether the cluster is rebalanced after changes
  directory:
    required: false
    description:
      - Directory for limit-usage
  options:
    required: false
    description:
      - A dictionary/hash with options/settings for the volume
  quota:
    required: false
    description:
      - Quota value for limit-usage (be sure to use 10.0MB instead of 10MB, see quota list)
notes:
  - "Requires cli tools for GlusterFS on servers"
  - "Will add new bricks, but not remove them"
author: Taneli Leppä
"""

EXAMPLES = """
- name: create gluster volume
  gluster_volume: state=present name=test1 brick=/bricks/brick1/g1 rebalance=yes hosts:"{{ play_hosts }}"
  run_once: true

- name: tune
  gluster_volume: state=present name=test1 options='{performance.cache-size: 256MB}'

- name: start gluster volume
  gluster_volume: status=started name=test1

- name: limit usage
  gluster_volume: state=present name=test1 directory=/foo quota=20.0MB

- name: stop gluster volume
  gluster_volume: state=stopped name=test1

- name: remove gluster volume
  gluster_volume: state=absent name=test1
"""

import time
import socket

def main():

    def run_gluster(gargs, **kwargs):
        args = [glusterbin]
        args.extend(gargs)
        rc, out, err = module.run_command(args, **kwargs)
        if rc != 0:
            module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out if out != '' else err))
        return out

    def run_gluster_nofail(gargs, **kwargs):
        args = [glusterbin]
        args.extend(gargs)
        rc, out, err = module.run_command(args, **kwargs)
        if rc != 0:
            return None
        return out

    def run_gluster_yes(gargs):
        args = [glusterbin]
        args.extend(gargs)
        rc, out, err = module.run_command(args, data='y\n')
        if rc != 0:
            module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out if out != '' else err))
        return out

    def get_peers():
        out = run_gluster([ 'peer', 'status'])
        i = 0
        peers = {}
        hostname = None
        uuid = None
        state = None
        for row in out.split('\n'):
            if ': ' in row:
                key, value = row.split(': ')
                if key.lower() == 'hostname':
                    hostname = value
                if key.lower() == 'uuid':
                    uuid = value
                if key.lower() == 'state':
                    state = value
                    peers[hostname] = [ uuid, state ]
        return peers

    def get_volumes():
        out = run_gluster([ 'volume', 'info' ])

        volumes = {}
        volume = {}
        for row in out.split('\n'):
            if ': ' in row:
                key, value = row.split(': ')
                if key.lower() == 'volume name':
                    volume['name'] = value
                    volume['options'] = {}
                    volume['quota'] = False
                if key.lower() == 'volume id':
                    volume['id'] = value
                if key.lower() == 'status':
                    volume['status'] = value
                if key.lower() == 'transport-type':
                    volume['transport'] = value
                if key.lower() != 'bricks' and key.lower()[:5] == 'brick':
                    if not 'bricks' in volume:
                        volume['bricks'] = []
                    volume['bricks'].append(value)
                # Volume options
                if '.' in key:
                    if not 'options' in volume:
                        volume['options'] = {}
                    volume['options'][key] = value
                    if key == 'features.quota' and value == 'on':
                        volume['quota'] = True
            else:
                if row.lower() != 'bricks:' and row.lower() != 'options reconfigured:':
                    if len(volume) > 0:
                        volumes[volume['name']] = volume
                    volume = {}
        return volumes

    def get_quotas(name, nofail):
        quotas = {}
        if nofail:
            out = run_gluster_nofail([ 'volume', 'quota', name, 'list' ])
            if not out:
                return quotas
        else:
            out = run_gluster([ 'volume', 'quota', name, 'list' ])
        for row in out.split('\n'):
            if row[:1] == '/':
                q = re.split('\s+', row)
                quotas[q[0]] = q[1]
        return quotas

    def wait_for_peer(host):
        for x in range(0, 4):
            peers = get_peers()
            if host in peers and peers[host][1].lower().find('peer in cluster') != -1:
                return True
            time.sleep(1)
        return False

    def probe(host):
        run_gluster([ 'peer', 'probe', host ])
        if not wait_for_peer(host):
            module.fail_json(msg='failed to probe peer %s' % host)
        changed = True

    def probe_all_peers(hosts, peers, myhostname):
        for host in hosts:
            if host not in peers:
                # dont probe ourselves
                if myhostname != host:
                    probe(host)

    def create_volume(name, stripe, replica, transport, hosts, brick, force):
        args = [ 'volume', 'create' ]
        args.append(name)
        if stripe:
            args.append('stripe')
            args.append(str(stripe))
        if replica:
            args.append('replica')
            args.append(str(replica))
        args.append('transport')
        args.append(transport)
        for host in hosts:
            args.append(('%s:%s' % (host, brick)))
        if force:
            args.append('force')
        run_gluster(args)

    def start_volume(name):
        run_gluster([ 'volume', 'start', name ])

    def stop_volume(name):
        run_gluster_yes([ 'volume', 'stop', name ])

    def set_volume_option(name, option, parameter):
        run_gluster([ 'volume', 'set', name, option, parameter ])

    def add_brick(name, brick):
        run_gluster([ 'volume', 'add-brick', name, brick ])

    def do_rebalance(name):
        run_gluster(['volume', 'rebalance', name, 'start'])

    def enable_quota(name):
        run_gluster([ 'volume', 'quota', name, 'enable' ])

    def set_quota(name, directory, value):
            run_gluster([ 'volume', 'quota', name, 'limit-usage', directory, value ])

    ### MAIN ###

    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True, default=None, aliases=['volume']),
            state=dict(required=True, choices=[ 'present', 'absent', 'started', 'stopped', 'rebalanced' ]),
            cluster=dict(required=False, default=None, type='list'),
            host=dict(required=False, default=None),
            stripes=dict(required=False, default=None, type='int'),
            replicas=dict(required=False, default=None, type='int'),
            transport=dict(required=False, default='tcp', choices=[ 'tcp', 'rdma', 'tcp,rdma' ]),
            brick=dict(required=False, default=None),
            start_on_create=dict(required=False, default=True, type='bool'),
            rebalance=dict(required=False, default=False, type='bool'),
            options=dict(required=False, default=None, type='dict'),
            quota=dict(required=False),
            directory=dict(required=False, default=None),
            force=dict(required=False, default=False, type='bool'),
            )
        )

    glusterbin = module.get_bin_path('gluster', True)

    changed = False

    action = module.params['state']
    volume_name = module.params['name']
    cluster= module.params['cluster']
    brick_path = module.params['brick']
    stripes = module.params['stripes']
    replicas = module.params['replicas']
    transport = module.params['transport']
    myhostname = module.params['host']
    start_on_create = module.boolean(module.params['start_on_create'])
    rebalance = module.boolean(module.params['rebalance'])
    force = module.boolean(module.params['force'])

    if not myhostname:
        myhostname = socket.gethostname()

    options = module.params['options']
    quota = module.params['quota']
    directory = module.params['directory']

    # get current state info
    peers = get_peers()
    volumes = get_volumes()
    quotas = {}
    if volume_name in volumes and volumes[volume_name]['quota'] and volumes[volume_name]['status'].lower() == 'started':
        quotas = get_quotas(volume_name, True)

    # do the work!
    if action == 'absent':
        if volume_name in volumes:
            run_gluster([ 'volume', 'delete', name ])
            changed = True

    if action == 'present':
        probe_all_peers(cluster, peers, myhostname)

        # create if it doesn't exist
        if volume_name not in volumes:
            create_volume(volume_name, stripes, replicas, transport, cluster, brick_path, force)
            changed = True

            # update volumes after the creation
            volumes = get_volumes()

        if volume_name in volumes:
            if volumes[volume_name]['status'].lower() != 'started' and start_on_create:
                start_volume(volume_name)
                changed = True

            # switch bricks
            new_bricks = []
            removed_bricks = []
            all_bricks = []
            for node in cluster:
                brick = '%s:%s' % (node, brick_path)
                all_bricks.append(brick)
                if brick not in volumes[volume_name]['bricks']:
                    new_bricks.append(brick)

            # this module does not yet remove bricks, but we check those anyways
            for brick in volumes[volume_name]['bricks']:
                if brick not in all_bricks:
                    removed_bricks.append(brick)

            for brick in new_bricks:
                add_brick(volume_name, brick)
                changed = True

            # handle quotas
            if quota:
                if not volumes[volume_name]['quota']:
                    enable_quota(volume_name)
                quotas = get_quotas(volume_name, False)
                if directory not in quotas or quotas[directory] != quota:
                    set_quota(volume_name, directory, quota)
                    changed = True

            # set options
            if options:
                for option in options.keys():
                    if option not in volumes[volume_name]['options'] or volumes[volume_name]['options'][option] != options[option]:
                        set_volume_option(volume_name, option, options[option])
                        changed = True

        else:
            module.fail_json(msg='failed to create volume %s' % volume_name)

    if volume_name not in volumes:
        module.fail_json(msg='volume not found %s' % volume_name)

    if action == 'started':
        if volumes[volume_name]['status'].lower() != 'started':
            start_volume(volume_name)
            changed = True

    if action == 'stopped':
        if volumes[volume_name]['status'].lower() != 'stopped':
            stop_volume(volume_name)
            changed = True

    if changed:
        volumes = get_volumes()
        if rebalance:
            do_rebalance(volume_name)

    facts = {}
    facts['glusterfs'] = { 'peers': peers, 'volumes': volumes, 'quotas': quotas }

    module.exit_json(changed=changed, ansible_facts=facts)

# import module snippets
from ansible.module_utils.basic import *
main()


text:
#ifndef IMPORTEXPRESSIONMATRIX_H
#define IMPORTEXPRESSIONMATRIX_H
#include <ace/core/core.h>

#include "expressionmatrix.h"

/*!
 * This class implements the import expression matrix analytic. This analytic
 * reads in a text file which contains a matrix as a table; that is, with each row
 * on a line, each value separated by whitespace, and the first row and column
 * containing the row names and column names, respectively. Elements which have
 * the given NAN token are read in as NAN. If the sample names are not in the
 * input file, the user must provide the number of samples to the analytic, and
 * the samples will be given integer names.
 */
class ImportExpressionMatrix : public EAbstractAnalytic
{
    Q_OBJECT
public:
    class Input;
    virtual int size() const override final;
    virtual void process(const EAbstractAnalyticBlock* result) override final;
    virtual EAbstractAnalyticInput* makeInput() override final;
    virtual void initialize();
private:
    /**
     * Structure used to load gene expression data
     */
    struct Gene
    {
        Gene() = default;
        Gene(int size)
        {
            expressions.resize(size);
        }

        QVector<float> expressions;
    };
    /**
     * Workspace variables to read from the input file.
     */
    QTextStream _stream;
    int _numLines {0};
    QVector<Gene> _genes;
    QStringList _geneNames;
    QStringList _sampleNames;
    /*!
     * Pointer to the input text file.
     */
    QFile* _input {nullptr};
    /*!
     * Pointer to the output expression matrix.
     */
    ExpressionMatrix* _output {nullptr};
    /*!
     * The string token used to represent NAN values.
     */
    QString _nanToken {"NA"};
    /*!
     * The number of samples to read.
     */
    qint32 _sampleSize {0};
    /*!
     * Whether the input expression matrix has a "RowID" entry that should
     * be ignored.
     */
    bool _containsRowID {false};
};

#endif


text:
package profitbricks

import (
	"fmt"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/profitbricks/profitbricks-sdk-go"
	"log"
	"strings"
)

func resourceProfitBricksNic() *schema.Resource {
	return &schema.Resource{
		Create: resourceProfitBricksNicCreate,
		Read:   resourceProfitBricksNicRead,
		Update: resourceProfitBricksNicUpdate,
		Delete: resourceProfitBricksNicDelete,
		Schema: map[string]*schema.Schema{

			"lan": {
				Type:     schema.TypeInt,
				Required: true,
			},
			"name": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"dhcp": {
				Type:     schema.TypeBool,
				Optional: true,
			},
			"ip": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"ips": {
				Type:     schema.TypeList,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Computed: true,
			},
			"firewall_active": {
				Type:     schema.TypeBool,
				Optional: true,
			},
			"nat": {
				Type:     schema.TypeBool,
				Optional: true,
			},
			"server_id": {
				Type:     schema.TypeString,
				Required: true,
			},
			"datacenter_id": {
				Type:     schema.TypeString,
				Required: true,
			},
		},
	}
}

func resourceProfitBricksNicCreate(d *schema.ResourceData, meta interface{}) error {
	nic := profitbricks.Nic{
		Properties: profitbricks.NicProperties{
			Lan: d.Get("lan").(int),
		},
	}
	if _, ok := d.GetOk("name"); ok {
		nic.Properties.Name = d.Get("name").(string)
	}
	if _, ok := d.GetOk("dhcp"); ok {
		nic.Properties.Dhcp = d.Get("dhcp").(bool)
	}

	if _, ok := d.GetOk("ip"); ok {
		raw := d.Get("ip").(string)
		ips := strings.Split(raw, ",")
		nic.Properties.Ips = ips
	}
	if _, ok := d.GetOk("firewall_active"); ok {
		raw := d.Get("firewall_active").(bool)
		nic.Properties.FirewallActive = raw
	}
	if _, ok := d.GetOk("nat"); ok {
		raw := d.Get("nat").(bool)
		nic.Properties.Nat = raw
	}

	nic = profitbricks.CreateNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), nic)
	if nic.StatusCode > 299 {
		return fmt.Errorf("Error occured while creating a nic: %s", nic.Response)
	}

	err := waitTillProvisioned(meta, nic.Headers.Get("Location"))
	if err != nil {
		return err
	}
	resp := profitbricks.RebootServer(d.Get("datacenter_id").(string), d.Get("server_id").(string))
	if resp.StatusCode > 299 {
		return fmt.Errorf("Error occured while creating a nic: %s", string(resp.Body))

	}
	err = waitTillProvisioned(meta, resp.Headers.Get("Location"))
	if err != nil {
		return err
	}
	d.SetId(nic.Id)
	return resourceProfitBricksNicRead(d, meta)
}

func resourceProfitBricksNicRead(d *schema.ResourceData, meta interface{}) error {
	nic := profitbricks.GetNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Id())
	if nic.StatusCode > 299 {
		if nic.StatusCode == 404 {
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Error occured while fetching a nic ID %s %s", d.Id(), nic.Response)
	}
	log.Printf("[INFO] LAN ON NIC: %d", nic.Properties.Lan)
	d.Set("dhcp", nic.Properties.Dhcp)
	d.Set("lan", nic.Properties.Lan)
	d.Set("name", nic.Properties.Name)
	d.Set("ips", nic.Properties.Ips)

	return nil
}

func resourceProfitBricksNicUpdate(d *schema.ResourceData, meta interface{}) error {
	properties := profitbricks.NicProperties{}

	if d.HasChange("name") {
		_, n := d.GetChange("name")

		properties.Name = n.(string)
	}
	if d.HasChange("lan") {
		_, n := d.GetChange("lan")
		properties.Lan = n.(int)
	}
	if d.HasChange("dhcp") {
		_, n := d.GetChange("dhcp")
		properties.Dhcp = n.(bool)
	}
	if d.HasChange("ip") {
		_, raw := d.GetChange("ip")
		ips := strings.Split(raw.(string), ",")
		properties.Ips = ips
	}
	if d.HasChange("nat") {
		_, raw := d.GetChange("nat")
		nat := raw.(bool)
		properties.Nat = nat
	}

	nic := profitbricks.PatchNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Id(), properties)

	if nic.StatusCode > 299 {
		return fmt.Errorf("Error occured while updating a nic: %s", nic.Response)
	}
	err := waitTillProvisioned(meta, nic.Headers.Get("Location"))
	if err != nil {
		return err
	}
	return resourceProfitBricksNicRead(d, meta)
}

func resourceProfitBricksNicDelete(d *schema.ResourceData, meta interface{}) error {
	resp := profitbricks.DeleteNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Id())
	err := waitTillProvisioned(meta, resp.Headers.Get("Location"))
	if err != nil {
		return err
	}
	d.SetId("")
	return nil
}


text:
require File.dirname(__FILE__) + '/../test_helper'

class TopicTest < Test::Unit::TestCase
  fixtures :all

  def test_last_page
    topic = topics(:Testing)
    assert_equal topic.last_page, 1
    topic.posts_count = 30
    assert_equal topic.last_page, 1
    topic.posts_count = 31
    assert_equal topic.last_page, 2
  end

  def test_to_s
    t = Topic.find(1)
    assert_equal t.to_s, 'Testing'
  end
end


text:
package org.nd4j.linalg.api.ops;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.shape.Shape;
import org.nd4j.linalg.exception.ND4JIllegalStateException;
import org.nd4j.linalg.util.ArrayUtil;
import org.nd4j.linalg.util.LinAlgExceptions;

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

/**
 * A base op for basic getters and setters
 *
 * @author Adam Gibson
 */
@Slf4j
public abstract class BaseTransformOp extends BaseOp implements TransformOp {

    public BaseTransformOp(SameDiff sameDiff,
                           SDVariable i_v1,
                           SDVariable i_v2) {
        this(sameDiff,i_v1,i_v2,false);
    }

    public BaseTransformOp(SameDiff sameDiff,
                           SDVariable i_v1,
                           SDVariable i_v2,
                           boolean inPlace) {
        super(sameDiff,inPlace,new Object[] {i_v2});
        if (i_v1 != null && i_v2 != null) {
            f().validateDifferentialFunctionsameDiff(i_v1);
            f().validateDifferentialFunctionsameDiff(i_v2);
            this.sameDiff = sameDiff;
            this.inPlace = inPlace;
            this.xVertexId = i_v1.getVarName();
            this.yVertexId = i_v2.getVarName();
            sameDiff.addArgsFor(new SDVariable[]{i_v1,i_v2},this);
            if(Shape.isPlaceholderShape(i_v1.getShape())) {
                sameDiff.addPropertyToResolve(this,i_v1.getVarName());
            }

            if(Shape.isPlaceholderShape(i_v2.getShape())) {
                sameDiff.addPropertyToResolve(this,i_v2.getVarName());
            }
            if(i_v1.getShape() != null)
                this.n = ArrayUtil.prod(i_v1.getShape());

        } else {
            throw new IllegalArgumentException("Input not null variables.");
        }

    }

    public BaseTransformOp(SameDiff sameDiff) {
        this.sameDiff = sameDiff;
    }

    public BaseTransformOp(SameDiff sameDiff,
                           SDVariable i_v1,
                           SDVariable i_v2,
                           Object[] extraArgs) {
        super(sameDiff,extraArgs);
        if (i_v1 != null && i_v2 != null) {

            f().validateDifferentialFunctionsameDiff(i_v1);
            f().validateDifferentialFunctionsameDiff(i_v2);
            this.sameDiff = sameDiff;
            this.xVertexId = i_v1.getVarName();
            this.yVertexId = i_v2.getVarName();
            sameDiff.addArgsFor(new SDVariable[]{i_v1,i_v2},this);
            if(i_v1.getShape() != null)
                this.n = ArrayUtil.prod(i_v1.getShape());

            if(Shape.isPlaceholderShape(i_v1.getShape())) {
                sameDiff.addPropertyToResolve(this,i_v1.getVarName());
            }

            if(Shape.isPlaceholderShape(i_v2.getShape())) {
                sameDiff.addPropertyToResolve(this,i_v2.getVarName());
            }

        } else {
            throw new IllegalArgumentException("Input not null variables.");
        }

    }

    public BaseTransformOp(SameDiff sameDiff,SDVariable i_v,boolean inPlace) {
        this(sameDiff,i_v,i_v.getShape(),inPlace,null);
    }

    public BaseTransformOp(SameDiff sameDiff,
                           SDVariable i_v,
                           int[] shape,
                           boolean inPlace,
                           Object[] extraArgs) {
        // FIXME: int cast !
        this(sameDiff, i_v, ArrayUtil.toLongArray(shape), inPlace, extraArgs);
    }

    public BaseTransformOp(SameDiff sameDiff,
                           SDVariable i_v,
                           long[] shape,
                           boolean inPlace,
                           Object[] extraArgs) {
        super(sameDiff,inPlace,extraArgs);

        if (i_v != null) {
            f().validateDifferentialFunctionsameDiff(i_v);
            this.xVertexId = i_v.getVarName();
            sameDiff.addArgsFor(new SDVariable[]{i_v},this);
            if(i_v.getShape() != null) {
                this.n = ArrayUtil.prod(i_v.getShape());
            }

            if(Shape.isPlaceholderShape(i_v.getShape())) {
                sameDiff.addPropertyToResolve(this,i_v.getVarName());
            }

        } else {
            throw new IllegalArgumentException("Input must not null variable.");
        }

    }

    public BaseTransformOp(SameDiff sameDiff,
                           SDVariable i_v,
                           Object[] extraArgs) {
        this(sameDiff,i_v,i_v.getShape(),false,extraArgs);

    }

    public BaseTransformOp(INDArray x, INDArray z) {
        super(x, z);
        LinAlgExceptions.assertSameShape(x, z);
    }

    public BaseTransformOp() {}

    public BaseTransformOp(INDArray x, INDArray z, long n) {
        super(x, z, n);
    }

    public BaseTransformOp(INDArray x, INDArray y, INDArray z, long n) {
        super(x, y, z, n);
        if (y != null)
            LinAlgExceptions.assertSameLength(x, y, z);
        else
            LinAlgExceptions.assertSameLength(x, z);

    }

    public BaseTransformOp(INDArray x) {
        super(x);
    }

    @Override
    public Type opType() {
        if(args() == null || args().length == 1)
            return Type.TRANSFORM;
        else if(args().length == 2)
            return Type.PAIRWISE;

        else throw new ND4JIllegalStateException("Illegal number of args (can only be 1 or 2)");
    }

    @Override
    public List<long[]> calculateOutputShape() {
        List<long[]> ret = new ArrayList<>(1);
        if(arg() == null)
            throw new ND4JIllegalStateException("No arg found for op!");

        val arr = sameDiff.getArrForVarName(arg().getVarName());
        if(arr == null)
            return Collections.emptyList();
        ret.add(arr.shape());
        this.n = arr.length();
        return ret;
    }

    @Override
    public INDArray z() {
        if(z == null) {
            if(sameDiff != null) {
                this.z = outputVariables()[0].getArr();
                if(this.z == null) {
                    val var = outputVariables()[0];
                    if(var.getShape() != null)
                        this. z = var.storeAndAllocateNewArray();
                    else {
                        val argsShape = args()[0].getShape();
                        if(argsShape != null) {
                            sameDiff.putShapeForVarName(var.getVarName(),argsShape);
                            this. z = var.storeAndAllocateNewArray();
                        }
                    }
                }
            }
        }

        return z;
    }

}


text:
#include <QVBoxLayout>
#include <QDir>
#include <QTextCodec>
#include <QTcpServer>
#include <QTcpSocket>

#include "ui_serverwindow.h"
#include "serverwindow.h"
#include "datamanager.h"
#include "consts.h"

ServerWindow::ServerWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    m_nbConnectedClients = 0;
    m_nbTCPConnections = 0;
    m_messageSize = 0;
    DrawInterface();

    m_serveur = new QTcpServer(this);
    if (!m_serveur->listen(QHostAddress::Any, 50885))
    {
        ui->L_serverStatus->setText(QString::fromUtf8("Le serveur n'a pas pu être démarré. Raison :
") +
                                    m_serveur->errorString());
    }
    else
    {
        ui->L_serverStatus->setText(QString::fromLatin1("Le serveur a été démarré sur le port ") +
                                    QString::number(m_serveur->serverPort()) +
                                    ".
Des clients peuvent maintenant se connecter.");

        connect(m_serveur, SIGNAL(newConnection()), this, SLOT(nouvelleConnexion()));
    }
}

ServerWindow::~ServerWindow()
{
    if (m_serveur)
    {
        m_serveur->close();
        delete m_serveur;
    }
    delete ui;
}

void ServerWindow::nouvelleConnexion()
{
    m_nbTCPConnections++;
    ui->L_tcpNumber->setText("Connexions TCP: " + QString::number(m_nbTCPConnections));
    QTcpSocket* newClient = m_serveur->nextPendingConnection();
    m_clients << newClient;
    connect(newClient, SIGNAL(readyRead()), this, SLOT(donneesRecues()));
    connect(newClient, SIGNAL(disconnected()), this, SLOT(deconnexionClient()));
    log("[new TcpConnection]: ");
}

void ServerWindow::donneesRecues()
{
    // 1 : on reçoit un paquet (ou un sous-paquet) d'un des clients

    // On détermine quel client envoie le message (recherche du QTcpSocket du client)
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    if (socket == 0)  // Si par hasard on n'a pas trouvé le client à l'origine du signal, on arrête la méthode
        return;

    // Si tout va bien, on continue : on récupère le message
    QDataStream in(socket);

    if (m_messageSize == 0)  // Si on ne connaît pas encore la taille du message, on essaie de la récupérer
    {
        if (socket->bytesAvailable() < (int)sizeof(quint16))  // On n'a pas reçu la taille du message en entier
            return;

        in >> m_messageSize;  // Si on a reçu la taille du message en entier, on la récupère
    }

    // Si on connaît la taille du message, on vérifie si on a reçu le message en entier
    if (socket->bytesAvailable() < m_messageSize)  // Si on n'a pas encore tout reçu, on arrête la méthode
        return;

    // Si ces lignes s'exécutent, c'est qu'on a reçu tout le message : on peut le récupérer !
    QString message;
    in >> message;
    log("[donneesRecues]: " + message);
    UserCommand userCMD = getCommand(message);

    //request handling
    switch (userCMD)
    {
        case UserCommand::newAccount:
            subscribe(message, socket);
            break;
        case UserCommand::connectRequest:
            connectUser(message, socket);
            break;
        case UserCommand::sendRequest:
            handleMessage(message, socket);
            break;
        case UserCommand::sentMessagesList:
        case UserCommand::receivedMessagesList:
            sendSavedMessages(message, socket, userCMD);
            break;
        case UserCommand::deleteMessage:
            deleteMessage(message, socket);
        default:
            break;
    }

    // 3 : remise de la taille du message à 0 pour permettre la réception des futurs messages
    m_messageSize = 0;
}

void ServerWindow::deconnexionClient()
{
    // On détermine quel client se déconnecte
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    if (socket == 0)
        return;

    log("[deconnexionClient]: " + m_users.value(socket));
    m_clients.removeOne(socket);
    if (m_users.contains(socket))
    {
        QString userName = m_users.value(socket);
        m_users.remove(socket);
        NotifyOthers(userName, false);
        if (m_nbConnectedClients > 0)
            m_nbConnectedClients--;
    }

    socket->deleteLater();
    m_nbTCPConnections--;
    ui->L_clientsNumber->setText("Nb clients :" + QString::number(m_nbConnectedClients));
    ui->L_tcpNumber->setText("Connexions TCP: " + QString::number(m_nbTCPConnections));
}

void ServerWindow::DumpConnectedClients()
{
    QList<QString> connectedUsers = m_users.values();
    ui->TE_log->clear();
    log(QString::number(connectedUsers.size()) + " connected Clients :");

    for (int i = 0; i < connectedUsers.size(); i++)
        log(connectedUsers[i]);
}

void ServerWindow::NotifyOthers(const QString& UserName, bool newConnection)
{
    QString message = _serverToken + _tcpSeparator;
    if (newConnection)
        message += _usersConnected;
    else
        message += _usersDIsconnected;

    message += _tcpSeparator + UserName;
    log("---NotifyOther---");
    sendToAll(message);
}

void ServerWindow::sendToAll(const QString& message) const
{
    QList<QTcpSocket*> connectedUsers = m_users.keys();
    for (auto it = connectedUsers.cbegin(); it != connectedUsers.cend(); ++it)
    {
        sendData(message, *it);
    }
}

/*
void ServerWindow::envoyerA(const QString &message,QString &dest)
{
    // Préparation du paquet
    QByteArray paquet;
    QDataStream out(&paquet, QIODevice::WriteOnly);

    out << (quint16) 0; // On écrit 0 au début du paquet pour réserver la place pour écrire la taille
    out << message; // On ajoute le message à la suite
    out.device()->seek(0); // On se replace au début du paquet
    out << (quint16) (paquet.size() - sizeof(quint16));
    m_users.key(dest)->write(paquet);
//    m_users.key(dest)->flush();
}
*/
void ServerWindow::sendUsersList(QTcpSocket* NewUser) const
{
    QString list = _serverToken + _tcpSeparator + _usersConnected + _tcpSeparator;
    QList<QString> usersList = m_users.values();
    log("SendUserList");
    int size = usersList.size();
    for (int i = 0; i < size - 1; i++)
    {
        list += usersList[i] + _tcpSeparator;
    }
    if (size > 0)
        list += usersList[size - 1];

    sendData(list, NewUser);
}

int ServerWindow::newMessagesCount(QString& userName)
{
    return DataManager::Instance()->MessagesCount(userName, NewMessage);
}

void ServerWindow::subscribe(const QString data, QTcpSocket* userSocket)
{
    log("[subscribe]: " + data);
    QString ServerResponse;
    QString login = data.split(_tcpSeparator).at(1);
    if (!findUser(login))
    {
        QString password = data.split(_tcpSeparator).at(2);
        QString newUser = login + _textSeparator + password + _newLine;
        QFile mdp("passwd.txt");
        if (appendToFile(mdp, newUser))
        {
            QDir currentDirectory(".");
            currentDirectory.mkdir(login);
            ServerResponse = _serverToken + _tcpSeparator + _newAccount + _tcpSeparator + _serverOk;
        }
        else
            ServerResponse =
                _serverToken + _tcpSeparator + _serverError + _tcpSeparator + "Could not insert a new user";
    }
    else
        ServerResponse = _serverToken + _tcpSeparator + _serverError + _tcpSeparator + "Login is already in use";

    sendData(ServerResponse, userSocket);
    userSocket->disconnectFromHost();
}

void ServerWindow::connectUser(const QString data, QTcpSocket* userSocket)
{
    log("[connection request]" + data);
    QStringList args = data.split(_tcpSeparator);

    // check if the client is already connected
    if (m_users.values().contains(args[1]))
    {
        sendData(_serverToken + _tcpSeparator + _serverError + _tcpSeparator + "User is already connected", userSocket);
        userSocket->disconnectFromHost();
    }
    else if (checkCredentials(args[1] + _textSeparator + args[2]))
    {
        sendData(_serverToken + _tcpSeparator + _connect + _tcpSeparator + _serverOk, userSocket);
        sendUsersList(userSocket);
        int count = newMessagesCount(args[1]);
        if (count > 0)
            sendData(_serverToken + _tcpSeparator + _newMessage + _tcpSeparator + QString::number(count), userSocket);

        NotifyOthers(args[1], true);
        m_users[userSocket] = args[1];
        m_nbConnectedClients++;
        ui->L_clientsNumber->setText("Nb clients :" + QString::number(m_nbConnectedClients));
        //        messagesnonrecu(a);
        log(args[1] + " is connected");
    }
    else
    {
        sendData(_serverToken + _tcpSeparator + _serverError + _tcpSeparator + "Incorrect Login or password",
                 userSocket);
        userSocket->disconnectFromHost();
    }
}

void ServerWindow::handleMessage(const QString data, QTcpSocket* userSocket)
{
    if (m_users.contains(userSocket))
    {
        QStringList args = data.split(_tcpSeparator);
        QString Tcpmessage, Logmessage;

        if (findUser(args[1]))  // si le client est inscrit
        {
            Tcpmessage = _serverToken + _tcpSeparator + _instantMessage + _tcpSeparator + m_users[userSocket] +
                         _tcpSeparator + args[2];

            Logmessage = QDateTime::currentDateTime().toString(Qt::ISODate) + _textSeparator;

            DataManager::Instance()->saveMessage(
                m_users[userSocket], Logmessage + args[1] + _textSeparator + args[2] + _newLine, SentMessage);
            if (m_users.key(args[1]) != NULL)  // s'il est connecté
            {
                // envoyerA(Tcpmessage, args[1]);
                sendData(Tcpmessage, m_users.key(args[1]));
                DataManager::Instance()->saveMessage(
                    args[1], Logmessage + m_users[userSocket] + _textSeparator + args[2] + _newLine, ReceivedMessage);
            }
            else
            {
                DataManager::Instance()->saveMessage(args[1],
                                                     Logmessage + m_users[userSocket] + _textSeparator + args[2] +
                                                         _textSeparator + QString::number(1) + _newLine,
                                                     ReceivedMessage);
            }
        }
        else
        {
            Tcpmessage =
                _serverToken + _tcpSeparator + _serverError + _tcpSeparator + args[1] + " is not a member of A7kili";
            sendData(Tcpmessage, userSocket);
        }
    }
}

void ServerWindow::sendSavedMessages(const QString msg, QTcpSocket* userSocket, UserCommand userCMD)
{
    QStringList args = msg.split(_tcpSeparator);
    QString messageList = _serverToken + _tcpSeparator;
    // Check if the user was connected
    if (m_users.contains(userSocket))
    {
        QString userName = m_users[userSocket];
        QDateTime since = QDateTime::fromString(args[1], Qt::ISODate);
        int count = args[2].toInt();
        QStringList messages;
        MessageType type;
        if (userCMD == UserCommand::receivedMessagesList)
        {
            type = MessageType::ReceivedMessage;
            messageList += _ReceivedMessages + _tcpSeparator;
        }
        else if (userCMD == UserCommand::sentMessagesList)
        {
            type = MessageType::SentMessage;
            messageList += _SentMessages + _tcpSeparator;
        }
        DataManager::Instance()->getMessages(userName, messages, type, since, count);
        for (auto it = messages.cbegin(); it != messages.cend(); ++it)
        {
            // TODO: remove the \n from the data
            // and the last <tcpSeparator>
            messageList += (*it) + _tcpSeparator;
        }
        int pos = messageList.size() - _tcpSeparator.size();
        messageList.remove(pos, _tcpSeparator.size());
        sendData(messageList, userSocket);
    }
}

//TODO: finish DataManager::deleteMessage()
void ServerWindow::deleteMessage(const QString &msg, QTcpSocket* userSocket)
{
    QStringList args = msg.split(_tcpSeparator);
    if (args.size() < 4)
        return;

    MessageType type = ReceivedMessage;
    QString userName = m_users[userSocket];

    if (args[1] == "Sent")
        type = SentMessage;

    QString ServerResponse = _serverToken + _tcpSeparator + args[0] + _tcpSeparator;
    if (DataManager::Instance()->deleteMessage(userName, args[2] + _textSeparator + args[3] ,type))
        ServerResponse += _serverOk;
    else
        ServerResponse += _serverError;

    sendData(ServerResponse, userSocket);

}

//TODO: Move it to the Data manager
bool ServerWindow::checkCredentials(const QString text) const
{
    QFile file("passwd.txt");

    if (!file.exists())
        return false;

    bool found = false;
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QByteArray data;
        while ((!file.atEnd()) && (found == false))
        {
            data = file.readLine();
            data.truncate(data.length() - 1);
            if (QString(data) == text)
                found = true;
        }
        file.close();
    }
    return found;
}

//TODO: Should be in the Data Manager
bool ServerWindow::findUser(const QString text) const
{
    QFile file("passwd.txt");

    if (!file.exists())
        return false;

    bool found = false;
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QByteArray data;
        while ((!file.atEnd()) && (found == false))
        {
            data = file.readLine();
            QString ligne(data);
            ligne = ligne.split(_textSeparator).at(0);
            if (ligne == text)
                found = true;
        }
        file.close();
    }
    return found;
}

void ServerWindow::sendData(const QString& message, QTcpSocket* client) const
{
    QByteArray paquet;
    QDataStream out(&paquet, QIODevice::WriteOnly);
    // out.setVersion(QDataStream::Qt_4_0);
    // message.prepend("register,");
    out << (quint16)0;
    out << message;
    out.device()->seek(0);
    out << (quint16)(paquet.size() - sizeof(quint16));
    qint64 data = client->write(paquet);
    client->flush();
    client->waitForBytesWritten();
    log("sentData: Size =" + QString::number(data) + ", message = " + message + "\n");
}

bool ServerWindow::appendToFile(QFile& file, const QString data) const
{
    if (! file.open(QIODevice::Append | QIODevice::Text))
        return false;

    QTextStream flux(&file);
    flux << data;
    file.close();
    return true;
}

UserCommand ServerWindow::getCommand(const QString txt) const
{
    if (txt.isEmpty())
        return UserCommand::error;

    QString cmd = txt.split(_tcpSeparator).at(0);
    if (cmd.isEmpty())
        return UserCommand::error;
    else if (cmd == _newAccount)
        return UserCommand::newAccount;
    else if (cmd == _sendMessage)
        return UserCommand::sendRequest;
    else if (cmd == _connect)
        return UserCommand::connectRequest;
    else if (cmd == _ReceivedMessages)
        return UserCommand::receivedMessagesList;
    else if (cmd == _SentMessages)
        return UserCommand::sentMessagesList;
    else if (cmd == _deleteMessage)
        return UserCommand::deleteMessage;
    else
        return UserCommand::other;
}

void ServerWindow::DrawInterface()
{
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf8"));
    ui->setupUi(this);
    ui->centralwidget->adjustSize();
    move(600, 200);

    setWindowTitle("A7kili - Serveur");
    this->setWindowIcon(QIcon("tchat.jpg"));
    ui->L_clientsNumber->setText(QString::fromLatin1("Aucun client n'est connecté"));
    ui->L_tcpNumber->setText(QString::fromLatin1("0 connexions Tcp"));

    connect(ui->PB_exit, SIGNAL(clicked()), qApp, SLOT(quit()));
    connect(ui->PB_Clear, SIGNAL(clicked()), ui->TE_log, SLOT(clear()));
    connect(ui->PB_Clients, SIGNAL(clicked()), this, SLOT(DumpConnectedClients()));
}

void ServerWindow::log(const QString text) const
{
    ui->TE_log->append(text);
}


text:
package "openjdk-7-jdk" do
  action :install
end

package "unzip" do
  action :install
end

package "vim" do
  action :install
end

package "build-essential" do
  action :install
end

directory node[:torquebox][:dir] do
  owner node[:torquebox][:user]
  mode "0755"
  action :create
end

directory node[:torquebox][:log_dir] do
  owner node[:torquebox][:user]
  group node[:torquebox][:user]
  mode "0755"
  action :create
end

ENV['TORQUEBOX_DIR']   = node[:torquebox][:dir]
ENV['TORQUEBOX_HOME']  = node[:torquebox][:home]
ENV['TORQUEBOX_OWNER'] = node[:torquebox][:user]

bash "install_torquebox" do
  cwd node[:torquebox][:dir]
  code <<-EOH
    /usr/bin/wget -N http://torquebox.org/release/org/torquebox/torquebox-dist/2.3.0/torquebox-dist-2.3.0-bin.zip
    /usr/bin/unzip -q torquebox-dist-2.3.0-bin.zip
    /bin/ln -s torquebox-2.3.0 $TORQUEBOX_HOME
    /bin/chown -R $TORQUEBOX_OWNER:$TORQUEBOX_OWNER $TORQUEBOX_DIR
  EOH
  creates "#{node[:torquebox][:home]}/jboss/bin/standalone.sh"
end

template "torquebox.profile" do
  path "#{node[:torquebox][:conf_dir]}/torquebox.sh"
  source "torquebox.profile.erb"
  owner "root"
  group "root"
  mode "0644"
end

template "torquebox.standalone.xml" do
  path "#{node[:torquebox][:home]}/jboss/standalone/configuration/standalone.xml"
  source "standalone.xml.erb"
  owner node[:torquebox][:user]
  group node[:torquebox][:user]
  mode "0664"
end

service "torquebox" do
  supports :restart => true, :start => true, :stop => true
  action :nothing
end

template "torquebox.initd" do
  path "/etc/init.d/torquebox"
  source "torquebox.initd.erb"
  owner "root"
  group "root"
  mode "0755"
  notifies :enable, resources(:service => "torquebox")
  notifies :start, resources(:service => "torquebox")

end

#service "torquebox" do
#  action [:enable, :start]
#end


text:
namespace nt2 { namespace container
{
  template<typename T, typename S>
  struct  table
        : expression< boost::proto::basic_expr< boost::proto::tag::terminal
                                              , boost::proto::term
                                                < nt2::memory
                                                     ::container< nt2::tag::table_
                                                                , T,S>
                                                                >
                                              >
                    , nt2::memory::container<nt2::tag::table_,T,S>
                    >
  {
    typedef nt2::memory::container<nt2::tag::table_,T,S>           container_type;
    typedef expression< boost::proto::basic_expr< boost::proto::tag::terminal
                                                , boost::proto::term<container_type>
                                                 >
                      , container_type
                      >                                           nt2_expression;

    typedef typename container_type::pointer                      pointer;
    typedef typename container_type::const_pointer                const_pointer;
    typedef typename container_type::iterator                     iterator;
    typedef typename container_type::const_iterator               const_iterator;
    typedef typename container_type::allocator_type               allocator_type;

    //==========================================================================
    //  table default constructor
    //==========================================================================
    table() {}

    //==========================================================================
    //  table constructor from its allocator
    //==========================================================================
    table( allocator_type const& a ) : nt2_expression(container_type(a)) {}

    //==========================================================================
    // table copy constructor
    //==========================================================================
    table( table const& a0 ) : nt2_expression(a0)
    {
    }

    //==========================================================================
    // table constructor from a single initializer.
    // This version handles initializing from of_size or expression.
    //==========================================================================
    template<typename A0>
    table( A0 const& a0 )
    {
      nt2::construct(*this,a0);
    }

    //==========================================================================
    // table constructor from a pair of initializer.
    //==========================================================================
    template<typename A0, typename A1>
    table( A0 const& a0, A1 const& a1 )
    {
      nt2::construct(*this,a0,a1);
    }

    //==========================================================================
    // table constructor from a triplet of initializer.
    // This version handles initializing from : { size, Iterator, Iterator }
    //==========================================================================
    template<typename A0, typename A1, typename A2>
    table( A0 const& a0, A1 const& a1, A2 const& a2 )
    {
      nt2::construct(*this,a0,a1,a2);
    }

    //==========================================================================
    // Enable base expression handling of assignment
    //==========================================================================
    template<class Xpr> BOOST_FORCEINLINE
    typename boost::disable_if< boost::is_base_of<nt2_expression, Xpr>
                              , table&
                              >::type
    operator=(Xpr const& xpr)
    {
      nt2_expression::operator=(xpr);
      return *this;
    }

    BOOST_FORCEINLINE table& operator=(table const& xpr)
    {
      nt2_expression::operator=(xpr);
      return *this;
    }

    iterator        begin()       { return boost::proto::value(*this).begin(); }
    const_iterator  begin() const { return boost::proto::value(*this).begin(); }

    iterator        end()       { return boost::proto::value(*this).end(); }
    const_iterator  end() const { return boost::proto::value(*this).end(); }
  };
} }

#if defined(BOOST_MSVC)
#pragma warning( pop )
#endif

#endif


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ThBroaderSandbox extends Model
{
    protected $table = 'th_broaders_master';
    /**
     * The attributes that are assignable.
     *
     * @var array
     */
    protected $fillable = [
        'broader_id',
        'narrower_id',
    ];

}