<commit_before>// CodeMirror 4.1.1, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  function wordRegexp(words) {
    return new RegExp("^((" + words.join(")|(") + "))\\b");
  }

  var wordOperators = wordRegexp(["and", "or", "not", "is", "in"]);
  var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield"];
  var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
  var py2 = {builtins: ["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
                        "file", "intern", "long", "raw_input", "reduce", "reload",
                        "unichr", "unicode", "xrange", "False", "True", "None"],
             keywords: ["exec", "print"]};
  var py3 = {builtins: ["ascii", "bytes", "exec", "print"],
             keywords: ["nonlocal", "False", "True", "None"]};

  CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

  function top(state) {
    return state.scopes[state.scopes.length - 1];
  }

  CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = "error";

    var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = parserConf.singleDelimiters || new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]");
    var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
    var hangingIndent = parserConf.hangingIndent || parserConf.indentUnit;

    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
    if(parserConf.extra_keywords != undefined){
      myKeywords = myKeywords.concat(parserConf.extra_keywords);
    }
    if(parserConf.extra_builtins != undefined){
      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
    }
    if (parserConf.version && parseInt(parserConf.version, 10) == 3) {
      myKeywords = myKeywords.concat(py3.keywords);
      myBuiltins = myBuiltins.concat(py3.builtins);
      var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
      myKeywords = myKeywords.concat(py2.keywords);
      myBuiltins = myBuiltins.concat(py2.builtins);
      var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(myKeywords);
    var builtins = wordRegexp(myBuiltins);

    // tokenizers
    function tokenBase(stream, state) {
      // Handle scope changes
      if (stream.sol() && top(state).type == "py") {
        var scopeOffset = top(state).offset;
        if (stream.eatSpace()) {
          var lineOffset = stream.indentation();
          if (lineOffset > scopeOffset)
            pushScope(stream, state, "py");
          else if (lineOffset < scopeOffset)
            return dedent(stream, state) ? ERRORCLASS : null;
          return null;
        } else if (scopeOffset > 0 && dedent(stream, state)) {
          return state.tokenize(stream, state) + " " + ERRORCLASS;
        }
      }
      if (stream.eatSpace()) return null;

      var ch = stream.peek();

      // Handle Comments
      if (ch == "#") {
        stream.skipToEnd();
        return "comment";
      }

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        var floatLiteral = false;
        // Floats
        if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be "imaginary"
          stream.eat(/J/i);
          return "number";
        }
        // Integers
        var intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
          // Decimal literals may be "imaginary"
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be "long"
          stream.eat(/L/i);
          return "number";
        }
      }

      // Handle Strings
      if (stream.match(stringPrefixes)) {
        state.tokenize = tokenStringFactory(stream.current());
        return state.tokenize(stream, state);
      }

      // Handle operators and Delimiters
      if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))
        return null;

      if (stream.match(doubleOperators)
          || stream.match(singleOperators)
          || stream.match(wordOperators))
        return "operator";

      if (stream.match(singleDelimiters))
        return null;

      if (stream.match(keywords))
        return "keyword";

      if (stream.match(builtins))
        return "builtin";

      if (stream.match(/^(self|cls)\b/))
        return "variable-2";

      if (stream.match(identifiers)) {
        if (state.lastToken == "def" || state.lastToken == "class")
          return "def";
        return "variable";
      }

      // Handle non-detected items
      stream.next();
      return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
      while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenBase;
            return OUTCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenBase;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function pushScope(stream, state, type) {
      var offset = 0, align = null;
      if (type == "py") {
        while (top(state).type != "py")
          state.scopes.pop();
      }
      offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent);
      if (type != "py" && !stream.match(/^(\s|#.*)*$/, false))
        align = stream.column() + 1;
      state.scopes.push({offset: offset, type: type, align: align});
    }

    function dedent(stream, state) {
      var indented = stream.indentation();
      while (top(state).offset > indented) {
        if (top(state).type != "py") return true;
        state.scopes.pop();
      }
      return top(state).offset == indented;
    }

    function tokenLexer(stream, state) {
      var style = state.tokenize(stream, state);
      var current = stream.current();

      // Handle '.' connected identifiers
      if (current == ".") {
        style = stream.match(identifiers, false) ? null : ERRORCLASS;
        if (style == null && state.lastStyle == "meta") {
          // Apply 'meta' style to '.' connected identifiers when
          // appropriate.
          style = "meta";
        }
        return style;
      }

      // Handle decorators
      if (current == "@")
        return stream.match(identifiers, false) ? "meta" : ERRORCLASS;

      if ((style == "variable" || style == "builtin")
          && state.lastStyle == "meta")
        style = "meta";

      // Handle scope changes.
      if (current == "pass" || current == "return")
        state.dedent += 1;

      if (current == "lambda") state.lambda = true;
      if (current == ":" && !state.lambda && top(state).type == "py")
        pushScope(stream, state, "py");

      var delimiter_index = "[({".indexOf(current);
      if (delimiter_index != -1)
        pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));

      delimiter_index = "])}".indexOf(current);
      if (delimiter_index != -1) {
        if (top(state).type == current) state.scopes.pop();
        else return ERRORCLASS;
      }
      if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
        if (state.scopes.length > 1) state.scopes.pop();
        state.dedent -= 1;
      }

      return style;
    }

    var external = {
      startState: function(basecolumn) {
        return {
          tokenize: tokenBase,
          scopes: [{offset: basecolumn || 0, type: "py", align: null}],
          lastStyle: null,
          lastToken: null,
          lambda: false,
          dedent: 0
        };
      },

      token: function(stream, state) {
        var style = tokenLexer(stream, state);

        state.lastStyle = style;

        var current = stream.current();
        if (current && style)
          state.lastToken = current;

        if (stream.eol() && state.lambda)
          state.lambda = false;
        return style;
      },

      indent: function(state, textAfter) {
        if (state.tokenize != tokenBase)
          return state.tokenize.isString ? CodeMirror.Pass : 0;

        var scope = top(state);
        var closing = textAfter && textAfter.charAt(0) == scope.type;
        if (scope.align != null)
          return scope.align - (closing ? 1 : 0);
        else
          return scope.offset - (closing ? conf.indentUnit : 0);
      },

      lineComment: "#",
      fold: "indent"
    };
    return external;
  });

  CodeMirror.defineMIME("text/x-python", "python");

  var words = function(str) { return str.split(" "); };

  CodeMirror.defineMIME("text/x-cython", {
    name: "python",
    extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
                          "extern gil include nogil property public"+
                          "readonly struct union DEF IF ELIF ELSE")
  });

});
<commit_msg>[python mode] Fix indentation-breaking bug<commit_after>// CodeMirror 4.1.1, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  function wordRegexp(words) {
    return new RegExp("^((" + words.join(")|(") + "))\\b");
  }

  var wordOperators = wordRegexp(["and", "or", "not", "is", "in"]);
  var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield"];
  var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
  var py2 = {builtins: ["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
                        "file", "intern", "long", "raw_input", "reduce", "reload",
                        "unichr", "unicode", "xrange", "False", "True", "None"],
             keywords: ["exec", "print"]};
  var py3 = {builtins: ["ascii", "bytes", "exec", "print"],
             keywords: ["nonlocal", "False", "True", "None"]};

  CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

  function top(state) {
    return state.scopes[state.scopes.length - 1];
  }

  CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = "error";

    var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = parserConf.singleDelimiters || new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]");
    var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;

    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
    if(parserConf.extra_keywords != undefined){
      myKeywords = myKeywords.concat(parserConf.extra_keywords);
    }
    if(parserConf.extra_builtins != undefined){
      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
    }
    if (parserConf.version && parseInt(parserConf.version, 10) == 3) {
      myKeywords = myKeywords.concat(py3.keywords);
      myBuiltins = myBuiltins.concat(py3.builtins);
      var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
      myKeywords = myKeywords.concat(py2.keywords);
      myBuiltins = myBuiltins.concat(py2.builtins);
      var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(myKeywords);
    var builtins = wordRegexp(myBuiltins);

    // tokenizers
    function tokenBase(stream, state) {
      // Handle scope changes
      if (stream.sol() && top(state).type == "py") {
        var scopeOffset = top(state).offset;
        if (stream.eatSpace()) {
          var lineOffset = stream.indentation();
          if (lineOffset > scopeOffset)
            pushScope(stream, state, "py");
          else if (lineOffset < scopeOffset)
            return dedent(stream, state) ? ERRORCLASS : null;
          return null;
        } else if (scopeOffset > 0 && dedent(stream, state)) {
          return state.tokenize(stream, state) + " " + ERRORCLASS;
        }
      }
      if (stream.eatSpace()) return null;

      var ch = stream.peek();

      // Handle Comments
      if (ch == "#") {
        stream.skipToEnd();
        return "comment";
      }

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        var floatLiteral = false;
        // Floats
        if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be "imaginary"
          stream.eat(/J/i);
          return "number";
        }
        // Integers
        var intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
          // Decimal literals may be "imaginary"
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be "long"
          stream.eat(/L/i);
          return "number";
        }
      }

      // Handle Strings
      if (stream.match(stringPrefixes)) {
        state.tokenize = tokenStringFactory(stream.current());
        return state.tokenize(stream, state);
      }

      // Handle operators and Delimiters
      if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))
        return null;

      if (stream.match(doubleOperators)
          || stream.match(singleOperators)
          || stream.match(wordOperators))
        return "operator";

      if (stream.match(singleDelimiters))
        return null;

      if (stream.match(keywords))
        return "keyword";

      if (stream.match(builtins))
        return "builtin";

      if (stream.match(/^(self|cls)\b/))
        return "variable-2";

      if (stream.match(identifiers)) {
        if (state.lastToken == "def" || state.lastToken == "class")
          return "def";
        return "variable";
      }

      // Handle non-detected items
      stream.next();
      return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
      while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenBase;
            return OUTCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenBase;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function pushScope(stream, state, type) {
      var offset = 0, align = null;
      if (type == "py") {
        while (top(state).type != "py")
          state.scopes.pop();
      }
      offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent);
      if (type != "py" && !stream.match(/^(\s|#.*)*$/, false))
        align = stream.column() + 1;
      state.scopes.push({offset: offset, type: type, align: align});
    }

    function dedent(stream, state) {
      var indented = stream.indentation();
      while (top(state).offset > indented) {
        if (top(state).type != "py") return true;
        state.scopes.pop();
      }
      return top(state).offset == indented;
    }

    function tokenLexer(stream, state) {
      var style = state.tokenize(stream, state);
      var current = stream.current();

      // Handle '.' connected identifiers
      if (current == ".") {
        style = stream.match(identifiers, false) ? null : ERRORCLASS;
        if (style == null && state.lastStyle == "meta") {
          // Apply 'meta' style to '.' connected identifiers when
          // appropriate.
          style = "meta";
        }
        return style;
      }

      // Handle decorators
      if (current == "@")
        return stream.match(identifiers, false) ? "meta" : ERRORCLASS;

      if ((style == "variable" || style == "builtin")
          && state.lastStyle == "meta")
        style = "meta";

      // Handle scope changes.
      if (current == "pass" || current == "return")
        state.dedent += 1;

      if (current == "lambda") state.lambda = true;
      if (current == ":" && !state.lambda && top(state).type == "py")
        pushScope(stream, state, "py");

      var delimiter_index = "[({".indexOf(current);
      if (delimiter_index != -1)
        pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));

      delimiter_index = "])}".indexOf(current);
      if (delimiter_index != -1) {
        if (top(state).type == current) state.scopes.pop();
        else return ERRORCLASS;
      }
      if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
        if (state.scopes.length > 1) state.scopes.pop();
        state.dedent -= 1;
      }

      return style;
    }

    var external = {
      startState: function(basecolumn) {
        return {
          tokenize: tokenBase,
          scopes: [{offset: basecolumn || 0, type: "py", align: null}],
          lastStyle: null,
          lastToken: null,
          lambda: false,
          dedent: 0
        };
      },

      token: function(stream, state) {
        var style = tokenLexer(stream, state);

        state.lastStyle = style;

        var current = stream.current();
        if (current && style)
          state.lastToken = current;

        if (stream.eol() && state.lambda)
          state.lambda = false;
        return style;
      },

      indent: function(state, textAfter) {
        if (state.tokenize != tokenBase)
          return state.tokenize.isString ? CodeMirror.Pass : 0;

        var scope = top(state);
        var closing = textAfter && textAfter.charAt(0) == scope.type;
        if (scope.align != null)
          return scope.align - (closing ? 1 : 0);
        else
          return scope.offset - (closing ? conf.indentUnit : 0);
      },

      lineComment: "#",
      fold: "indent"
    };
    return external;
  });

  CodeMirror.defineMIME("text/x-python", "python");

  var words = function(str) { return str.split(" "); };

  CodeMirror.defineMIME("text/x-cython", {
    name: "python",
    extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
                          "extern gil include nogil property public"+
                          "readonly struct union DEF IF ELIF ELSE")
  });

});
<|endoftext|>


<commit_before>$(function() {

    var lang = {
            save: 'Save',
            saved: 'Saved :)',
            saving_error : 'Oops! an error occurred while saving :(',

            edit: 'Edit',

            retrieve_error: 'Oops! an error occurred while retrieving your content :('
        },

        article    = document.getElementById('whitepage'),
        edited     = false,
        last_value = '',

        edit_b     = document.createElement('button');

    function retrieve() {
        $.ajax('api.php?retrieve=1', {
            dataType: 'json',
            success: function(r) {
                if (r.error) {
                    notif(lang.retriving_error, 'error');
                }

                r = r.data;

                article.innerHTML = last_value = r ? r : '';
            },

            error: notif.bind(null, lang.retrieving_error, 'error')
        });
    }

    function save() {
        $.ajax('api.php?save=1', {
            dataType: 'json',
            type: 'POST',
            data: {
                text: article.innerHTML
            },

            success: function(r) {
                console.log(r);
            },

            error: notif.bind(null, lang.saving_error, 'error')

        });
    }

    function save_and_exit() {
        save();
        article.removeAttribute('contenteditable');
        edited = false;

        edit_b.innerText = lang.edit;
        edit_b.onclick   = edit;
    }

    function edit() {
        if (edited) {return;}
        edited = true;
        article.setAttribute('contenteditable', true);

        edit_b.innerText = lang.save;
        edit_b.onclick = save_and_exit;
    }

    function notif(text, type) {
        //TODO
        console.log(text, type);
    }

    retrieve();
    edit_b.innerText = lang.edit;
    document.body.insertBefore(edit_b, article);
    edit_b.onclick = edit;
});
<commit_msg>using .textContent instead of .innerText for Firefox support, notifications added.<commit_after>$(function() {

    var lang = {
            save: 'Save',
            saved: 'Saved :)',
            saving_error : 'Oops! an error occurred while saving :(',

            edit: 'Edit',

            retrieve_error: 'Oops! an error occurred while retrieving your content :('
        },

        body       = document.body,

        article    = document.getElementById('whitepage'),
        edited     = false,
        last_value = '',

        edit_b     = document.createElement('button'),

        notif      = document.createElement('div'),
        notif_msg  = document.createElement('span'),
        shown_notif= false;

    function retrieve() {
        $.ajax('api.php?retrieve=1', {
            dataType: 'json',
            success: function(r) {
                if (r.error) {
                    display_notif(lang.retriving_error, 'error');
                }

                r = r.data;

                article.innerHTML = last_value = r ? r : '';
            },

            error: display_notif.bind(null, lang.retrieving_error, 'error')
        });
    }

    function save(fn) {
        if (last_value === article.innerHTML) {return;}

        $.ajax('api.php?save=1', {
            dataType: 'json',
            type: 'POST',
            data: {
                text: article.innerHTML
            },

            success: function(r) {
                if (r.error) {
                    display_notif(lang.saving_error, 'error');
                }
                else {
                    last_value = r.data;
                    display_notif(lang.saved, 'success');
                }
                if (fn instanceof Function)
                    fn();
            },

            error: display_notif.bind(null, lang.saving_error, 'error')

        });
    }

    function save_and_exit() {
        save();
        article.removeAttribute('contenteditable');
        edited = false;

        edit_b.textContent = lang.edit;
        edit_b.onclick   = edit;
    }

    function regular_saving() {
        if (last_value == article.innerHTML) {return}

        save(function() {
            window.setTimeout(regular_saving, 10000);
        });
    }

    function edit() {
        if (edited) {return;}
        edited = true;
        article.setAttribute('contenteditable', true);
        article.focus();

        edit_b.textContent = lang.save;
        edit_b.onclick = save_and_exit;

        window.setTimeout(regular_saving, 10000);
    }

    function hide_notif(fn) {
        if (!shown_notif) {return}
        $(notif).animate({top: '-500px'}, {
            duration: 2000,
            complete: function(){
                notif_msg.textContent = '';
                shown_notif = false;
                if (fn instanceof Function)
                    fn()
            }
        });
    }

    function display_notif(text, type) {

        if (shown_notif) {
            if (text === notif_msg.textContent) {return}
            return hide_notif(display_notif.bind(null, text, type));
        }

        notif_msg.textContent = text;
        notif.className = 'notif '+type;

        if (!notif_msg.parentNode) {
            notif.appendChild(notif_msg);
        }
        if (!notif.parentNode) {
            body.insertBefore(notif, body.firstChild);
        }

        $(notif).animate({top: '-5px'}, {
            duration: 500,
            complete: function() { shown_notif = true; }
        });

        window.setTimeout(hide_notif, type==='error' ? 3000 : 2000);

    }

    retrieve();
    edit_b.textContent = lang.edit;
    document.body.insertBefore(edit_b, article);
    edit_b.onclick = edit;

});
<|endoftext|>


<commit_before>'use strict';

let otherCmd;
let x11w;
let CFG;
let utility;
const waterfall = require('promise-waterfall');
const fs = require('fs');
const path = require('path');
const otherCmdMod = require('./otherCmd');
const x11wMod = require('./x11Wrapper');
const utilityMod = require('./utility');

module.exports = (passedCFG) => {
  CFG = passedCFG;
  otherCmd = otherCmdMod(CFG);
  x11w = x11wMod(CFG);
  utility = utilityMod(CFG);

  return {
    // expose x11 helper
    x11Helper: x11w,

    // node x11
    goToFirstWorkspace,
    restoreWindowPosition,
    getWindowGeometry,
    closeWindow,
    goToWorkspace,

    // other cmd
    getActiveWindowList,
    getConnectedDisplaysId,
    readAndSetAdditionalMetaDataForWin,
    findDesktopFile,
    startProgram,
  };
};

function catchGenericErr(err) {
  console.error('Generic Error in Meta Wrapper', err, err.stack);
  throw err;
}

// NODE X11
function closeWindow(windowId) {
  return x11w.closeWindow(windowId);
}

function goToFirstWorkspace() {
  return x11w.goToViewport(0, 0);
}

function restoreWindowPosition(win) {
  console.log('Restoring window position for "' + win.wmClassName + '"');
  return x11w.restoreWindowPosition(win);
}

function getWindowGeometry(winId) {
  return x11w.getWindowGeometry(winId);
}

function goToWorkspace(winId, workSpaceNr) {
  return x11w.goToWorkspace(winId, workSpaceNr);
}

// OTHER CMD
function getConnectedDisplaysId() {
  return otherCmd.getConnectedDisplaysId();
}

function readAndSetAdditionalMetaDataForWin(win) {
  return otherCmd.readAndSetAdditionalMetaDataForWin(win);
}

function findDesktopFile(file) {
  return utility.findDesktopFile(file);
}

function startProgram(executableFile, desktopFilePath) {
  console.log('Starting: ' + (executableFile || desktopFilePath));
  return otherCmd.startProgram(executableFile, desktopFilePath);
}

// MIXED
function getActiveWindowList() {
  return new Promise((fulfill, reject) => {
    return otherCmd.getActiveWindowList()
      .then((windowList) => {
        const promises = [];

        windowList.forEach((win) => {
          promises.push(() => {
            return getWindowGeometry(win.windowId)
              .then((geo) => {
                for (let prop in geo) {
                  if (geo.hasOwnProperty(prop)) {
                    win[prop] = geo[prop];
                  }
                }

                // TODO organize adding of all those different properties better
                // add missing static properties
                win.simpleName = parseSimpleWindowName(win.wmClassName);
              });
          });
        });

        // we're using a waterfall because we're dealing with x11 requests

        if (promises.length > 0) {
          waterfall(promises)
            .then(() => {
              addParsedExecutableFilesFromWmClassNames(windowList)
                .then((windowListWithWmClassNames) => {
                  fulfill(windowListWithWmClassNames);
                });
            })
            .catch(reject);
        } else {
          fulfill([])
        }
      });
  }).catch(catchGenericErr);
}

// MIXED
function addParsedExecutableFilesFromWmClassNames(windowList) {
  return new Promise((fulfill, reject) => {
    const promises = [];
    windowList.forEach((win) => {
      // only if we're unable to parse this via xprop
      if (!win.executableFile) {
        promises.push(() => {
          return parseExecutableFileFromWmClassName(win.wmClassName)
            .then((fileName) => {
              win.executableFile = fileName;
            });
        });
      }
    });

    // TODO replace waterfall with regular exec
    waterfall(promises)
      .then(() => {
        fulfill(windowList);
      })
      .catch(reject);
  }).catch(catchGenericErr);
}

function parseExecutableFileFromWmClassName(wmClassName) {
  return new Promise((fulfill, reject) => {
    const executableFileFromMap = CFG.WM_CLASS_AND_EXECUTABLE_FILE_MAP[wmClassName];
    if (executableFileFromMap) {
      fulfill(executableFileFromMap);
    } else {
      const splitValues = wmClassName.split('.');
      const fileName = splitValues[0];
      if (isChromeApp(fileName)) {
        parseChromeAppDesktopFileName(fileName)
          .then(fulfill)
          .catch(reject);
      } else {
        fulfill(fileName + '.desktop');
      }
    }
  }).catch(catchGenericErr);
}

function parseSimpleWindowName(wmClassName) {
  const splitValues = wmClassName.split('.');
  if (splitValues[1]) {
    return splitValues[1];
  } else {
    return wmClassName;
  }
}

function isChromeApp(fileName) {
  return !!fileName.match(/^crx_/);
}

function parseChromeAppDesktopFileName(fileName) {
  return new Promise((fulfill, reject) => {
    // we wan't to search fro desktop files only
    const locateStr = '*' + fileName.replace('crx_', 'chrome-') + '*.desktop';
    findDesktopFile(locateStr)
      .then((fileNameStr) => {
        const split = fileNameStr.split('\n');
        const newFileName = path.basename(split[0]);
        fulfill(newFileName);
      })
      .catch(reject);
  }).catch(catchGenericErr);
}<commit_msg>Prevent an error when no windows with an unknown executable exist in windowList<commit_after>'use strict';

let otherCmd;
let x11w;
let CFG;
let utility;
const waterfall = require('promise-waterfall');
const fs = require('fs');
const path = require('path');
const otherCmdMod = require('./otherCmd');
const x11wMod = require('./x11Wrapper');
const utilityMod = require('./utility');

module.exports = (passedCFG) => {
  CFG = passedCFG;
  otherCmd = otherCmdMod(CFG);
  x11w = x11wMod(CFG);
  utility = utilityMod(CFG);

  return {
    // expose x11 helper
    x11Helper: x11w,

    // node x11
    goToFirstWorkspace,
    restoreWindowPosition,
    getWindowGeometry,
    closeWindow,
    goToWorkspace,

    // other cmd
    getActiveWindowList,
    getConnectedDisplaysId,
    readAndSetAdditionalMetaDataForWin,
    findDesktopFile,
    startProgram,
  };
};

function catchGenericErr(err) {
  console.error('Generic Error in Meta Wrapper', err, err.stack);
  throw err;
}

// NODE X11
function closeWindow(windowId) {
  return x11w.closeWindow(windowId);
}

function goToFirstWorkspace() {
  return x11w.goToViewport(0, 0);
}

function restoreWindowPosition(win) {
  console.log('Restoring window position for "' + win.wmClassName + '"');
  return x11w.restoreWindowPosition(win);
}

function getWindowGeometry(winId) {
  return x11w.getWindowGeometry(winId);
}

function goToWorkspace(winId, workSpaceNr) {
  return x11w.goToWorkspace(winId, workSpaceNr);
}

// OTHER CMD
function getConnectedDisplaysId() {
  return otherCmd.getConnectedDisplaysId();
}

function readAndSetAdditionalMetaDataForWin(win) {
  return otherCmd.readAndSetAdditionalMetaDataForWin(win);
}

function findDesktopFile(file) {
  return utility.findDesktopFile(file);
}

function startProgram(executableFile, desktopFilePath) {
  console.log('Starting: ' + (executableFile || desktopFilePath));
  return otherCmd.startProgram(executableFile, desktopFilePath);
}

// MIXED
function getActiveWindowList() {
  return new Promise((fulfill, reject) => {
    return otherCmd.getActiveWindowList()
      .then((windowList) => {
        const promises = [];

        windowList.forEach((win) => {
          promises.push(() => {
            return getWindowGeometry(win.windowId)
              .then((geo) => {
                for (let prop in geo) {
                  if (geo.hasOwnProperty(prop)) {
                    win[prop] = geo[prop];
                  }
                }

                // TODO organize adding of all those different properties better
                // add missing static properties
                win.simpleName = parseSimpleWindowName(win.wmClassName);
              });
          });
        });

        // we're using a waterfall because we're dealing with x11 requests

        if (promises.length > 0) {
          waterfall(promises)
            .then(() => {
              addParsedExecutableFilesFromWmClassNames(windowList)
                .then((windowListWithWmClassNames) => {
                  fulfill(windowListWithWmClassNames);
                });
            })
            .catch(reject);
        } else {
          fulfill([])
        }
      });
  }).catch(catchGenericErr);
}

// MIXED
function addParsedExecutableFilesFromWmClassNames(windowList) {
  return new Promise((fulfill, reject) => {
    const promises = [];
    windowList.forEach((win) => {
      // only if we're unable to parse this via xprop
      if (!win.executableFile) {
        promises.push(() => {
          return parseExecutableFileFromWmClassName(win.wmClassName)
            .then((fileName) => {
              win.executableFile = fileName;
            });
        });
      }
    });

    // TODO replace waterfall with regular exec
    if(promises.length){
      waterfall(promises)
        .then(() => {
          fulfill(windowList);
        })
        .catch(reject);
    }else{
      fulfill(windowList);
    }
  }).catch(catchGenericErr);
}

function parseExecutableFileFromWmClassName(wmClassName) {
  return new Promise((fulfill, reject) => {
    const executableFileFromMap = CFG.WM_CLASS_AND_EXECUTABLE_FILE_MAP[wmClassName];
    if (executableFileFromMap) {
      fulfill(executableFileFromMap);
    } else {
      const splitValues = wmClassName.split('.');
      const fileName = splitValues[0];
      if (isChromeApp(fileName)) {
        parseChromeAppDesktopFileName(fileName)
          .then(fulfill)
          .catch(reject);
      } else {
        fulfill(fileName + '.desktop');
      }
    }
  }).catch(catchGenericErr);
}

function parseSimpleWindowName(wmClassName) {
  const splitValues = wmClassName.split('.');
  if (splitValues[1]) {
    return splitValues[1];
  } else {
    return wmClassName;
  }
}

function isChromeApp(fileName) {
  return !!fileName.match(/^crx_/);
}

function parseChromeAppDesktopFileName(fileName) {
  return new Promise((fulfill, reject) => {
    // we wan't to search fro desktop files only
    const locateStr = '*' + fileName.replace('crx_', 'chrome-') + '*.desktop';
    findDesktopFile(locateStr)
      .then((fileNameStr) => {
        const split = fileNameStr.split('\n');
        const newFileName = path.basename(split[0]);
        fulfill(newFileName);
      })
      .catch(reject);
  }).catch(catchGenericErr);
}
<|endoftext|>


<commit_before>module.exports = {
  dist: 'dist',
  distJs: 'dist/js',
  distCss: 'dist/css',

  banner:
    '/*!\n' +
    ' * Copyright 2014 Drifty Co.\n' +
    ' * http://drifty.com/\n' +
    ' *\n' +
    ' * Ionic, v<%= pkg.version %>\n' +
    ' * A powerful HTML5 mobile app framework.\n' +
    ' * http://ionicframework.com/\n' +
    ' *\n' +
    ' * By @maxlynch, @benjsperry, @adamdbradley <3\n' +
    ' *\n' +
    ' * Licensed under the MIT license. Please see LICENSE for more information.\n'+
    ' *\n' +
    ' */\n\n' +
    '(function() {\n',
  bundleBanner:
    '/*!\n' +
    ' * ionic.bundle.js is a concatenation of:\n' +
    ' * ionic.js, angular.js, angular-animate.js,\n'+
    ' * angular-ui-router.js, and ionic-angular.js\n'+
    ' */\n\n',
  footer: '\n})();',

  ionicFiles: [
    // Base
    'js/ionic.js',

    // Utils
    'js/utils/animate.js',
    'js/utils/dom.js',
    'js/utils/events.js',
    'js/utils/gestures.js',
    'js/utils/platform.js',
    'js/utils/poly.js',
    'js/utils/tap.js',
    'js/utils/activator.js',
    'js/utils/utils.js',
    'js/utils/keyboard.js',

    // Views
    'js/views/view.js',

    'js/views/scrollView.js',

    'js/views/actionSheetView.js',
    'js/views/headerBarView.js',
    'js/views/listView.js',
    'js/views/loadingView.js',
    'js/views/modalView.js',
    'js/views/navBarView.js',
    'js/views/sideMenuView.js',
    'js/views/sliderView.js',
    'js/views/tabBarView.js',
    'js/views/toggleView.js',

    // Controllers
    'js/controllers/viewController.js',

    'js/controllers/navController.js',
    'js/controllers/sideMenuController.js',
    'js/controllers/tabBarController.js'

  ],

  angularIonicFiles: [
    'js/ext/angular/src/ionicAngular.js',
    'js/ext/angular/src/service/**/*.js',
    'js/ext/angular/src/directive/**/*.js',
    'js/ext/angular/src/controller/**/*.js'
  ],

  //Which vendor files to include in dist, used by build
  //Matched relative to config/lib/
  vendorFiles: [
    'js/angular/angular-animate.js',
    'js/angular/angular-animate.min.js',
    'js/angular/angular-resource.js',
    'js/angular/angular-resource.min.js',
    'js/angular/angular-sanitize.js',
    'js/angular/angular-sanitize.min.js',
    'js/angular/angular.js',
    'js/angular/angular.min.js',
    'js/angular-ui/angular-ui-router.js',
    'js/angular-ui/angular-ui-router.min.js',
    'fonts/ionicons.eot',
    'fonts/ionicons.svg',
    'fonts/ionicons.ttf',
    'fonts/ionicons.woff'
  ],

  ionicBundleFiles: [
    'dist/js/ionic.js',
    'dist/js/angular/angular.js',
    'dist/js/angular/angular-animate.js',
    'dist/js/angular/angular-sanitize.js',
    'dist/js/angular-ui/angular-ui-router.js',
    'dist/js/ionic-angular.js'
  ]
};
<commit_msg>chore(build): fix banner<commit_after>module.exports = {
  dist: 'dist',
  distJs: 'dist/js',
  distCss: 'dist/css',

  banner:
    '/*!\n' +
    ' * Copyright 2014 Drifty Co.\n' +
    ' * http://drifty.com/\n' +
    ' *\n' +
    ' * Ionic, v<%= pkg.version %>\n' +
    ' * A powerful HTML5 mobile app framework.\n' +
    ' * http://ionicframework.com/\n' +
    ' *\n' +
    ' * By @maxlynch, @benjsperry, @adamdbradley <3\n' +
    ' *\n' +
    ' * Licensed under the MIT license. Please see LICENSE for more information.\n'+
    ' *\n' +
    ' */\n\n' ,
  bundleBanner:
    '/*!\n' +
    ' * ionic.bundle.js is a concatenation of:\n' +
    ' * ionic.js, angular.js, angular-animate.js,\n'+
    ' * angular-ui-router.js, and ionic-angular.js\n'+
    ' */\n\n',
  footer: '\n})();',

  ionicFiles: [
    // Base
    'js/ionic.js',

    // Utils
    'js/utils/animate.js',
    'js/utils/dom.js',
    'js/utils/events.js',
    'js/utils/gestures.js',
    'js/utils/platform.js',
    'js/utils/poly.js',
    'js/utils/tap.js',
    'js/utils/activator.js',
    'js/utils/utils.js',
    'js/utils/keyboard.js',

    // Views
    'js/views/view.js',

    'js/views/scrollView.js',

    'js/views/actionSheetView.js',
    'js/views/headerBarView.js',
    'js/views/listView.js',
    'js/views/loadingView.js',
    'js/views/modalView.js',
    'js/views/navBarView.js',
    'js/views/sideMenuView.js',
    'js/views/sliderView.js',
    'js/views/tabBarView.js',
    'js/views/toggleView.js',

    // Controllers
    'js/controllers/viewController.js',

    'js/controllers/navController.js',
    'js/controllers/sideMenuController.js',
    'js/controllers/tabBarController.js'

  ],

  angularIonicFiles: [
    'js/ext/angular/src/ionicAngular.js',
    'js/ext/angular/src/service/**/*.js',
    'js/ext/angular/src/directive/**/*.js',
    'js/ext/angular/src/controller/**/*.js'
  ],

  //Which vendor files to include in dist, used by build
  //Matched relative to config/lib/
  vendorFiles: [
    'js/angular/angular-animate.js',
    'js/angular/angular-animate.min.js',
    'js/angular/angular-resource.js',
    'js/angular/angular-resource.min.js',
    'js/angular/angular-sanitize.js',
    'js/angular/angular-sanitize.min.js',
    'js/angular/angular.js',
    'js/angular/angular.min.js',
    'js/angular-ui/angular-ui-router.js',
    'js/angular-ui/angular-ui-router.min.js',
    'fonts/ionicons.eot',
    'fonts/ionicons.svg',
    'fonts/ionicons.ttf',
    'fonts/ionicons.woff'
  ],

  ionicBundleFiles: [
    'dist/js/ionic.js',
    'dist/js/angular/angular.js',
    'dist/js/angular/angular-animate.js',
    'dist/js/angular/angular-sanitize.js',
    'dist/js/angular-ui/angular-ui-router.js',
    'dist/js/ionic-angular.js'
  ]
};
<|endoftext|>


<commit_before>CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = 'error';

    function wordRegexp(words) {
        return new RegExp("^((" + words.join(")|(") + "))\\b");
    }

    var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
    var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");

    var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
    var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
                          'def', 'del', 'elif', 'else', 'except', 'finally',
                          'for', 'from', 'global', 'if', 'import',
                          'lambda', 'pass', 'raise', 'return',
                          'try', 'while', 'with', 'yield'];
    var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
                          'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
                          'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
                          'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
                          'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
                          'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
                          'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
                          'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
                          'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
                          'type', 'vars', 'zip', '__import__', 'NotImplemented',
                          'Ellipsis', '__debug__'];
    var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
                            'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
                            'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
               'keywords': ['exec', 'print']};
    var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
               'keywords': ['nonlocal', 'False', 'True', 'None']};

    if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
        commonkeywords = commonkeywords.concat(py3.keywords);
        commonBuiltins = commonBuiltins.concat(py3.builtins);
        var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
        commonkeywords = commonkeywords.concat(py2.keywords);
        commonBuiltins = commonBuiltins.concat(py2.builtins);
        var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(commonkeywords);
    var builtins = wordRegexp(commonBuiltins);

    var indentInfo = null;

    // tokenizers
    function tokenBase(stream, state) {
        // Handle scope changes
        if (stream.sol()) {
            var scopeOffset = state.scopes[0].offset;
            if (stream.eatSpace()) {
                var lineOffset = stream.indentation();
                if (lineOffset > scopeOffset) {
                    indentInfo = 'indent';
                } else if (lineOffset < scopeOffset) {
                    indentInfo = 'dedent';
                }
                return null;
            } else {
                if (scopeOffset > 0) {
                    dedent(stream, state);
                }
            }
        }
        if (stream.eatSpace()) {
            return null;
        }

        var ch = stream.peek();

        // Handle Comments
        if (ch === '#') {
            stream.skipToEnd();
            return 'comment';
        }

        // Handle Number Literals
        if (stream.match(/^[0-9\.]/, false)) {
            var floatLiteral = false;
            // Floats
            if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
            if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
            if (stream.match(/^\.\d+/)) { floatLiteral = true; }
            if (floatLiteral) {
                // Float literals may be "imaginary"
                stream.eat(/J/i);
                return 'number';
            }
            // Integers
            var intLiteral = false;
            // Hex
            if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
            // Binary
            if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
            // Octal
            if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
            // Decimal
            if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
                // Decimal literals may be "imaginary"
                stream.eat(/J/i);
                // TODO - Can you have imaginary longs?
                intLiteral = true;
            }
            // Zero by itself with no other piece of number.
            if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
            if (intLiteral) {
                // Integer literals may be "long"
                stream.eat(/L/i);
                return 'number';
            }
        }

        // Handle Strings
        if (stream.match(stringPrefixes)) {
            state.tokenize = tokenStringFactory(stream.current());
            return state.tokenize(stream, state);
        }

        // Handle operators and Delimiters
        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
            return null;
        }
        if (stream.match(doubleOperators)
            || stream.match(singleOperators)
            || stream.match(wordOperators)) {
            return 'operator';
        }
        if (stream.match(singleDelimiters)) {
            return null;
        }

        if (stream.match(keywords)) {
            return 'keyword';
        }

        if (stream.match(builtins)) {
            return 'builtin';
        }

        if (stream.match(identifiers)) {
            return 'variable';
        }

        // Handle non-detected items
        stream.next();
        return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
        while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
            delimiter = delimiter.substr(1);
        }
        var singleline = delimiter.length == 1;
        var OUTCLASS = 'string';

        return function tokenString(stream, state) {
            while (!stream.eol()) {
                stream.eatWhile(/[^'"\\]/);
                if (stream.eat('\\')) {
                    stream.next();
                    if (singleline && stream.eol()) {
                        return OUTCLASS;
                    }
                } else if (stream.match(delimiter)) {
                    state.tokenize = tokenBase;
                    return OUTCLASS;
                } else {
                    stream.eat(/['"]/);
                }
            }
            if (singleline) {
                if (parserConf.singleLineStringErrors) {
                    return ERRORCLASS;
                } else {
                    state.tokenize = tokenBase;
                }
            }
            return OUTCLASS;
        };
    }

    function indent(stream, state, type) {
        type = type || 'py';
        var indentUnit = 0;
        if (type === 'py') {
            if (state.scopes[0].type !== 'py') {
                state.scopes[0].offset = stream.indentation();
                return;
            }
            for (var i = 0; i < state.scopes.length; ++i) {
                if (state.scopes[i].type === 'py') {
                    indentUnit = state.scopes[i].offset + conf.indentUnit;
                    break;
                }
            }
        } else {
            indentUnit = stream.column() + stream.current().length;
        }
        state.scopes.unshift({
            offset: indentUnit,
            type: type
        });
    }

    function dedent(stream, state, type) {
        type = type || 'py';
        if (state.scopes.length == 1) return;
        if (state.scopes[0].type === 'py') {
            var _indent = stream.indentation();
            var _indent_index = -1;
            for (var i = 0; i < state.scopes.length; ++i) {
                if (_indent === state.scopes[i].offset) {
                    _indent_index = i;
                    break;
                }
            }
            if (_indent_index === -1) {
                return true;
            }
            while (state.scopes[0].offset !== _indent) {
                state.scopes.shift();
            }
            return false
        } else {
            if (type === 'py') {
                state.scopes[0].offset = stream.indentation();
                return false;
            } else {
                if (state.scopes[0].type != type) {
                    return true;
                }
                state.scopes.shift();
                return false;
            }
        }
    }

    function tokenLexer(stream, state) {
        indentInfo = null;
        var style = state.tokenize(stream, state);
        var current = stream.current();

        // Handle '.' connected identifiers
        if (current === '.') {
            style = stream.match(identifiers, false) ? null : ERRORCLASS;
            if (style === null && state.lastToken.style === 'meta') {
                // Apply 'meta' style to '.' connected identifiers when
                // appropriate.
                style = 'meta';
            }
            return style;
        }

        // Handle decorators
        if (current === '@') {
            return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
        }

        if ((style === 'variable' || style === 'builtin')
            && state.lastToken.style === 'meta') {
            style = 'meta';
        }

        // Handle scope changes.
        if (current === 'pass' || current === 'return') {
            state.dedent += 1;
        }
        if (current === 'lambda') state.lambda = true;
        if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
            || indentInfo === 'indent') {
            indent(stream, state);
        }
        var delimiter_index = '[({'.indexOf(current);
        if (delimiter_index !== -1) {
            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
        }
        if (indentInfo === 'dedent') {
            if (dedent(stream, state)) {
                return ERRORCLASS;
            }
        }
        delimiter_index = '])}'.indexOf(current);
        if (delimiter_index !== -1) {
            if (dedent(stream, state, current)) {
                return ERRORCLASS;
            }
        }
        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
            if (state.scopes.length > 1) state.scopes.shift();
            state.dedent -= 1;
        }

        return style;
    }

    var external = {
        startState: function(basecolumn) {
            return {
              tokenize: tokenBase,
              scopes: [{offset:basecolumn || 0, type:'py'}],
              lastToken: null,
              lambda: false,
              dedent: 0
          };
        },

        token: function(stream, state) {
            var style = tokenLexer(stream, state);

            state.lastToken = {style:style, content: stream.current()};

            if (stream.eol() && stream.lambda) {
                state.lambda = false;
            }

            return style;
        },

        indent: function(state, textAfter) {
            if (state.tokenize != tokenBase) {
                return 0;
            }

            return state.scopes[0].offset;
        }

    };
    return external;
});

CodeMirror.defineMIME("text/x-python", "python");
<commit_msg>[python mode] Fix null-dereference bug<commit_after>CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = 'error';

    function wordRegexp(words) {
        return new RegExp("^((" + words.join(")|(") + "))\\b");
    }

    var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
    var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");

    var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
    var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
                          'def', 'del', 'elif', 'else', 'except', 'finally',
                          'for', 'from', 'global', 'if', 'import',
                          'lambda', 'pass', 'raise', 'return',
                          'try', 'while', 'with', 'yield'];
    var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
                          'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
                          'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
                          'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
                          'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
                          'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
                          'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
                          'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
                          'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
                          'type', 'vars', 'zip', '__import__', 'NotImplemented',
                          'Ellipsis', '__debug__'];
    var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
                            'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
                            'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
               'keywords': ['exec', 'print']};
    var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
               'keywords': ['nonlocal', 'False', 'True', 'None']};

    if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
        commonkeywords = commonkeywords.concat(py3.keywords);
        commonBuiltins = commonBuiltins.concat(py3.builtins);
        var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
        commonkeywords = commonkeywords.concat(py2.keywords);
        commonBuiltins = commonBuiltins.concat(py2.builtins);
        var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(commonkeywords);
    var builtins = wordRegexp(commonBuiltins);

    var indentInfo = null;

    // tokenizers
    function tokenBase(stream, state) {
        // Handle scope changes
        if (stream.sol()) {
            var scopeOffset = state.scopes[0].offset;
            if (stream.eatSpace()) {
                var lineOffset = stream.indentation();
                if (lineOffset > scopeOffset) {
                    indentInfo = 'indent';
                } else if (lineOffset < scopeOffset) {
                    indentInfo = 'dedent';
                }
                return null;
            } else {
                if (scopeOffset > 0) {
                    dedent(stream, state);
                }
            }
        }
        if (stream.eatSpace()) {
            return null;
        }

        var ch = stream.peek();

        // Handle Comments
        if (ch === '#') {
            stream.skipToEnd();
            return 'comment';
        }

        // Handle Number Literals
        if (stream.match(/^[0-9\.]/, false)) {
            var floatLiteral = false;
            // Floats
            if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
            if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
            if (stream.match(/^\.\d+/)) { floatLiteral = true; }
            if (floatLiteral) {
                // Float literals may be "imaginary"
                stream.eat(/J/i);
                return 'number';
            }
            // Integers
            var intLiteral = false;
            // Hex
            if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
            // Binary
            if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
            // Octal
            if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
            // Decimal
            if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
                // Decimal literals may be "imaginary"
                stream.eat(/J/i);
                // TODO - Can you have imaginary longs?
                intLiteral = true;
            }
            // Zero by itself with no other piece of number.
            if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
            if (intLiteral) {
                // Integer literals may be "long"
                stream.eat(/L/i);
                return 'number';
            }
        }

        // Handle Strings
        if (stream.match(stringPrefixes)) {
            state.tokenize = tokenStringFactory(stream.current());
            return state.tokenize(stream, state);
        }

        // Handle operators and Delimiters
        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
            return null;
        }
        if (stream.match(doubleOperators)
            || stream.match(singleOperators)
            || stream.match(wordOperators)) {
            return 'operator';
        }
        if (stream.match(singleDelimiters)) {
            return null;
        }

        if (stream.match(keywords)) {
            return 'keyword';
        }

        if (stream.match(builtins)) {
            return 'builtin';
        }

        if (stream.match(identifiers)) {
            return 'variable';
        }

        // Handle non-detected items
        stream.next();
        return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
        while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
            delimiter = delimiter.substr(1);
        }
        var singleline = delimiter.length == 1;
        var OUTCLASS = 'string';

        return function tokenString(stream, state) {
            while (!stream.eol()) {
                stream.eatWhile(/[^'"\\]/);
                if (stream.eat('\\')) {
                    stream.next();
                    if (singleline && stream.eol()) {
                        return OUTCLASS;
                    }
                } else if (stream.match(delimiter)) {
                    state.tokenize = tokenBase;
                    return OUTCLASS;
                } else {
                    stream.eat(/['"]/);
                }
            }
            if (singleline) {
                if (parserConf.singleLineStringErrors) {
                    return ERRORCLASS;
                } else {
                    state.tokenize = tokenBase;
                }
            }
            return OUTCLASS;
        };
    }

    function indent(stream, state, type) {
        type = type || 'py';
        var indentUnit = 0;
        if (type === 'py') {
            if (state.scopes[0].type !== 'py') {
                state.scopes[0].offset = stream.indentation();
                return;
            }
            for (var i = 0; i < state.scopes.length; ++i) {
                if (state.scopes[i].type === 'py') {
                    indentUnit = state.scopes[i].offset + conf.indentUnit;
                    break;
                }
            }
        } else {
            indentUnit = stream.column() + stream.current().length;
        }
        state.scopes.unshift({
            offset: indentUnit,
            type: type
        });
    }

    function dedent(stream, state, type) {
        type = type || 'py';
        if (state.scopes.length == 1) return;
        if (state.scopes[0].type === 'py') {
            var _indent = stream.indentation();
            var _indent_index = -1;
            for (var i = 0; i < state.scopes.length; ++i) {
                if (_indent === state.scopes[i].offset) {
                    _indent_index = i;
                    break;
                }
            }
            if (_indent_index === -1) {
                return true;
            }
            while (state.scopes[0].offset !== _indent) {
                state.scopes.shift();
            }
            return false
        } else {
            if (type === 'py') {
                state.scopes[0].offset = stream.indentation();
                return false;
            } else {
                if (state.scopes[0].type != type) {
                    return true;
                }
                state.scopes.shift();
                return false;
            }
        }
    }

    function tokenLexer(stream, state) {
        indentInfo = null;
        var style = state.tokenize(stream, state);
        var current = stream.current();

        // Handle '.' connected identifiers
        if (current === '.') {
            style = stream.match(identifiers, false) ? null : ERRORCLASS;
            if (style === null && state.lastToken === 'meta') {
                // Apply 'meta' style to '.' connected identifiers when
                // appropriate.
                style = 'meta';
            }
            return style;
        }

        // Handle decorators
        if (current === '@') {
            return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
        }

        if ((style === 'variable' || style === 'builtin')
            && state.lastToken === 'meta') {
            style = 'meta';
        }

        // Handle scope changes.
        if (current === 'pass' || current === 'return') {
            state.dedent += 1;
        }
        if (current === 'lambda') state.lambda = true;
        if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
            || indentInfo === 'indent') {
            indent(stream, state);
        }
        var delimiter_index = '[({'.indexOf(current);
        if (delimiter_index !== -1) {
            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
        }
        if (indentInfo === 'dedent') {
            if (dedent(stream, state)) {
                return ERRORCLASS;
            }
        }
        delimiter_index = '])}'.indexOf(current);
        if (delimiter_index !== -1) {
            if (dedent(stream, state, current)) {
                return ERRORCLASS;
            }
        }
        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
            if (state.scopes.length > 1) state.scopes.shift();
            state.dedent -= 1;
        }

        return style;
    }

    var external = {
        startState: function(basecolumn) {
            return {
              tokenize: tokenBase,
              scopes: [{offset:basecolumn || 0, type:'py'}],
              lastToken: null,
              lambda: false,
              dedent: 0
          };
        },

        token: function(stream, state) {
            var style = tokenLexer(stream, state);

            state.lastToken = style;

            if (stream.eol() && stream.lambda) {
                state.lambda = false;
            }

            return style;
        },

        indent: function(state, textAfter) {
            if (state.tokenize != tokenBase) {
                return 0;
            }

            return state.scopes[0].offset;
        }

    };
    return external;
});

CodeMirror.defineMIME("text/x-python", "python");
<|endoftext|>


<commit_before>/**
 * Created by Jurriaan on 4-12-2015.
 * Server node file
 */
var d = new Date();
var t = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log("Server started\n" + t);

var express = require('express'),
    app = express(),
    http = require('http'),
    url = require('url'),
    bodyParser = require('body-parser'),
    db = require('./todos.js'),
    dashboard = require('./dashboard.js');

app.use(bodyParser.json());
app.use(express.static(__dirname + "/../"));

http.createServer(app).listen(3030);
console.log("Listening on port 3030");

app.get("/a+l+t+o+d+o+s+", function (req, res) {
    console.log("Received /alltodos");
    db.getAllTodos(res);
});

app.get("/a+d+t+o+d+o+", function(req, res) {
    console.log("Received /addtodo");
    db.addTodo(req, res);
});

app.get("/r+e+m+o+v+e+t+o+d+o+", function(req, res) {
    console.log("Received /removetodo");
    db.removeTodo(req, res);
});

app.get("/d+a+s+h+b+o+a+r+d+", function(req, res) {
    console.log("Recieved /dashboard");
    dashboard.getDashboardInfo(req, res);
});

app.get("/u+p+d+a+t+e+t+o+d+o+", function(req, res) {
    console.log("Received /updatetodo");
    db.updateTodo(req, res);
});
<commit_msg>fixed typo in server.js<commit_after>/**
 * Created by Jurriaan on 4-12-2015.
 * Server node file
 */
var d = new Date();
var t = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log("Server started\n" + t);

var express = require('express'),
    app = express(),
    http = require('http'),
    url = require('url'),
    bodyParser = require('body-parser'),
    db = require('./todos.js'),
    dashboard = require('./dashboard.js');

app.use(bodyParser.json());
app.use(express.static(__dirname + "/../"));

http.createServer(app).listen(3030);
console.log("Listening on port 3030");

app.get("/a+l+t+o+d+o+s+", function (req, res) {
    console.log("Received /alltodos");
    db.getAllTodos(res);
});

app.get("/a+d+d+t+o+d+o+", function(req, res) {
    console.log("Received /addtodo");
    db.addTodo(req, res);
});

app.get("/r+e+m+o+v+e+t+o+d+o+", function(req, res) {
    console.log("Received /removetodo");
    db.removeTodo(req, res);
});

app.get("/d+a+s+h+b+o+a+r+d+", function(req, res) {
    console.log("Recieved /dashboard");
    dashboard.getDashboardInfo(req, res);
});

app.get("/u+p+d+a+t+e+t+o+d+o+", function(req, res) {
    console.log("Received /updatetodo");
    db.updateTodo(req, res);
});
<|endoftext|>


<commit_before>var five = require("johnny-five"),
	board, sensor;
var arDrone = require('ar-drone');
var events = require('events');
var util = require('util');
var history = [];
var KONAMI = ["up", "up", "down", "down", "left", "right", "left", "right", "b", "a"];
function isKonami() {
	var is = true;
	var kl = KONAMI.length;
	if(history < kl) { return false; }
	is = KONAMI.join() === history.reverse().join();
	return is;
}
function WiiDrone(opts) {
	opts = opts || {};
	this.started = false;
	this.client = new arDrone.createClient();
	// map incoming button events to ar-drone commands.
	this.buttonMap = {
		'x': 'up',
		'y': 'down',
		'up': 'front',
		'down': 'back',
		'left': 'left',
		'right': 'right',
		'zl': 'clockwise',
		'zr': 'counterClockwise'
	};
}
util.inherits(WiiDrone, events.EventEmitter);
WiiDrone.prototype.flip = function() {
	this.client.animate('flipLeft', 100);
	var backup = (function(that) {
		return function() { that.client.up(1);		}
	}(this));

	var respin = (function(that) {
		return function() { that.client.animate('flipRight', 100); }
	}(this));
	setTimeout(backup, 2400);
	setTimeout(respin, 4800);
}
WiiDrone.prototype.toggleStartStop = function() {
	if(this.started) {
		this.client.stop();
		this.client.land();
		this.emit('stop', null, this);
	} else {
		this.client.takeoff();
		this.emit('takeoff', null, this);
	}
	this.started = !this.started;
};
WiiDrone.prototype.handleUp = function(err, event) {
	var buttonId = event.target.which;
	if(this.buttonMap.hasOwnProperty(buttonId)) {
		this.client[this.buttonMap[buttonId]](0);
	} else {
		switch(buttonId) {
		case 'start':
			this.toggleStartStop();
			break;
		case 'r':
			this.flip();
			break;
		}
	}
	this.emit('up', err, event, buttonId, this);
}
WiiDrone.prototype.handleDown = function(err, event) {
	var buttonId = event.target.which;
	if(this.buttonMap.hasOwnProperty(buttonId)) {
		this.client[this.buttonMap[buttonId]](1);
	}
	this.emit('down', err, event, buttonId, this);
}
board = new five.Board({ debug: true});
board.on("ready", function() {
	var wiiDrone = new WiiDrone();
	var classicController = five.Nunchuk({ pins: ["A4", "A5"], freq: 100, device: "RVL-005" });
	board.repl.inject({
		sensor: classicController
	});
	classicController.on("up", function(err, event) {
		//console.log(event);
		history.unshift(event.target.which);
		history.length = KONAMI.length;
		if(isKonami()) {
			wiiDrone.flip();
		} else {
			wiiDrone.handleUp(err, event);
		}
	});
	classicController.on("down", function(err, event) { wiiDrone.handleDown(err, event);	});
});<commit_msg>Current instantiation.<commit_after>var five = require("johnny-five"),
	board, sensor;
var arDrone = require('ar-drone');
var events = require('events');
var util = require('util');
var history = [];
var KONAMI = ["up", "up", "down", "down", "left", "right", "left", "right", "b", "a"];
function isKonami() {
	var is = true;
	var kl = KONAMI.length;
	if(history < kl) { return false; }
	is = KONAMI.join() === history.reverse().join();
	console.log(is);
	return is;
}
function WiiDrone(opts) {
	opts = opts || {};
	this.started = false;
	this.client = new arDrone.createClient();
	// map incoming button events to ar-drone commands.
	this.buttonMap = {
		'x': 'up',
		'y': 'down',
		'up': 'front',
		'down': 'back',
		'left': 'left',
		'right': 'right',
		'l': 'counterClockwise',
		'r': 'clockwise'

	};
}
util.inherits(WiiDrone, events.EventEmitter);
WiiDrone.prototype.rightFlip = function() {
	this.client.animate('flipRight', 100);
}
WiiDrone.prototype.leftFlip = function() {
	this.client.animate('flipLeft', 100);
}
WiiDrone.prototype.toggleStartStop = function() {
	if(this.started) {
		this.client.stop();
		this.client.land();
		this.emit('stop', null, this);
	} else {
		this.client.takeoff();
		this.emit('takeoff', null, this);
	}
	this.started = !this.started;
};
WiiDrone.prototype.handleUp = function(err, event) {
	var buttonId = event.target.which;
	if(this.buttonMap.hasOwnProperty(buttonId)) {
		this.client[this.buttonMap[buttonId]](0);
	} else {
		switch(buttonId) {
		case 'start':
			this.toggleStartStop();
			break;
		}
	}
	this.emit('up', err, event, buttonId, this);
}
WiiDrone.prototype.handleDown = function(err, event) {
	var buttonId = event.target.which;
	if(this.buttonMap.hasOwnProperty(buttonId)) {
		this.client[this.buttonMap[buttonId]](1);
	}
	this.emit('down', err, event, buttonId, this);
}
board = new five.Board({ debug: true});
board.on("ready", function() {
	var wiiDrone = new WiiDrone();
	var classicController = five.Nunchuk({ pins: ["A4", "A5"], freq: 100, device: "RVL-005" });
	board.repl.inject({
		sensor: classicController
	});
	classicController.on("up", function(err, event) {
		console.log(event);
		history.unshift(event.target.which);
		history.length = KONAMI.length;
		if(event.target.which =='zl') {
			console.log("leftflip")
			wiiDrone.leftFlip();
		} else if(event.target.which =='zr') {
			console.log("rightflip")
			wiiDrone.rightFlip();
		} else {
			wiiDrone.handleUp(err, event);
		}
	});
	classicController.on("down", function(err, event) { wiiDrone.handleDown(err, event);	});
});<|endoftext|>


<commit_before>const pkg = require('../package.json');

module.exports = {
  ngVersion: '1.5.5',
  version: pkg.version,
  repository: pkg.repository.url
    .replace(/^git/,'https')
    .replace(/(\.git)?\/?$/,'')
};
<commit_msg>docs: update to Angular 1.6.7 (#11096)<commit_after>const pkg = require('../package.json');

module.exports = {
  ngVersion: '1.6.7',
  version: pkg.version,
  repository: pkg.repository.url
    .replace(/^git/,'https')
    .replace(/(\.git)?\/?$/,'')
};
<|endoftext|>