<commit_before>module.exports = {
	name: 'Hawken MacKay Rives',
	enrolled: 2012,
	graduation: 2016,

	creditsNeeded: 35,

	studies: [
		{
			id: 'ba', type: 'degree',
			abbr: 'B.A.', title: 'Bachelor of Arts',
		},
		{
			id: 'bm', type: 'degree',
			abbr: 'B.M.', title: 'Bachelor of Music',
		},
		{
			id: 'chmus', type: 'major',
			abbr: 'CHMUS', title: 'Church Music',
		},
		{
			id: 'csci', type: 'major',
			abbr: 'CSCI', title: 'Computer Science',
		},
		{
			id: 'asian', type: 'major',
			abbr: 'ASIAN', title: 'Asian Studies',
		},
		{
			id: 'japan', type: 'concentration',
			abbr: 'JAPAN', title: 'Japan Studies',
		},
		{
			id: 'math', type: 'concentration',
			abbr: 'MATH', title: 'Mathematics',
		},
	],

	schedules: [
		{
			id: 1, year: 2012, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [82908, 82768, 82792, 83505],
			active: true,
		},
		{
			id: 2, year: 2012, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [85898],
			active: true,
		},
		{
			id: 3, year: 2012, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [84512, 84461, 84378, 85991, 90802],
			active: true,
		},
		{
			id: 4, year: 2013, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [89090, 88273, 88681, 88593, 88630],
			active: true,
		},
		{
			id: 5, year: 2013, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [89466],
			active: true,
		},
		{
			id: 6, year: 2013, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [90719, 89957, 90339, 90172],
			active: true,
		},
		{
			id: 7, year: 2014, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [97217, 97120, 97119, 97125],
			active: true,
		},
		{
			id: 8, year: 2014, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [97261],
			active: true,
		},
		{
			id: 9, year: 2014, semester: 2,
			title: 'Schedule 2', sequence: 2,
			clbids: [97174],
			active: false,
		},
		{
			id: 10, year: 2014, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [95594, 95842],
			active: true,
		},
		{
			id: 11, year: 2015, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [92908, 97122],
			active: true,
		},
		{
			id: 12, year: 2015, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [],
			active: true,
		},
		{
			id: 13, year: 2015, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [91746, 96980],
			active: true,
		},
		{
			id: 14, year: 2012, semester: 1,
			title: 'Schedule 2', sequence: 2,
			clbids: [12346, 12459, 13460, 17358],
		},
	],

	overrides: [
		{
			what: 'credits',
			with: 1
		}
	]
}
<commit_msg>Add an emphasis to demo_student<commit_after>module.exports = {
	name: 'Hawken MacKay Rives',
	enrolled: 2012,
	graduation: 2016,

	creditsNeeded: 35,

	studies: [
		{
			id: 'ba', type: 'degree',
			abbr: 'B.A.', title: 'Bachelor of Arts',
		},
		{
			id: 'bm', type: 'degree',
			abbr: 'B.M.', title: 'Bachelor of Music',
		},
		{
			id: 'chmus', type: 'major',
			abbr: 'CHMUS', title: 'Church Music',
		},
		{
			id: 'csci', type: 'major',
			abbr: 'CSCI', title: 'Computer Science',
		},
		{
			id: 'asian', type: 'major',
			abbr: 'ASIAN', title: 'Asian Studies',
		},
		{
			id: 'japan', type: 'concentration',
			abbr: 'JAPAN', title: 'Japan Studies',
		},
		{
			id: 'math', type: 'concentration',
			abbr: 'MATH', title: 'Mathematics',
		},
		{
			id: 'management', type: 'emphasis',
			abbr: 'MGMT', title: 'Management',
		}
	],

	schedules: [
		{
			id: 1, year: 2012, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [82908, 82768, 82792, 83505],
			active: true,
		},
		{
			id: 2, year: 2012, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [85898],
			active: true,
		},
		{
			id: 3, year: 2012, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [84512, 84461, 84378, 85991, 90802],
			active: true,
		},
		{
			id: 4, year: 2013, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [89090, 88273, 88681, 88593, 88630],
			active: true,
		},
		{
			id: 5, year: 2013, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [89466],
			active: true,
		},
		{
			id: 6, year: 2013, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [90719, 89957, 90339, 90172],
			active: true,
		},
		{
			id: 7, year: 2014, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [97217, 97120, 97119, 97125],
			active: true,
		},
		{
			id: 8, year: 2014, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [97261],
			active: true,
		},
		{
			id: 9, year: 2014, semester: 2,
			title: 'Schedule 2', sequence: 2,
			clbids: [97174],
			active: false,
		},
		{
			id: 10, year: 2014, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [95594, 95842],
			active: true,
		},
		{
			id: 11, year: 2015, semester: 1,
			title: 'Schedule 1', sequence: 1,
			clbids: [92908, 97122],
			active: true,
		},
		{
			id: 12, year: 2015, semester: 2,
			title: 'Schedule 1', sequence: 1,
			clbids: [],
			active: true,
		},
		{
			id: 13, year: 2015, semester: 3,
			title: 'Schedule 1', sequence: 1,
			clbids: [91746, 96980],
			active: true,
		},
		{
			id: 14, year: 2012, semester: 1,
			title: 'Schedule 2', sequence: 2,
			clbids: [12346, 12459, 13460, 17358],
		},
	],

	overrides: [
		{
			what: 'credits',
			with: 1
		}
	]
}
<|endoftext|>


<commit_before>// Workaround for missing functionality in IE 8 and earlier.
if( Object.create === undefined ) {
	Object.create = function( o ) {
	    function F(){}
	    F.prototype = o;
	    return new F();
	};
}

CodeMirror.defineMode("haskell", function(_config, modeConfig) {

  function switchState(source, setState, f) {
    setState(f);
    return f(source, setState);
  }

  // These should all be Unicode extended, as per the Haskell 2010 report
  var smallRE = /[a-z_]/;
  var largeRE = /[A-Z]/;
  var digitRE = /[0-9]/;
  var hexitRE = /[0-9A-Fa-f]/;
  var octitRE = /[0-7]/;
  var qualRE = /[a-z_A-Z0-9'\.]*\./;
  var idRE = /[a-z_A-Z0-9']/;
  var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
  var specialRE = /[(),;[\]`{}]/;
  var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer

  function normal(source, setState) {
    if (source.eatWhile(whiteCharRE)) {
      return null;
    }

    var ch = source.next();
    if (specialRE.test(ch)) {
      if (ch == '{' && source.eat('-')) {
        var t = "comment";
        if (source.eat('#')) {
          t = "meta";
        }
        return switchState(source, setState, ncomment(t, 1));
      }
      return null;
    }

    if (ch == '\'') {
      if (source.eat('\\')) {
        source.next();  // should handle other escapes here
      }
      else {
        source.next();
      }
      if (source.eat('\'')) {
        return "string";
      }
      return "error";
    }

    if (ch == '"') {
      return switchState(source, setState, stringLiteral);
    }

    if (largeRE.test(ch) && source.match(qualRE)) {
      return "qualifier";
    }
    if (largeRE.test(ch)) {
      source.eatWhile(idRE);
      return "variable-2";
    }

    if (smallRE.test(ch)) {
      source.eatWhile(idRE);
      return "variable";
    }

    if (digitRE.test(ch)) {
      if (ch == '0') {
        if (source.eat(/[xX]/)) {
          source.eatWhile(hexitRE); // should require at least 1
          return "integer";
        }
        if (source.eat(/[oO]/)) {
          source.eatWhile(octitRE); // should require at least 1
          return "number";
        }
      }
      source.eatWhile(digitRE);
      var t = "number";
      if (source.eat('.')) {
        t = "number";
        source.eatWhile(digitRE); // should require at least 1
      }
      if (source.eat(/[eE]/)) {
        t = "number";
        source.eat(/[-+]/);
        source.eatWhile(digitRE); // should require at least 1
      }
      return t;
    }

    if (symbolRE.test(ch)) {
      if (ch == '-' && source.eat(/-/)) {
        source.eatWhile(/-/);
        if (!source.eat(symbolRE)) {
          source.skipToEnd();
          return "comment";
        }
      }
      var t = "operator";
      if (ch == ':') {
        t = "operator-2";
      }
      source.eatWhile(symbolRE);
      return t;
    }

    return "error";
  }

  function ncomment(type, nest) {
    if (nest == 0) {
      return normal;
    }
    return function(source, setState) {
      var currNest = nest;
      while (!source.eol()) {
        var ch = source.next();
        if (ch == '{' && source.eat('-')) {
          ++currNest;
        }
        else if (ch == '-' && source.eat('}')) {
          --currNest;
          if (currNest == 0) {
            setState(normal);
            return type;
          }
        }
      }
      setState(ncomment(type, currNest));
      return type;
    };
  }

  function stringLiteral(source, setState) {
    while (!source.eol()) {
      var ch = source.next();
      if (ch == '"') {
        setState(normal);
        return "string";
      }
      if (ch == '\\') {
        if (source.eol() || source.eat(whiteCharRE)) {
          setState(stringGap);
          return "string";
        }
        if (source.eat('&')) {
        }
        else {
          source.next(); // should handle other escapes here
        }
      }
    }
    setState(normal);
    return "error";
  }

  function stringGap(source, setState) {
    if (source.eat('\\')) {
      return switchState(source, setState, stringLiteral);
    }
    source.next();
    setState(normal);
    return "error";
  }

  var wellKnownWords = (function() {
    var wkw = Object.create(null);
    function setType(t) {
      return function () {
        for (var i = 0; i < arguments.length; i++)
          wkw[arguments[i]] = t;
      };
    }

    setType("keyword")(
      "case", "class", "data", "default", "deriving", "do", "else", "foreign",
      "if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
      "module", "newtype", "of", "then", "type", "where", "_");

    setType("keyword")(
      "\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>");

    setType("builtin")(
      "!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<",
      "==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "**");

    setType("builtin")(
      "Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq",
      "False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT",
      "IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
      "Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
      "ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
      "String", "True");

    setType("builtin")(
      "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
      "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
      "compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
      "cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
      "elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
      "flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
      "foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
      "fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
      "getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
      "isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
      "lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
      "mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
      "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
      "otherwise", "pi", "pred", "print", "product", "properFraction",
      "putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
      "readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
      "realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
      "sequence", "sequence_", "show", "showChar", "showList", "showParen",
      "showString", "shows", "showsPrec", "significand", "signum", "sin",
      "sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
      "tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
      "toRational", "truncate", "uncurry", "undefined", "unlines", "until",
      "unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
      "zip3", "zipWith", "zipWith3");

    var override = modeConfig.overrideKeywords;
    if (override) for (var word in override) if (override.hasOwnProperty(word))
      wkw[word] = override[word];

    return wkw;
  })();

  return {
    startState: function ()  { return { f: normal }; },
    copyState:  function (s) { return { f: s.f }; },

    token: function(stream, state) {
      var t = state.f(stream, function(s) { state.f = s; });
      var w = stream.current();
      return (w in wellKnownWords) ? wellKnownWords[w] : t;
    },

    blockCommentStart: "{-",
    blockCommentEnd: "-}",
    lineComment: "--"
  };

});

CodeMirror.defineMIME("text/x-haskell", "haskell");
<commit_msg>The concept of highlighting Prelude as "builtins" doesn't seem very haskell-ey<commit_after>// Workaround for missing functionality in IE 8 and earlier.
if( Object.create === undefined ) {
	Object.create = function( o ) {
	    function F(){}
	    F.prototype = o;
	    return new F();
	};
}

CodeMirror.defineMode("haskell", function(_config, modeConfig) {

  function switchState(source, setState, f) {
    setState(f);
    return f(source, setState);
  }

  // These should all be Unicode extended, as per the Haskell 2010 report
  var smallRE = /[a-z_]/;
  var largeRE = /[A-Z]/;
  var digitRE = /[0-9]/;
  var hexitRE = /[0-9A-Fa-f]/;
  var octitRE = /[0-7]/;
  var qualRE = /[a-z_A-Z0-9'\.]*\./;
  var idRE = /[a-z_A-Z0-9']/;
  var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
  var specialRE = /[(),;[\]`{}]/;
  var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer

  function normal(source, setState) {
    if (source.eatWhile(whiteCharRE)) {
      return null;
    }

    var ch = source.next();
    if (specialRE.test(ch)) {
      if (ch == '{' && source.eat('-')) {
        var t = "comment";
        if (source.eat('#')) {
          t = "meta";
        }
        return switchState(source, setState, ncomment(t, 1));
      }
      return null;
    }

    if (ch == '\'') {
      if (source.eat('\\')) {
        source.next();  // should handle other escapes here
      }
      else {
        source.next();
      }
      if (source.eat('\'')) {
        return "string";
      }
      return "error";
    }

    if (ch == '"') {
      return switchState(source, setState, stringLiteral);
    }

    if (largeRE.test(ch) && source.match(qualRE)) {
      return "qualifier";
    }
    if (largeRE.test(ch)) {
      source.eatWhile(idRE);
      return "variable-2";
    }

    if (smallRE.test(ch)) {
      source.eatWhile(idRE);
      return "variable";
    }

    if (digitRE.test(ch)) {
      if (ch == '0') {
        if (source.eat(/[xX]/)) {
          source.eatWhile(hexitRE); // should require at least 1
          return "integer";
        }
        if (source.eat(/[oO]/)) {
          source.eatWhile(octitRE); // should require at least 1
          return "number";
        }
      }
      source.eatWhile(digitRE);
      var t = "number";
      if (source.eat('.')) {
        t = "number";
        source.eatWhile(digitRE); // should require at least 1
      }
      if (source.eat(/[eE]/)) {
        t = "number";
        source.eat(/[-+]/);
        source.eatWhile(digitRE); // should require at least 1
      }
      return t;
    }

    if (symbolRE.test(ch)) {
      if (ch == '-' && source.eat(/-/)) {
        source.eatWhile(/-/);
        if (!source.eat(symbolRE)) {
          source.skipToEnd();
          return "comment";
        }
      }
      var t = "operator";
      if (ch == ':') {
        t = "operator-2";
      }
      source.eatWhile(symbolRE);
      return t;
    }

    return "error";
  }

  function ncomment(type, nest) {
    if (nest == 0) {
      return normal;
    }
    return function(source, setState) {
      var currNest = nest;
      while (!source.eol()) {
        var ch = source.next();
        if (ch == '{' && source.eat('-')) {
          ++currNest;
        }
        else if (ch == '-' && source.eat('}')) {
          --currNest;
          if (currNest == 0) {
            setState(normal);
            return type;
          }
        }
      }
      setState(ncomment(type, currNest));
      return type;
    };
  }

  function stringLiteral(source, setState) {
    while (!source.eol()) {
      var ch = source.next();
      if (ch == '"') {
        setState(normal);
        return "string";
      }
      if (ch == '\\') {
        if (source.eol() || source.eat(whiteCharRE)) {
          setState(stringGap);
          return "string";
        }
        if (source.eat('&')) {
        }
        else {
          source.next(); // should handle other escapes here
        }
      }
    }
    setState(normal);
    return "error";
  }

  function stringGap(source, setState) {
    if (source.eat('\\')) {
      return switchState(source, setState, stringLiteral);
    }
    source.next();
    setState(normal);
    return "error";
  }

  var wellKnownWords = (function() {
    var wkw = Object.create(null);
    function setType(t) {
      return function () {
        for (var i = 0; i < arguments.length; i++)
          wkw[arguments[i]] = t;
      };
    }

    setType("keyword")(
      "case", "class", "data", "default", "deriving", "do", "else", "foreign",
      "if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
      "module", "newtype", "of", "then", "type", "where", "_");

    setType("keyword")(
      "\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>");

    /*
    setType("builtin")(
      "!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<",
      "==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "**");

    setType("builtin")(
      "Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq",
      "False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT",
      "IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
      "Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
      "ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
      "String", "True");

    setType("builtin")(
      "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
      "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
      "compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
      "cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
      "elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
      "flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
      "foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
      "fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
      "getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
      "isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
      "lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
      "mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
      "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
      "otherwise", "pi", "pred", "print", "product", "properFraction",
      "putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
      "readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
      "realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
      "sequence", "sequence_", "show", "showChar", "showList", "showParen",
      "showString", "shows", "showsPrec", "significand", "signum", "sin",
      "sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
      "tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
      "toRational", "truncate", "uncurry", "undefined", "unlines", "until",
      "unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
      "zip3", "zipWith", "zipWith3");

    var override = modeConfig.overrideKeywords;
    if (override) for (var word in override) if (override.hasOwnProperty(word))
      wkw[word] = override[word];

    */

    return wkw;
  })();

  return {
    startState: function ()  { return { f: normal }; },
    copyState:  function (s) { return { f: s.f }; },

    token: function(stream, state) {
      var t = state.f(stream, function(s) { state.f = s; });
      var w = stream.current();
      return (w in wellKnownWords) ? wellKnownWords[w] : t;
    },

    blockCommentStart: "{-",
    blockCommentEnd: "-}",
    lineComment: "--"
  };

});

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


<commit_before>var extend = require("extend");

var p = function(core, config, state) {
  var self = this;
  this.core = core;
  this.config = config;
  this.state = state;

  self.core.on("penalize.minor", function(nick, reason) {
    self.penalize("minor", nick, reason);
  });

  self.core.on("penalize.major", function(nick, reason) {
    self.penalize("major", nick, reason);
  });

  self.core.on("penalize.mute", function(nick, duration, reason) {
    self.core.send("MUTE", {
      duration: duration * 1000000, // the chat server deals with nanoseconds, so multiply it up
      data: nick
    });

    // format the duration as a timestamp, in the simplest way possible
    var time = "";
    var days = Math.floor(duration / (24 * 60 * 60 * 1000));
    if (days > 0) {
      time += days + " days ";
      duration -= days * 24 * 60 * 60 * 1000;
    }

    var hours = Math.floor(duration / (60 * 60 * 1000));
    if (hours > 0) {
      time += hours + "h ";
      duration -= hours * 60 * 60 * 1000;
    }

    var minutes = Math.floor(duration / (60 * 1000));
    if (minutes > 0)
      time = time + minutes + "m";

    time = time.trim();
    self.core.say(time + " " + nick + ": " + reason);
  });

  self.core.on("penalize.unmute", function(nick) {
    self.core.send("UNMUTE", {
      data: nick
    });
  });

  self.penalize = function(type, nick, reason) {
    var now = Date.now();
    var settings = config[type];
    var record = {
      score: 0,
      lastinfraction: 0,
      numberofinfractions: 0
    };

    if (state.nicks[nick])
      record = extend(record, state.nicks[nick]);

    record.lastinfraction = now;
    record.numberofinfractions += 1;

    if (!record.score)
      record.score = settings.def;
    else
      record.score = record.score * settings.mul;

    state.nicks[nick] = record;
    self.core.emit("penalize.mute", nick, record.score, reason);
  };

  self.decayScores = function(penalties, settings) {
    var now = Date.now();
    for (var nick in penalties) {
      if (!penalties.hasOwnProperty(nick))
        continue;

      var record = penalties[nick];
      if (!record.score || now - record.lastinfraction < settings.decayafter)
        return;

      // add it back, so that we can decrease it again after decayafter time passes
      record.lastinfraction = now;
      record.score = Math.round(record.score / settings.decayby);
      if (record.score <= settings.def)
        record.score = 0;

    };
  }.bind(self);

  setInterval(function() {
    self.decayScores(state.minor, config.minor);
    self.decayScores(state.major, config.major);
  }, 60 * 1000);
};

module.exports = {
  init: p,
  config,
  {
    minor: {
      def: 60 * 1000, // default 1 minute mute
      mul: 5, // every other infraction will multiply it by this much
      decayafter: 60 * 60 * 1000, // penalties start decaying after an hour
      decayby: 5 // the number of miliseconds is divided by this number after decaying
    },
    major: {
      def: 5 * 60 * 1000, // 5 min
      mul: 5,
      decayafter: 24 * 60 * 60 * 1000, // 24h
      decayby: 5
    }
  },
  state: {
    minor: {},
    major: {}
  }
};
<commit_msg>fix penalize plugin typo<commit_after>var extend = require("extend");

var p = function(core, config, state) {
  var self = this;
  this.core = core;
  this.config = config;
  this.state = state;

  self.core.on("penalize.minor", function(nick, reason) {
    self.penalize("minor", nick, reason);
  });

  self.core.on("penalize.major", function(nick, reason) {
    self.penalize("major", nick, reason);
  });

  self.core.on("penalize.mute", function(nick, duration, reason) {
    self.core.send("MUTE", {
      duration: duration * 1000000, // the chat server deals with nanoseconds, so multiply it up
      data: nick
    });

    // format the duration as a timestamp, in the simplest way possible
    var time = "";
    var days = Math.floor(duration / (24 * 60 * 60 * 1000));
    if (days > 0) {
      time += days + " days ";
      duration -= days * 24 * 60 * 60 * 1000;
    }

    var hours = Math.floor(duration / (60 * 60 * 1000));
    if (hours > 0) {
      time += hours + "h ";
      duration -= hours * 60 * 60 * 1000;
    }

    var minutes = Math.floor(duration / (60 * 1000));
    if (minutes > 0)
      time = time + minutes + "m";

    time = time.trim();
    self.core.say(time + " " + nick + ": " + reason);
  });

  self.core.on("penalize.unmute", function(nick) {
    self.core.send("UNMUTE", {
      data: nick
    });
  });

  self.penalize = function(type, nick, reason) {
    var now = Date.now();
    var settings = config[type];
    var record = {
      score: 0,
      lastinfraction: 0,
      numberofinfractions: 0
    };

    if (state.nicks[nick])
      record = extend(record, state.nicks[nick]);

    record.lastinfraction = now;
    record.numberofinfractions += 1;

    if (!record.score)
      record.score = settings.def;
    else
      record.score = record.score * settings.mul;

    state.nicks[nick] = record;
    self.core.emit("penalize.mute", nick, record.score, reason);
  };

  self.decayScores = function(penalties, settings) {
    var now = Date.now();
    for (var nick in penalties) {
      if (!penalties.hasOwnProperty(nick))
        continue;

      var record = penalties[nick];
      if (!record.score || now - record.lastinfraction < settings.decayafter)
        return;

      // add it back, so that we can decrease it again after decayafter time passes
      record.lastinfraction = now;
      record.score = Math.round(record.score / settings.decayby);
      if (record.score <= settings.def)
        record.score = 0;

    };
  }.bind(self);

  setInterval(function() {
    self.decayScores(state.minor, config.minor);
    self.decayScores(state.major, config.major);
  }, 60 * 1000);
};

module.exports = {
  init: p,
  config: {
    minor: {
      def: 60 * 1000, // default 1 minute mute
      mul: 5, // every other infraction will multiply it by this much
      decayafter: 60 * 60 * 1000, // penalties start decaying after an hour
      decayby: 5 // the number of miliseconds is divided by this number after decaying
    },
    major: {
      def: 5 * 60 * 1000, // 5 min
      mul: 5,
      decayafter: 24 * 60 * 60 * 1000, // 24h
      decayby: 5
    }
  },
  state: {
    minor: {},
    major: {}
  }
};
<|endoftext|>


<commit_before>const searchInput = document.querySelector('input[type="search"]');
const tabList = document.querySelector('.tab-list');
// Initialize window
// getAllTabs().then(injectTabsInList);

tabList.addEventListener('click', switchTabs);
searchInput.addEventListener('change', updateSearch);
searchInput.addEventListener('keyup', updateSearch);

function getAllTabs() {
  return browser.tabs.query({ currentWindow: true });
}

function updateSearch(event) {
  const query = event.target.value.toLowerCase();
  const tabFilter = tab => tab.title.includes(query);
  return getAllTabs()
    .then(tabArray => tabArray.filter(tabFilter))
    .then(injectTabsInList);
}

function injectTabsInList(tabArray) {
  tabList.innerHTML = tabArray.map(tabToTag).join('');
}

// Got to make this an onClick event that switches tab
function tabToTag(tab) {
  return `

        ${tab.title}

  `;
}

function switchTabs(event) {
  if (event.target.className !== 'tab-link') return;
  event.preventDefault();
  const tabId = parseInt(event.target.dataset.id);
  browser.tabs.update(tabId, { active: true });
}

// To switch tabs
// onClick -> tabs.update(tab.id, { active: true })
<commit_msg>Search against lowercased titles<commit_after>const searchInput = document.querySelector('input[type="search"]');
const tabList = document.querySelector('.tab-list');

// Initialize tabs

{
  getAllTabs().then(injectTabsInList);
}

tabList.addEventListener('click', switchTabs);
searchInput.addEventListener('change', updateSearch);
searchInput.addEventListener('keyup', updateSearch);

function getAllTabs() {
  return browser.tabs.query({ currentWindow: true });
}

function updateSearch(event) {
  const query = event.target.value.toLowerCase();
  const tabFilter = tab => tab.title.toLowerCase().includes(query);
  return getAllTabs()
    .then(tabArray => tabArray.filter(tabFilter))
    .then(injectTabsInList);
}

function injectTabsInList(tabArray) {
  tabList.innerHTML = tabArray.map(tabToTag).join('');
}

// Got to make this an onClick event that switches tab
function tabToTag(tab) {
  return `

        ${tab.title}

  `;
}

function switchTabs(event) {
  if (event.target.className !== 'tab-link') return;
  event.preventDefault();
  const tabId = parseInt(event.target.dataset.id);
  browser.tabs.update(tabId, { active: true });
}

// To switch tabs
// onClick -> tabs.update(tab.id, { active: true })
<|endoftext|>


<commit_before>// When an error occurs
function errorFn(msg, trace) {
  // Log the error and trace
  console.error(msg);
  trace.forEach(function(item) {
      console.error('  ', item.file, ':', item.line);
  });

  // Leave with a bad exit code
  phantom.exit(1);
}
phantom.onError = errorFn;

// Load in dependencies
var system = require('system'),
    webpage = require('webpage');

// Create a webpage
var page = webpage.create();
page.onError = errorFn;

// Grab the arguments
var args = system.args,
    username = args[1];

// If there is no image, throw an error
if (!username) {
  throw new Error('No username was specified.');
}

// Count the resources as they load
var resourceCount = 0,
    resourceExpected = 4; // index.html, light font, heavy font, heart.git
page.onResourceReceived = function (response) {
  if (response.stage === 'end') {
    resourceCount += 1;
  }
};

// Load the screenshot page
var __dirname = phantom.libraryPath;
page.open(__dirname + '/index.html?' + username, function (status) {
  // Wait until the canvas has rendered
  function checkCanvas() {
    // Determine if the canvas is rendered
    var canvasRendered = page.evaluate(function () {
          return window.canvasRendered;
        });

    // console.log('checking', canvasRendered);
    // If it has not, check again in 100ms
    if (!canvasRendered || resourceCount < resourceExpected) {
      return setTimeout(checkCanvas, 100);
    }

    // Grab the canvas contents and echo
    var dataPng = page.evaluate(function () {
          var canvas = document.getElementById('canvas');
          return canvas.toDataURL();
        }),
        // 'data:image/png;base64,iVBORw0KGgoAAAANS...'
        // 'data:image/png;base64,'.length === 22
        png = dataPng.slice(22);
    console.log(png);

    // Leave gracefully
    phantom.exit(0);
  }
  checkCanvas();
});

// Set up a timeout to autokill
setTimeout(function () {
  console.error('Timeout occurred at 2 seconds.');
  phantom.exit(1);
}, 2000);<commit_msg>...and down to 2 resources<commit_after>// When an error occurs
function errorFn(msg, trace) {
  // Log the error and trace
  console.error(msg);
  trace.forEach(function(item) {
      console.error('  ', item.file, ':', item.line);
  });

  // Leave with a bad exit code
  phantom.exit(1);
}
phantom.onError = errorFn;

// Load in dependencies
var system = require('system'),
    webpage = require('webpage');

// Create a webpage
var page = webpage.create();
page.onError = errorFn;

// Grab the arguments
var args = system.args,
    username = args[1];

// If there is no image, throw an error
if (!username) {
  throw new Error('No username was specified.');
}

// Count the resources as they load
var resourceCount = 0,
    resourceExpected = 2; // index.html, heart.gif
page.onResourceReceived = function (response) {
  if (response.stage === 'end') {
    resourceCount += 1;
  }
};

// Load the screenshot page
var __dirname = phantom.libraryPath;
page.open(__dirname + '/index.html?' + username, function (status) {
  // Wait until the canvas has rendered
  function checkCanvas() {
    // Determine if the canvas is rendered
    var canvasRendered = page.evaluate(function () {
          return window.canvasRendered;
        });

    // console.log('checking', canvasRendered);
    // If it has not, check again in 100ms
    if (!canvasRendered || resourceCount < resourceExpected) {
      return setTimeout(checkCanvas, 100);
    }

    // Grab the canvas contents and echo
    var dataPng = page.evaluate(function () {
          var canvas = document.getElementById('canvas');
          return canvas.toDataURL();
        }),
        // 'data:image/png;base64,iVBORw0KGgoAAAANS...'
        // 'data:image/png;base64,'.length === 22
        png = dataPng.slice(22);
    console.log(png);

    // Leave gracefully
    phantom.exit(0);
  }
  checkCanvas();
});

// Set up a timeout to autokill
setTimeout(function () {
  console.error('Timeout occurred at 2 seconds.');
  phantom.exit(1);
}, 2000);<|endoftext|>


<commit_before>var template = require('./template');
var View = require('view');
var dom = require('dom');
var Quill = require('quill');

var defaults = {
  toolbar: {
    fontFace: false,
    fontSize: false,
    fontWidth: true
  },
  theme: 'snow'
};

module.exports = RichTextView;

function RichTextView(el, options) {
  if (!(this instanceof RichTextView)) {
    return new RichTextView(el, options);
  }

  // The original input or textarea element
  this.input = 'string' === typeof el ? dom(el) : el;

  // Settings merged with options provided by callee
  // fixme: i can't find a component that extends the defaults object with the options object.
  //this.settings = options || {};
  this.settings = defaults;

  View.call(this, template, this.settings);

  this.editor = new Quill(this.find('#editor')[0], {
    modules: {
      'toolbar': { container: this.find('#toolbar')[0] },
      'link-tooltip': true,
      'image-tooltip': true
    },
    theme: this.settings.theme
  });

  this.editor.setHTML(this.input.val());
};

View(RichTextView);

RichTextView.prototype.switchOn = function() {
  this.editor.on('text-change', this.bound('ontextchange'));
};

RichTextView.prototype.ontextchange = function(delta, source) {
  var contents = this.editor.getHTML();
  this.input.val(contents);
};

RichTextView.prototype.render = function() {
  if (this.input) {
    this.input.addClass('hide');
    this.el.insertAfter(this.input);
  }

  return View.prototype.render.call(this);
};<commit_msg>[richtext] Fixed bug when rendering against empty textarea #438<commit_after>var template = require('./template');
var View = require('view');
var dom = require('dom');
var Quill = require('quill');

var defaults = {
  toolbar: {
    fontFace: false,
    fontSize: false,
    fontWidth: true
  },
  theme: 'snow'
};

module.exports = RichTextView;

function RichTextView(el, options) {
  if (!(this instanceof RichTextView)) {
    return new RichTextView(el, options);
  }

  // The original input or textarea element
  this.input = 'string' === typeof el ? dom(el) : el;

  // Settings merged with options provided by callee
  // fixme: i can't find a component that extends the defaults object with the options object.
  //this.settings = options || {};
  this.settings = defaults;

  View.call(this, template, this.settings);

  this.editor = new Quill(this.find('#editor')[0], {
    modules: {
      'toolbar': { container: this.find('#toolbar')[0] },
      'link-tooltip': true,
      'image-tooltip': true
    },
    theme: this.settings.theme
  });

  if (this.input.val()) this.editor.setHTML(this.input.val());
  this.render();
};

View(RichTextView);

RichTextView.prototype.switchOn = function() {
  this.editor.on('text-change', this.bound('ontextchange'));
};

RichTextView.prototype.ontextchange = function(delta, source) {
  var contents = this.editor.getHTML();
  this.input.val(contents);
};

RichTextView.prototype.render = function() {
  if (this.input) {
    this.input.addClass('hide');
    this.el.insertAfter(this.input);
  }

  return View.prototype.render.call(this);
};<|endoftext|>


<commit_before>/**
 * Upwork auth library for using with public API by OAuth
 *
 * @package     UpworkAPI
 * @since       09/23/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

/**
 * @module routes.workdiary
 */

/**
 * @property entryPoint
 * @type String
 * @default api
 * @static
 * @final
 */
var entryPoint = 'api';

/**
 * @class Workdiary
 * @constructor
 */
exports.Workdiary = function(api) {
  this.api = api;
  this.api.epoint = entryPoint;
}

/**
 * Get Workdiary
 *
 * @method get
 * @param company {String} Company
 * @param username {String} Username
 * @param date {String} Date
 * @param params {Hash} Parameters
 * @param callback {String} Callback function
 * @async
 */
exports.Workdiary.prototype.get = function(company, username, date, params, callback) {
  debug('running request');
  this.api.client.get('team/v1/workdiaries/' + company + '/' + username + '/' + date, params, callback);
}

/**
 * Get Work Diary by Contract
 *
 * @method getByContract
 * @param contract {String} Contract ID
 * @param date {String} Date
 * @param params {Hash} Parameters
 * @param callback {String} Callback function
 * @async
 */
exports.Workdiary.prototype.getByContract = function(contract, date, params, callback) {
  debug('running request');
  this.api.client.get('team/v1/workdiaries/contracts/' + contract + '/' + date, params, callback);
}
<commit_msg>fix wrong url version in workdiary getByContract<commit_after>/**
 * Upwork auth library for using with public API by OAuth
 *
 * @package     UpworkAPI
 * @since       09/23/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

/**
 * @module routes.workdiary
 */

/**
 * @property entryPoint
 * @type String
 * @default api
 * @static
 * @final
 */
var entryPoint = 'api';

/**
 * @class Workdiary
 * @constructor
 */
exports.Workdiary = function(api) {
  this.api = api;
  this.api.epoint = entryPoint;
}

/**
 * Get Workdiary
 *
 * @method get
 * @param company {String} Company
 * @param username {String} Username
 * @param date {String} Date
 * @param params {Hash} Parameters
 * @param callback {String} Callback function
 * @async
 */
exports.Workdiary.prototype.get = function(company, username, date, params, callback) {
  debug('running request');
  this.api.client.get('team/v1/workdiaries/' + company + '/' + username + '/' + date, params, callback);
}

/**
 * Get Work Diary by Contract
 *
 * @method getByContract
 * @param contract {String} Contract ID
 * @param date {String} Date
 * @param params {Hash} Parameters
 * @param callback {String} Callback function
 * @async
 */
exports.Workdiary.prototype.getByContract = function(contract, date, params, callback) {
  debug('running request');
  this.api.client.get('team/v2/workdiaries/contracts/' + contract + '/' + date, params, callback);
}
<|endoftext|>


<commit_before>var fs = require("fs");
var log = require("ringo/logging").getLogger(module.id);
var compress = require("./compress");
var registry = require("./registry");

export("isActivated", "isInstalled", "install", "uninstall", "activate",
        "deactivate", "getDescriptor", "getPackagesDir", "getInstallDir",
        "resolveDependencies");

function getInstallDir(name, version) {
    var dir = fs.join(system.prefix, "packages.available");
    if (name && version) {
        dir = fs.join(dir, name + "-" + version);
    }
    return dir;
}

function getPackagesDir() {
    return fs.join(system.prefix, "packages");
}

function isInstalled(name, version) {
    return fs.exists(getInstallDir(name, version));
}

function isActivated(name) {
    return fs.exists(fs.join(getPackagesDir(), name));
}

function getDescriptor(dir) {
    var jsonPath = fs.join(dir, "package.json");
    if (fs.exists(jsonPath)) {
        return JSON.parse(fs.read(jsonPath));
    }
    return null;
}

function install(archivePath, name, version) {
    var installDir = getInstallDir(name, version);
    log.debug("Installing", fs.base(archivePath), "in", installDir);
    if (!fs.exists(installDir)) {
        fs.makeTree(installDir);
        var fileStream = fs.open(archivePath, {
            "binary": true
        });
        compress.extractStream(fileStream, installDir);
        log.debug("Installed", name, " " + version + " in", fs.absolute(installDir));
    }
    return installDir;
}

function uninstall(name, version) {
    var installDir = getInstallDir(name, version);
    if (!fs.exists(installDir)) {
        throw new Error("The package " + name + " " + version + " isn't installed")
    }
    fs.removeTree(installDir);
    return installDir;
}

function activate(name, version) {
    var installDir = getInstallDir(name, version);
    if (!fs.exists(installDir)) {
        throw new Error("The package " + name + " " + version + " isn't installed");
    }
    var src = fs.relative(fs.join(system.prefix, "packages/"), installDir);
    var dest = fs.join(getPackagesDir(), name);
    if (fs.exists(dest)) {
        // bail out if link points to a different package version
        var activePackage = getDescriptor(fs.readLink(dest));
        if (activePackage != null && activePackage.version != version) {
            throw new Error("A different version (" + activePackage.version +
                    ") of package " + name +
                    " is currently active, please clean up manually");
        }
        fs.remove(dest);
    }
    fs.symbolicLink(src, dest);
    log.debug("Activated package", name);
    return dest;
}

function deactivate(name) {
    var path = fs.join(getPackagesDir(), name);
    if (!fs.exists(path)) {
        throw new Error("The package" + name + " is not activated");
    } else if (!fs.isLink(path)) {
        throw new Error("Package " + name +
                " has been copied into packages directory, please move it away manually");
    }
    fs.remove(path);
    return;
}

function resolveDependencies(descriptor, queue, map) {
    queue = queue || [];
    map = map || {};
    queue.push(descriptor);
    if (descriptor.dependencies != undefined) {
        var depNames = Object.keys(descriptor.dependencies).sort();
        for each (var depName in depNames) {
            var depVersion = descriptor.dependencies[depName];
            if (map.hasOwnProperty(depName)) {
                if (!semver.satisfies(depVersion, map[depName].version)) {
                    throw new Error("Dependency conflict: " + descriptor.name +
                            " depends on " + depName + " " + depVersion +
                            ", but " + map[depName].requiredBy +
                            " requires version " + map[depName].version);
                } else if (semver.isGreaterOrEqual(map[depName].version, depVersion)) {
                    // we already have a greater or equal version, continue
                    continue;
                }
            }
            var depDescriptor = registry.getPackageDescriptor(depName, depVersion);
            if (!depDescriptor) {
                throw new Error("Required package " + depName + " " +
                        depVersion + " doesn't exist in registry");
            }
            map[depDescriptor.name] = {
                "version": depDescriptor.version,
                "requiredBy": descriptor.name
            };
            resolveDependencies(depDescriptor, queue, map);
        };
    }
    return queue;
}
<commit_msg>added FIXME<commit_after>var fs = require("fs");
var log = require("ringo/logging").getLogger(module.id);
var compress = require("./compress");
var registry = require("./registry");

export("isActivated", "isInstalled", "install", "uninstall", "activate",
        "deactivate", "getDescriptor", "getPackagesDir", "getInstallDir",
        "resolveDependencies");

function getInstallDir(name, version) {
    var dir = fs.join(system.prefix, "packages.available");
    if (name && version) {
        dir = fs.join(dir, name + "-" + version);
    }
    return dir;
}

function getPackagesDir() {
    return fs.join(system.prefix, "packages");
}

function isInstalled(name, version) {
    return fs.exists(getInstallDir(name, version));
}

function isActivated(name) {
    return fs.exists(fs.join(getPackagesDir(), name));
}

function getDescriptor(dir) {
    var jsonPath = fs.join(dir, "package.json");
    if (fs.exists(jsonPath)) {
        return JSON.parse(fs.read(jsonPath));
    }
    return null;
}

function install(archivePath, name, version) {
    var installDir = getInstallDir(name, version);
    log.debug("Installing", fs.base(archivePath), "in", installDir);
    if (!fs.exists(installDir)) {
        fs.makeTree(installDir);
        var fileStream = fs.open(archivePath, {
            "binary": true
        });
        compress.extractStream(fileStream, installDir);
        log.debug("Installed", name, " " + version + " in", fs.absolute(installDir));
    }
    return installDir;
}

function uninstall(name, version) {
    var installDir = getInstallDir(name, version);
    if (!fs.exists(installDir)) {
        throw new Error("The package " + name + " " + version + " isn't installed")
    }
    fs.removeTree(installDir);
    return installDir;
}

function activate(name, version) {
    var installDir = getInstallDir(name, version);
    if (!fs.exists(installDir)) {
        throw new Error("The package " + name + " " + version + " isn't installed");
    }
    var src = fs.relative(fs.join(system.prefix, "packages/"), installDir);
    var dest = fs.join(getPackagesDir(), name);
    if (fs.exists(dest)) {
        // bail out if link points to a different package version
        var activePackage = getDescriptor(fs.readLink(dest));
        if (activePackage != null && activePackage.version != version) {
            throw new Error("A different version (" + activePackage.version +
                    ") of package " + name +
                    " is currently active, please clean up manually");
        }
        fs.remove(dest);
    }
    fs.symbolicLink(src, dest);
    log.debug("Activated package", name);
    return dest;
}

function deactivate(name) {
    var path = fs.join(getPackagesDir(), name);
    if (!fs.exists(path)) {
        throw new Error("The package" + name + " is not activated");
    } else if (!fs.isLink(path)) {
        throw new Error("Package " + name +
                " has been copied into packages directory, please move it away manually");
    }
    fs.remove(path);
    return;
}

function resolveDependencies(descriptor, queue, map) {
    queue = queue || [];
    map = map || {};
    queue.push(descriptor);
    if (descriptor.dependencies != undefined) {
        var depNames = Object.keys(descriptor.dependencies).sort();
        for each (var depName in depNames) {
            var depVersion = descriptor.dependencies[depName];
            if (map.hasOwnProperty(depName)) {
                if (!semver.satisfies(depVersion, map[depName].version)) {
                    throw new Error("Dependency conflict: " + descriptor.name +
                            " depends on " + depName + " " + depVersion +
                            ", but " + map[depName].requiredBy +
                            " requires version " + map[depName].version);
                } else if (semver.isGreaterOrEqual(map[depName].version, depVersion)) {
                    // we already have a greater or equal version, continue
                    continue;
                }
            }
            // FIXME: getPackageDescriptor does semver.satisfies() again ...
            var depDescriptor = registry.getPackageDescriptor(depName, depVersion);
            if (!depDescriptor) {
                throw new Error("Required package " + depName + " " +
                        depVersion + " doesn't exist in registry");
            }
            map[depDescriptor.name] = {
                "version": depDescriptor.version,
                "requiredBy": descriptor.name
            };
            resolveDependencies(depDescriptor, queue, map);
        };
    }
    return queue;
}
<|endoftext|>


<commit_before>/**
 * Farcaster is the module for rebuilding a remote service into a local accessible
 * service class.
 */

/**
 * Module dependencies.
 */

var RPC = require('../rpc')
var Asset = require('../web/asset')
var debug = require('debug')('micromono:service')
var assign = require('lodash.assign')
var Service = require('./service')
var toArray = require('lodash.toarray')
var shortid = require('shortid')
var Scheduler = require('../scheduler')

var Farcaster = module.exports = {}

/**
 * Rebuild the remote API to a local class based on serivce announcement.
 *
 * @param  {Object} serviceAnnouncement Service announcement information loaded from network.
 * @return {Service}
 */
Farcaster.build = function(serviceAnnouncement) {
  var serviceProto = {

    isRemote: function() {
      return true
    },

    constructor: function() {
      var ann = this.announcement = serviceAnnouncement
      this.baseUrl = this.announcement.baseUrl
      this.callbacks = {}

      this.scheduler = new Scheduler()

      if (ann.rpc && ann.rpcPort && ann.rpcType) {
        this.rpc = new RPC({
          api: ann.rpc,
          type: ann.rpcType,
          isRemote: true
        })
      }

      if (ann.route) {
        this.route = ann.route;
      }

      if (ann.asset) {
        this.asset = new Asset(ann.asset)
      }

      buildMiddlewares(this, ann.middleware)
    },

    generateID: function() {
      var id = shortid.generate()

      if (!this.callbacks[id]) {
        this.callbacks[id] = null
        return id
      } else {
        return this.generateID()
      }
    },

    run: function(app) {
      if (app) {
        this.express(app)
      }

      if (this.router) {
        // load route handlers
        this.router.getRoutes()
      }

      this.addProvider(this.announcement)

      return Promise.resolve()
    },

    addProvider: function(ann) {
      if (this.hasProvider(ann)) {
        return
      }

      debug('new provider for service `%s` found at %s', ann.name, ann.address)

      if (ann.api && ann.rpcPort) {
        this.connect(ann)
      }

      this.scheduler.add(ann)
    },

    hasProvider: function(ann) {
      var found = this.providers.some(function(provider) {
        if (ann.address && provider.address === ann.address) {
          if (ann.rpcPort && provider.rpcPort === ann.rpcPort) {
            return true
          }
          if (ann.webPort && provider.webPort === ann.webPort) {
            return true
          }
          if (ann.middlewarePort && provider.middlewarePort === ann.middlewarePort) {
            return true
          }
        }
      })
      return found
    },

    scheduleProvider: function(callback) {
      var provider = this.providers.shift()
      callback(provider)
      this.providers.push(provider)
    },

    onProviderDisconnect: function(provider) {
      var idx = this.providers.indexOf(provider)
      if (idx > -1) {
        delete this.providers[idx]
      }
    }
  }

  buildAPIs(serviceProto, serviceAnnouncement.api)
  return Service.extend(serviceProto)
}

/**
 * Private helper functions
 */

function buildAPIs(proto, apis) {
  if (apis) {
    Object.keys(apis).forEach(function(apiName) {
      proto[apiName] = function() {
        var args = toArray(arguments)
        var data = {
          name: apiName,
          args: args
        }
        this.send(data)
      }
    })
  }
}

function buildMiddlewares(service, middlewares) {
  if (middlewares) {
    var middleware = {}

    Object.keys(middlewares).forEach(function(name) {
      // a place holder, the actual handler will be set by framework adapter
      middleware[name] = null
    })

    service.middleware = middleware
  }
}
<commit_msg>Update farcaster with new RPC/Router.<commit_after>/**
 * Farcaster is the module for rebuilding a remote service into a local accessible
 * service class.
 */

/**
 * Module dependencies.
 */

var RPC = require('../rpc')
var Asset = require('../web/asset')
var debug = require('debug')('micromono:service')
var Service = require('./service')
var Scheduler = require('../scheduler')

var Farcaster = module.exports = {}

/**
 * Rebuild the remote API to a local class based on serivce announcement.
 *
 * @param  {Object} serviceAnnouncement Service announcement information loaded from network.
 * @return {Service}
 */
Farcaster.build = function(serviceAnnouncement) {
  var serviceProto = {

    announcement: serviceAnnouncement,

    isRemote: function() {
      return true
    },

    constructor: function() {
      this.setDefaults(this.announcement)
      this.scheduler = new Scheduler()

      this.setupWeb()
      this.setupRPC(this.announcement)
    },

    setDefaults: function(ann) {
      this.name = ann.name
      this.baseUrl = ann.baseUrl
      this.version = ann.version

      if (ann.asset) {
        this.asset = new Asset(ann.asset)
      }

      this.route = ann.route;
      this.middleware = ann.middleware
    },

    setupRPC: function(ann) {
      if (ann.rpc && ann.rpcType && ann.rpcPort && ann.address) {
        var rpcOptions = {
          api: ann.rpc,
          type: this.rpcType,
          context: null,
          isRemote: true,
          scheduler: this.scheduler
        }
        this.rpc = new RPC(rpcOptions)
        this.api = this.rpc.getHandlers()
        this.rpcType = ann.rpcType
      }
    },

    run: function(app) {
      if (this.router) {
        this.router.buildRoutes()
        this.router.startServer(app)
      }

      this.addProvider(this.announcement)

      return Promise.resolve()
    },

    addProvider: function(ann) {
      if (this.hasProvider(ann)) {
        return
      }

      debug('new provider for service `%s` found at %s', ann.name, ann.address)

      if (this.rpc) {
        this.rpc.connect(ann)
      }

      this.scheduler.add(ann)
    },

    hasProvider: function(ann) {
      var found = this.providers.some(function(provider) {
        if (ann.address && provider.address === ann.address) {
          if (ann.rpcPort && provider.rpcPort === ann.rpcPort) {
            return true
          }
          if (ann.webPort && provider.webPort === ann.webPort) {
            return true
          }
          if (ann.middlewarePort && provider.middlewarePort === ann.middlewarePort) {
            return true
          }
        }
      })
      return found
    },

    onProviderDisconnect: function(provider) {
      this.scheduler.remove(provider)
    }
  }

  return Service.extend(serviceProto)
}
<|endoftext|>


<commit_before>var q = require('q'),
    log = require('../log'),
    apps = require('../http-apps');

module.exports = function(req, res, registry) {
    return q(req.data)
        .then(function(data) {
            if (!data && req.headers['content-type'].indexOf('text/plain') > -1) {
                return req.body.read()
                    .then(function(body) {
                        return JSON.parse(body);
                    });
            }
            return data;
        })
        .catch(function() {
            return q.reject(apps.content('Invalid parameters', 'text/plain', 400));
        })
        .then(function(data) {
            return q(registry)
                .invoke('createNode', data)
                .catch(function(err) {
                    log.error('Error:', err || err.stack);
                    return q.reject(apps.content('Invalid parameters', 'text/plain', 400));
                })
                .then(function(node) {
                    return node.register()
                        .then(function(success) {
                            if (success) {
                                log.info('Registered node with ID=%s', node.getId());
                                return apps.content('ok');
                            }
                            return q.reject(apps.content('Invalid parameters', 'text/plain', 400));
                        });
                });
        });
};
<commit_msg>Fix error stack output in register servlet<commit_after>var q = require('q'),
    log = require('../log'),
    apps = require('../http-apps');

module.exports = function(req, res, registry) {
    return q(req.data)
        .then(function(data) {
            if (!data && req.headers['content-type'].indexOf('text/plain') > -1) {
                return req.body.read()
                    .then(function(body) {
                        return JSON.parse(body);
                    });
            }
            return data;
        })
        .catch(function() {
            return q.reject(apps.content('Invalid parameters', 'text/plain', 400));
        })
        .then(function(data) {
            return q(registry)
                .invoke('createNode', data)
                .catch(function(err) {
                    log.error('Error:', err.stack || err);
                    return q.reject(apps.content('Invalid parameters', 'text/plain', 400));
                })
                .then(function(node) {
                    return node.register()
                        .then(function(success) {
                            if (success) {
                                log.info('Registered node with ID=%s', node.getId());
                                return apps.content('ok');
                            }
                            return q.reject(apps.content('Invalid parameters', 'text/plain', 400));
                        });
                });
        });
};
<|endoftext|>


<commit_before>/* Simple timeline example
 * Single and multiline timelines
 */

import * as d3 from 'd3';
import * as textures from 'textures';

export default function(config) {

  var parseDate = d3.timeParse('%Y-%m-%d');

  function Timeline(config){
    var vm = this;
    vm._config = config ? config : {};
    vm._config.area = false;
    vm._data = [];
    vm._scales ={};
    vm._axes = {};

    vm._line = d3.line()
      .curve(d3.curveBasis)
      .x(function(d) { return vm._scales.x(d.x); })
      .y(function(d) { return vm._scales.y(d.y); });

    vm._area = d3.area()
      .curve(d3.curveBasis)
      .x(function(d) {
        if (d.alreadyScaled && d.alreadyScaled === true){
          return d.x;
        }else{
          return vm._scales.x(d.x);
        }
      })
      .y1(function(d) {
        if (d.alreadyScaled && d.alreadyScaled === true){
          return d.y;
        }else{
          return vm._scales.y(d.y);
        }

      });

  }

  //-------------------------------
  //User config functions
  Timeline.prototype.x = function(col){
    var vm = this;
    vm._config.x = col;
    return vm;
  }

  Timeline.prototype.y = function(col){
    var vm = this;
    vm._config.y = col;
    return vm;
  }

  Timeline.prototype.series = function(arr){
    var vm = this;
    vm._config.series = arr;
    return vm;
  }

  Timeline.prototype.colors = function(arr){
    var vm = this;
    vm._config.colors = arr;
    return vm;
  }

  Timeline.prototype.timeParse = function(timeParse){
    var vm = this;
    parseDate= d3.timeParse(timeParse);
    return vm;
  }

  Timeline.prototype.area = function(area){
    var vm = this;
    vm._config.area = area;
    return vm;
  }

  Timeline.prototype.color = function(col){
    var vm = this;
    vm._config.color = col;
    return vm;
  }

  Timeline.prototype.end = function(){
    var vm = this;
    return vm._chart;
  }

  //-------------------------------
  //Triggered by the chart.js;
  Timeline.prototype.chart = function(chart){
    var vm = this;
    vm._chart = chart;
    return vm;
  }

  Timeline.prototype.data = function(data){
    var vm = this;

    vm._data = data.map(function(d){
      d.x = parseDate(d[vm._config.x]);
      delete(d[vm._config.x]);
      return d;
    });

    vm._lines = vm._config.y ? vm._config.y : vm._config.series;

    vm._lines = vm._lines.map(function(name) {
      return {
        name: name,
        values: data.map(function(d) {
          return {x: d.x, y: +d[name]};
        })
      };
    });
    return vm;
  }

  Timeline.prototype.scales = function(s){
    var vm = this;
    vm._scales = s;
    return vm;
  }

  Timeline.prototype.axes = function(a){
    var vm = this;
    vm._axes = a;
    return vm;
  }

  Timeline.prototype.domains = function(){
    var vm = this;
    vm._xMinMax = d3.extent(vm._data, function(d) { return d.x; });

    vm._yMinMax = [
      d3.min(vm._lines, function(c) { return d3.min(c.values, function(v) { return v.y; }); }),
      d3.max(vm._lines, function(c) { return d3.max(c.values, function(v) { return v.y; }); })
    ];

    vm._scales.x.domain(vm._xMinMax)
    vm._scales.y.domain(vm._yMinMax)

    //console.log(vm._scales.x.domain(), vm._chart._scales.x.domain())

    vm._chart._scales = vm._scales;

    return vm;
  };

  Timeline.prototype.draw = function(){
    var vm = this;

    var lines = vm._chart._svg.selectAll(".lines")
      .data(vm._lines)
    .enter().append("g")
      .attr("class", "lines");

    var path = vm._chart._svg.selectAll(".lines").append("path")
      .attr("class", "line")
      .attr("d", function(d) {
        return vm._line(d.values);
      })
      .style("stroke", function(d, i ){
        return vm._config.colors[i];
      })
      .style("fill", 'none');

    //var t = textures.lines().thicker();
    //vm._chart._svg.call(t);

    if(vm._config.area === true){
      vm._area.y0(vm._scales.y(vm._yMinMax[0]));

      var areas = vm._chart._svg.selectAll(".areas")
        .data(vm._lines)
      .enter().append("g")
        .attr("class", "areas");

      var pathArea  = vm._chart._svg.selectAll(".areas").append("path")
        .attr("class", "area")
        .attr("d", function(d) {
          return vm._area(d.values);
        })
        .attr("fill",  function(d, i ){
          return vm._config.colors[i];
        });
    }

    /*path.each(function(d) { d.totalLength = this.getTotalLength(); })
      .attr("stroke-dasharray", function(d) { return d.totalLength + " " + d.totalLength; })
      .attr("stroke-dashoffset", function(d) { return d.totalLength; })
      .transition()
        .duration(5000)
        .ease(d3.easeLinear)
        .attr("stroke-dashoffset", 0);*/

    return vm;
  }

  return new Timeline(config);
}

/*import chart from './chart.js';

function Timeline(config) {
  var vm = this;
  vm._config = config;
  vm._chart;
  vm._scales = {};
  vm._axes = {};
}

Timeline.prototype = timeline.prototype = {
	generate:function(){
		var vm = this, q;

		vm.draw();
    vm.setScales();
		vm.setAxes();

		q = vm._chart.loadData();

    q.await(function(error,data){
      if (error) {
        //console.log(error)
        throw error;
        return false;
      }

      vm.setData(data);
      vm.setDomains();
      vm.drawAxes();
      console.log("generate", vm._data);
      vm.drawData();
    })

	},
	draw : function(){
		var vm = this
		vm._chart = chart(vm._config);
	},
	setScales: function(){
		var vm = this;

		vm._scales.x = d3.scaleTime()
		  .range([0, vm._chart._width]);

		vm._scales.y = d3.scaleLinear()
		  .range([vm._chart._height, 0]);

    vm._scales.color = d3.scaleOrdinal(d3.schemeCategory20c);
	},
	setAxes : function(){
		var vm = this;

		vm._axes.x = d3.svg.axis()
		  .scale(vm._scales.x)
		  .orient("bottom");

		vm._axes.y = d3.svg.axis()
		  .scale(vm._scales.y)
		  .orient("left");

    if(vm._config.yAxis && vm._config.yAxis.ticks
        && vm._config.yAxis.ticks.enabled === true && vm._config.yAxis.ticks.style ){

      switch(vm._config.yAxis.ticks.style){
        case 'straightLine':
          vm._axes.y
            .tickSize(-vm._chart._width,0);
        break;
      }

    }

    if( vm._config.yAxis.ticks.format){
      console.log('Set tick format');
      vm._axes.y.tickFormat(vm._config.yAxis.ticks.format);
    }
	},
	setData:function(data){
    var vm = this;
    var keys = d3.keys(data[0]).filter(function(key) { return key !== "date"; });

    var series = keys.map(function(name) {
      return {
        name: name,
        values: data.map(function(d) {
          return {x: d.date, y: +d[name]};
        })
      };
    });

    vm._data = series;
  },
  setDomains:function(){
    var vm = this;

    vm._scales.color.domain(vm._data.map(function(serie){
      return serie.name;
    }));

    vm._scales.x.domain([
      d3.min(vm._data, function(c) { return d3.min(c.values, function(v) { return v.x; }); }),
      d3.max(vm._data, function(c) { return d3.max(c.values, function(v) { return v.x; }); })
    ]);

    vm._scales.y.domain([
      d3.min(vm._data, function(c) { return d3.min(c.values, function(v) { return v.y; }); }),
      d3.max(vm._data, function(c) { return d3.max(c.values, function(v) { return v.y; }); })
    ]);
  },
  drawAxes:function(){
    var vm = this;

    vm._chart._svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + vm._chart._height + ")")
        .call(vm._axes.x)
      .append("text")
        .attr("class", "label")
        .attr("x", vm._chart._width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text("");

    var yAxis = vm._chart._svg.append("g")
        .attr("class", "y axis")
        .call(vm._axes.y)

    if(vm._config.yAxis && vm._config.yAxis.text){
      yAxis.append("text")
        .attr("class", "label")
        .attr("transform", "rotate(-90)")
        .attr("x", -vm._chart._height/2)
        .attr("y", -vm._config.size.margin.left + 10)
        .attr("dy", ".71em")
        .style("text-anchor", "middle")
        .style("font-size","14px")
        .text(vm._config.yAxis.text);
    }

  },
  drawData : function(){
    var vm = this;
    var line = d3.svg.line()
        .interpolate(vm._config.data.interpolation)
        .defined(function(d) { return d; })
        .x(function(d) { return vm._scales.x(d.x); })
        .y(function(d) { return vm._scales.y(d.y); });

    var series = vm._chart._svg.selectAll(".series")
        .data(vm._data)
      .enter().append("g")
        .attr("class", "series")

    series.append("path")
        .attr("class", "line")
        .attr("d", function(d) { return line(d.values); })
        .style("stroke-dasharray",function(d){ if(d.name == "Nacional"){
            return ("10,5");
          }})
        .style("stroke", function(d) {
          if(d.color){ return d.color; }
          else { return vm._scales.color(d.key); }
        }) //return vm._scales.color(d.name); })
        .style("stroke-width", 3);

    series.selectAll('.dot')
        .data(function(d){return d.values})
      .enter().append("circle")
        .attr("class", "dot")
        .attr("r", 3)
        .attr("cx", function(d) { return vm._scales.x(d.x); })
        .attr("cy", function(d) { return vm._scales.y(d.y); })
        .style("fill", function(d) {
          if(d.color){ return d.color; }
          else { return vm._scales.color(d.key); }
        })//return vm._scales.color(d.name); })
        .style("stroke", function(d) {
          if(d.color){ return d.color; }
          else { return vm._scales.color(d.key); }
        }) // return vm._scales.color(d.name); })
        .on('mouseover', function(d,i){
          if(vm._config.data.mouseover){
            vm._config.data.mouseover.call(vm, d,i)
          }
          vm._chart._tip.show(d, d3.select(this).node())
        })
        .on('mouseout',function(d,i){
          if(vm._config.data.mouseout){
            vm._config.data.mouseout.call(vm, d,i)
          }
          vm._chart._tip.hide(d, d3.select(this).node())
        });

        //series.selectAll('.dot-inside')
        //  .data(function(d){return d.values})
        //.enter().append("circle")
        //  .attr("class", "dot-inside")
        //  .attr("r", 4)
        //  .attr("cx", function(d) { return vm._scales.x(d.x); })
        //  .attr("cy", function(d) { return vm._scales.y(d.y); })
        //  .style("fill", 'black')//return vm._scales.color(d.name); })
        //  .style("stroke", function(d) { return d.color;}) // return vm._scales.color(d.name); })
        //  .on('mouseover', function(d,i){
        //    if(vm._config.data.mouseover){
        //      vm._config.data.mouseover.call(vm, d,i)
        //    }
        //    vm._chart._tip.show(d, d3.select(this).node())
        //  })
        //  .on('mouseout',function(d,i){
        //    if(vm._config.data.mouseout){
        //      vm._config.data.mouseout.call(vm, d,i)
        //    }
        //    vm._chart._tip.hide(d, d3.select(this).node())
        //  });

    //series.append("text")
    //    .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
    //    .attr("transform", function(d) { return "translate(" + vm._scales.x(d.value.x) + "," + vm._scales.y(d.value.y) + ")"; })
    //    .attr("x", 3)
    //    .attr("dy", ".35em")
    //    .text(function(d) { return d.name; });
  }

}

export default function timeline(config) {
  return new Timeline(arguments.length ? config : null);
}*/
<commit_msg>curveMonotoneX<commit_after>/* Simple timeline example
 * Single and multiline timelines
 */

import * as d3 from 'd3';
import * as textures from 'textures';

export default function(config) {

  var parseDate = d3.timeParse('%Y-%m-%d');

  function Timeline(config){
    var vm = this;
    vm._config = config ? config : {};
    vm._config.area = false;
    vm._data = [];
    vm._scales ={};
    vm._axes = {};

    vm._line = d3.line()
      .curve(d3.curveMonotoneX)
      .x(function(d) { return vm._scales.x(d.x); })
      .y(function(d) { return vm._scales.y(d.y); });

    vm._area = d3.area()
      .curve(d3.curveMonotoneX)
      .x(function(d) {
        if (d.alreadyScaled && d.alreadyScaled === true){
          return d.x;
        }else{
          return vm._scales.x(d.x);
        }
      })
      .y1(function(d) {
        if (d.alreadyScaled && d.alreadyScaled === true){
          return d.y;
        }else{
          return vm._scales.y(d.y);
        }

      });

  }

  //-------------------------------
  //User config functions
  Timeline.prototype.x = function(col){
    var vm = this;
    vm._config.x = col;
    return vm;
  }

  Timeline.prototype.y = function(col){
    var vm = this;
    vm._config.y = col;
    return vm;
  }

  Timeline.prototype.series = function(arr){
    var vm = this;
    vm._config.series = arr;
    return vm;
  }

  Timeline.prototype.colors = function(arr){
    var vm = this;
    vm._config.colors = arr;
    return vm;
  }

  Timeline.prototype.timeParse = function(timeParse){
    var vm = this;
    parseDate= d3.timeParse(timeParse);
    return vm;
  }

  Timeline.prototype.area = function(area){
    var vm = this;
    vm._config.area = area;
    return vm;
  }

  Timeline.prototype.color = function(col){
    var vm = this;
    vm._config.color = col;
    return vm;
  }

  Timeline.prototype.end = function(){
    var vm = this;
    return vm._chart;
  }

  //-------------------------------
  //Triggered by the chart.js;
  Timeline.prototype.chart = function(chart){
    var vm = this;
    vm._chart = chart;
    return vm;
  }

  Timeline.prototype.data = function(data){
    var vm = this;

    vm._data = data.map(function(d){
      d.x = parseDate(d[vm._config.x]);
      delete(d[vm._config.x]);
      return d;
    });

    vm._lines = vm._config.y ? vm._config.y : vm._config.series;

    vm._lines = vm._lines.map(function(name) {
      return {
        name: name,
        values: data.map(function(d) {
          return {x: d.x, y: +d[name]};
        })
      };
    });
    return vm;
  }

  Timeline.prototype.scales = function(s){
    var vm = this;
    vm._scales = s;
    return vm;
  }

  Timeline.prototype.axes = function(a){
    var vm = this;
    vm._axes = a;
    return vm;
  }

  Timeline.prototype.domains = function(){
    var vm = this;
    vm._xMinMax = d3.extent(vm._data, function(d) { return d.x; });

    vm._yMinMax = [
      d3.min(vm._lines, function(c) { return d3.min(c.values, function(v) { return v.y; }); }),
      d3.max(vm._lines, function(c) { return d3.max(c.values, function(v) { return v.y; }); })
    ];

    vm._scales.x.domain(vm._xMinMax)
    vm._scales.y.domain(vm._yMinMax)

    //console.log(vm._scales.x.domain(), vm._chart._scales.x.domain())

    vm._chart._scales = vm._scales;

    return vm;
  };

  Timeline.prototype.draw = function(){
    var vm = this;

    var lines = vm._chart._svg.selectAll(".lines")
      .data(vm._lines)
    .enter().append("g")
      .attr("class", "lines");

    var path = vm._chart._svg.selectAll(".lines").append("path")
      .attr("class", "line")
      .attr("d", function(d) {
        return vm._line(d.values);
      })
      .style("stroke", function(d, i ){
        return vm._config.colors[i];
      })
      .style("fill", 'none');

    //var t = textures.lines().thicker();
    //vm._chart._svg.call(t);

    if(vm._config.area === true){
      vm._area.y0(vm._scales.y(vm._yMinMax[0]));

      var areas = vm._chart._svg.selectAll(".areas")
        .data(vm._lines)
      .enter().append("g")
        .attr("class", "areas");

      var pathArea  = vm._chart._svg.selectAll(".areas").append("path")
        .attr("class", "area")
        .attr("d", function(d) {
          return vm._area(d.values);
        })
        .attr("fill",  function(d, i ){
          return vm._config.colors[i];
        });
    }

    /*path.each(function(d) { d.totalLength = this.getTotalLength(); })
      .attr("stroke-dasharray", function(d) { return d.totalLength + " " + d.totalLength; })
      .attr("stroke-dashoffset", function(d) { return d.totalLength; })
      .transition()
        .duration(5000)
        .ease(d3.easeLinear)
        .attr("stroke-dashoffset", 0);*/

    return vm;
  }

  return new Timeline(config);
}

/*import chart from './chart.js';

function Timeline(config) {
  var vm = this;
  vm._config = config;
  vm._chart;
  vm._scales = {};
  vm._axes = {};
}

Timeline.prototype = timeline.prototype = {
	generate:function(){
		var vm = this, q;

		vm.draw();
    vm.setScales();
		vm.setAxes();

		q = vm._chart.loadData();

    q.await(function(error,data){
      if (error) {
        //console.log(error)
        throw error;
        return false;
      }

      vm.setData(data);
      vm.setDomains();
      vm.drawAxes();
      console.log("generate", vm._data);
      vm.drawData();
    })

	},
	draw : function(){
		var vm = this
		vm._chart = chart(vm._config);
	},
	setScales: function(){
		var vm = this;

		vm._scales.x = d3.scaleTime()
		  .range([0, vm._chart._width]);

		vm._scales.y = d3.scaleLinear()
		  .range([vm._chart._height, 0]);

    vm._scales.color = d3.scaleOrdinal(d3.schemeCategory20c);
	},
	setAxes : function(){
		var vm = this;

		vm._axes.x = d3.svg.axis()
		  .scale(vm._scales.x)
		  .orient("bottom");

		vm._axes.y = d3.svg.axis()
		  .scale(vm._scales.y)
		  .orient("left");

    if(vm._config.yAxis && vm._config.yAxis.ticks
        && vm._config.yAxis.ticks.enabled === true && vm._config.yAxis.ticks.style ){

      switch(vm._config.yAxis.ticks.style){
        case 'straightLine':
          vm._axes.y
            .tickSize(-vm._chart._width,0);
        break;
      }

    }

    if( vm._config.yAxis.ticks.format){
      console.log('Set tick format');
      vm._axes.y.tickFormat(vm._config.yAxis.ticks.format);
    }
	},
	setData:function(data){
    var vm = this;
    var keys = d3.keys(data[0]).filter(function(key) { return key !== "date"; });

    var series = keys.map(function(name) {
      return {
        name: name,
        values: data.map(function(d) {
          return {x: d.date, y: +d[name]};
        })
      };
    });

    vm._data = series;
  },
  setDomains:function(){
    var vm = this;

    vm._scales.color.domain(vm._data.map(function(serie){
      return serie.name;
    }));

    vm._scales.x.domain([
      d3.min(vm._data, function(c) { return d3.min(c.values, function(v) { return v.x; }); }),
      d3.max(vm._data, function(c) { return d3.max(c.values, function(v) { return v.x; }); })
    ]);

    vm._scales.y.domain([
      d3.min(vm._data, function(c) { return d3.min(c.values, function(v) { return v.y; }); }),
      d3.max(vm._data, function(c) { return d3.max(c.values, function(v) { return v.y; }); })
    ]);
  },
  drawAxes:function(){
    var vm = this;

    vm._chart._svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + vm._chart._height + ")")
        .call(vm._axes.x)
      .append("text")
        .attr("class", "label")
        .attr("x", vm._chart._width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text("");

    var yAxis = vm._chart._svg.append("g")
        .attr("class", "y axis")
        .call(vm._axes.y)

    if(vm._config.yAxis && vm._config.yAxis.text){
      yAxis.append("text")
        .attr("class", "label")
        .attr("transform", "rotate(-90)")
        .attr("x", -vm._chart._height/2)
        .attr("y", -vm._config.size.margin.left + 10)
        .attr("dy", ".71em")
        .style("text-anchor", "middle")
        .style("font-size","14px")
        .text(vm._config.yAxis.text);
    }

  },
  drawData : function(){
    var vm = this;
    var line = d3.svg.line()
        .interpolate(vm._config.data.interpolation)
        .defined(function(d) { return d; })
        .x(function(d) { return vm._scales.x(d.x); })
        .y(function(d) { return vm._scales.y(d.y); });

    var series = vm._chart._svg.selectAll(".series")
        .data(vm._data)
      .enter().append("g")
        .attr("class", "series")

    series.append("path")
        .attr("class", "line")
        .attr("d", function(d) { return line(d.values); })
        .style("stroke-dasharray",function(d){ if(d.name == "Nacional"){
            return ("10,5");
          }})
        .style("stroke", function(d) {
          if(d.color){ return d.color; }
          else { return vm._scales.color(d.key); }
        }) //return vm._scales.color(d.name); })
        .style("stroke-width", 3);

    series.selectAll('.dot')
        .data(function(d){return d.values})
      .enter().append("circle")
        .attr("class", "dot")
        .attr("r", 3)
        .attr("cx", function(d) { return vm._scales.x(d.x); })
        .attr("cy", function(d) { return vm._scales.y(d.y); })
        .style("fill", function(d) {
          if(d.color){ return d.color; }
          else { return vm._scales.color(d.key); }
        })//return vm._scales.color(d.name); })
        .style("stroke", function(d) {
          if(d.color){ return d.color; }
          else { return vm._scales.color(d.key); }
        }) // return vm._scales.color(d.name); })
        .on('mouseover', function(d,i){
          if(vm._config.data.mouseover){
            vm._config.data.mouseover.call(vm, d,i)
          }
          vm._chart._tip.show(d, d3.select(this).node())
        })
        .on('mouseout',function(d,i){
          if(vm._config.data.mouseout){
            vm._config.data.mouseout.call(vm, d,i)
          }
          vm._chart._tip.hide(d, d3.select(this).node())
        });

        //series.selectAll('.dot-inside')
        //  .data(function(d){return d.values})
        //.enter().append("circle")
        //  .attr("class", "dot-inside")
        //  .attr("r", 4)
        //  .attr("cx", function(d) { return vm._scales.x(d.x); })
        //  .attr("cy", function(d) { return vm._scales.y(d.y); })
        //  .style("fill", 'black')//return vm._scales.color(d.name); })
        //  .style("stroke", function(d) { return d.color;}) // return vm._scales.color(d.name); })
        //  .on('mouseover', function(d,i){
        //    if(vm._config.data.mouseover){
        //      vm._config.data.mouseover.call(vm, d,i)
        //    }
        //    vm._chart._tip.show(d, d3.select(this).node())
        //  })
        //  .on('mouseout',function(d,i){
        //    if(vm._config.data.mouseout){
        //      vm._config.data.mouseout.call(vm, d,i)
        //    }
        //    vm._chart._tip.hide(d, d3.select(this).node())
        //  });

    //series.append("text")
    //    .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
    //    .attr("transform", function(d) { return "translate(" + vm._scales.x(d.value.x) + "," + vm._scales.y(d.value.y) + ")"; })
    //    .attr("x", 3)
    //    .attr("dy", ".35em")
    //    .text(function(d) { return d.name; });
  }

}

export default function timeline(config) {
  return new Timeline(arguments.length ? config : null);
}*/
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var path = require('path')
  , estraverse = require('estraverse')
  , utils = require('../utils')
  , isRequire = utils.isRequire
  , isDefine = utils.isDefine;

/**
 * Transforms require statements to use absolute module IDs.
 *
 * Node's module resolution algorithm finds modules by searching in node_modules
 * directories, as well as loading from directories containing a package.json
 * file (with a `main` property).  This algorithm is incompatible with AMD's
 * algorithm, which locates all modules under a base URL.
 *
 * When transforming a Node module to AMD, `require` statements will be
 * re-written to use absolute module IDs.  This ensures that dependencies are
 * correctly resolved when loaded by an AMD-compatible loader in a browser.
 *
 * @param {Module} mod
 * @param {Object} ast
 * @param {Object} opts
 * @return {Function}
 * @api public
 */
module.exports = function(mod, ast, opts) {
  opts = opts || {};

  //console.log(JSON.stringify(ast, null, 2));

  var baseDir = opts.baseDir || process.cwd()
    , requires = mod.requires
    , map = {}
    , flatten = opts.flatten || false;

  for (var i = 0, len = requires.length; i < len; i++) {
    var dep = requires[i];

    if (mod.resolve.isCore(dep)) {
      // Core modules are built in to Node.  When loading Node modules in an AMD
      // context, they will be provided by a compatibility layer and resolved
      // from the base URL.
    } else if (flatten && dep[0] != '.') {
      // When flatten mode is enabled, any non-relative modules will not be
      // mapped to their Node resolution path.  This forces all dependencies up
      // to the top level, where they are resolved from the base URL in an AMD
      // context.
    } else {
      // Any required non-core modules will be required by their absolute ID.
      // In effect, this "pre-resolves" modules since Node's algorithm cannot be
      // performed within a browser.
      //
      // Note that, at first glance, it is tempting to leave relative modules
      // (in the form `require('./foo')`) alone thinking that they will correctly
      // be resolved by AMD from the parent module's path.  However, this does
      // not hold when the parent module is loaded from a directory containing a
      // package.json file.  Therefore, even relative require statements are
      // mapped to absolute module IDs.

      try {
        var fname = mod.resolve(dep);
        var ext = path.extname(fname);
        var aid = path.relative(baseDir, fname);
        aid = aid.slice(0, aid.length - ext.length);

        // map id to absolute id
        map[dep] = aid;
      } catch(e) {
        // Catch and ignore MODULE_NOT_FOUND errors, leaving the module
        // unmapped.
      }
    }
  }

  estraverse.traverse(ast, {
    leave: function(node) {
      if (isRequire(node)) {
        // TODO: Implement test case for non-literal require.  Should not be modified.

        if (node.arguments.length && node.arguments[0].type === 'Literal') {
          var mid = map[node.arguments[0].value] || node.arguments[0].value;
          node.arguments[0].value = mid;
        }
      } else if (isDefine(node)) {
        var dependencies = []
          , di = 0;

        // TODO: Find position of dependencies argument (0 or 1) (if listed, may not be)

        dependencies = node.arguments[di].elements;
        var elements = dependencies.map(function(d) {
          var mid = map[d.value] || d.value;
          return { type: "Literal", value: mid }
        });
        node.arguments[di].elements = elements;
      }
    }
  });

  return ast;
}
<commit_msg>Pick dependencies from correct argument position.<commit_after>/**
 * Module dependencies.
 */
var path = require('path')
  , estraverse = require('estraverse')
  , utils = require('../utils')
  , isRequire = utils.isRequire
  , isDefine = utils.isDefine;

/**
 * Transforms require statements to use absolute module IDs.
 *
 * Node's module resolution algorithm finds modules by searching in node_modules
 * directories, as well as loading from directories containing a package.json
 * file (with a `main` property).  This algorithm is incompatible with AMD's
 * algorithm, which locates all modules under a base URL.
 *
 * When transforming a Node module to AMD, `require` statements will be
 * re-written to use absolute module IDs.  This ensures that dependencies are
 * correctly resolved when loaded by an AMD-compatible loader in a browser.
 *
 * @param {Module} mod
 * @param {Object} ast
 * @param {Object} opts
 * @return {Function}
 * @api public
 */
module.exports = function(mod, ast, opts) {
  opts = opts || {};

  //console.log(JSON.stringify(ast, null, 2));

  var baseDir = opts.baseDir || process.cwd()
    , requires = mod.requires
    , map = {}
    , flatten = opts.flatten || false;

  for (var i = 0, len = requires.length; i < len; i++) {
    var dep = requires[i];

    if (mod.resolve.isCore(dep)) {
      // Core modules are built in to Node.  When loading Node modules in an AMD
      // context, they will be provided by a compatibility layer and resolved
      // from the base URL.
    } else if (flatten && dep[0] != '.') {
      // When flatten mode is enabled, any non-relative modules will not be
      // mapped to their Node resolution path.  This forces all dependencies up
      // to the top level, where they are resolved from the base URL in an AMD
      // context.
    } else {
      // Any required non-core modules will be required by their absolute ID.
      // In effect, this "pre-resolves" modules since Node's algorithm cannot be
      // performed within a browser.
      //
      // Note that, at first glance, it is tempting to leave relative modules
      // (in the form `require('./foo')`) alone thinking that they will correctly
      // be resolved by AMD from the parent module's path.  However, this does
      // not hold when the parent module is loaded from a directory containing a
      // package.json file.  Therefore, even relative require statements are
      // mapped to absolute module IDs.

      try {
        var fname = mod.resolve(dep);
        var ext = path.extname(fname);
        var aid = path.relative(baseDir, fname);
        aid = aid.slice(0, aid.length - ext.length);

        // map id to absolute id
        map[dep] = aid;
      } catch(e) {
        // Catch and ignore MODULE_NOT_FOUND errors, leaving the module
        // unmapped.
      }
    }
  }

  estraverse.traverse(ast, {
    leave: function(node) {
      if (isRequire(node)) {
        // TODO: Implement test case for non-literal require.  Should not be modified.

        if (node.arguments.length && node.arguments[0].type === 'Literal') {
          var mid = map[node.arguments[0].value] || node.arguments[0].value;
          node.arguments[0].value = mid;
        }
      } else if (isDefine(node)) {
        var dependencies
          , di;

        if (node.arguments.length >= 1 && node.arguments[0].type == 'ArrayExpression') {
          dependencies = node.arguments[0].elements;
          di = 0;
        } else if (node.arguments.length >= 2 && node.arguments[1].type == 'ArrayExpression') {
          dependencies = node.arguments[1].elements;
          di = 1;
        }

        if (dependencies) {
          var elements = dependencies.map(function(d) {
            var mid = map[d.value] || d.value;
            return { type: "Literal", value: mid }
          });
          node.arguments[di].elements = elements;
        }
      }
    }
  });

  return ast;
}
<|endoftext|>


<commit_before>'use strict';
const _ = require('lodash');
const chalk = require('chalk');
const opts = require("nomnom")
    .option('development', {
        abbr: 'dev',
        flag: true,
        help: 'Run with process.env.COINS_ENV set to \'development\''
    })
    .option('release', {
        abbr: 'rel',
        flag: true,
        help: 'Run with process.env.COINS_ENV set to \'release\''
    })
    .option('production', {
        abbr: 'prd',
        flag: true,
        help: 'Run with process.env.COINS_ENV set to \'production\''
    })
    .parse();

_.each(opts, (val, opt) => {
    if (_.contains(['development', 'release', 'production'], opt) && val) {
        console.log(chalk.blue(`Running with COINS_ENV: ${opt}`));
        process.env.COINS_ENV = opt;
    }
});

module.exports = opts;<commit_msg>Update cli-options.js<commit_after>'use strict';
const _ = require('lodash');
const chalk = require('chalk');
const opts = require("nomnom")
    .option('development', {
        abbr: 'dev',
        flag: true,
        help: 'Run with process.env.COINS_ENV set to \'development\''
    })
    .option('release', {
        abbr: 'rel',
        flag: true,
        help: 'Run with process.env.COINS_ENV set to \'release\''
    })
    .option('production', {
        abbr: 'prd',
        flag: true,
        help: 'Run with process.env.COINS_ENV set to \'production\''
    })
    .parse();

_.each(opts, (val, opt) => {
    if (_.contains(['development', 'release', 'production'], opt) && val) {
        process.env.COINS_ENV = opt;
    }
});
console.log(chalk.blue(`Running with COINS_ENV: ${process.env.COINS_ENV}`));

module.exports = opts;
<|endoftext|>


<commit_before>/*

Code to set up the log collection and to send it back to the server.

*/
// Set up global vAnnotate object if it doesn't exist already
(function(window){
    {{{serializeLogResult}}}

    if (!window.vAnnotate){
        var logResults = {},
            vAnnotate = {
                log: function(fileId, i, value){
                    logResults[fileId][i] = serializeLogResult(value);
                },
                _logResults: logResults
            }
        window.vAnnotate = vAnnotate;
    }
})(window);
// Set up code for this file
(function(window){
	var RESULT_SAVE_INTERVAL = 1000,
		fileId = '{{{fileId}}}',
        vAnnotate = window.vAnnotate;

    vAnnotate._logResults[fileId] = {};

	function sendResults(){
		var xmlhttp = new XMLHttpRequest(),
            logResults = vAnnotate._logResults[fileId];

		data = JSON.stringify(logResults);

	    xmlhttp.open("POST", "/vAnnotate/results", true);
	    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	    xmlhttp.send('results=' + data + '&fileId=' + fileId);
	};

	setInterval(sendResults, RESULT_SAVE_INTERVAL);
	setTimeout(sendResults, 0); // Run once all page initialization code has run
})(window);
<commit_msg>Fix server erros if data contains ampersand<commit_after>/*

Code to set up the log collection and to send it back to the server.

*/
// Set up global vAnnotate object if it doesn't exist already
(function(window){
    {{{serializeLogResult}}}

    if (!window.vAnnotate){
        var logResults = {},
            vAnnotate = {
                log: function(fileId, i, value){
                    logResults[fileId][i] = serializeLogResult(value);
                },
                _logResults: logResults
            }
        window.vAnnotate = vAnnotate;
    }
})(window);
// Set up code for this file
(function(window){
	var RESULT_SAVE_INTERVAL = 1000,
		fileId = '{{{fileId}}}',
        vAnnotate = window.vAnnotate;

    vAnnotate._logResults[fileId] = {};

	function sendResults(){
		var xmlhttp = new XMLHttpRequest(),
            logResults = vAnnotate._logResults[fileId];

		data = JSON.stringify(logResults);

	    xmlhttp.open("POST", "/vAnnotate/results", true);
	    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      // We need encodeURIComponent because the data might contain an ampersand...
	    xmlhttp.send('results=' + encodeURIComponent(data) + '&fileId=' + encodeURIComponent(fileId));
	};

	setInterval(sendResults, RESULT_SAVE_INTERVAL);
	setTimeout(sendResults, 0); // Run once all page initialization code has run
})(window);
<|endoftext|>


<commit_before>/** @babel */
/** @jsx etch.dom */

import etch from 'etch'
import {CompositeDisposable} from 'atom'

export default class BranchView {
  constructor (props) {
    this.props = props
    this.didSelectItem = this.didSelectItem.bind(this)
    this.createBranch = this.createBranch.bind(this)
    const TextEditor = props.workspace.buildTextEditor
    this.textEditorWidget =
      <TextEditor
        ref='editor'
        mini={true}
        softWrapped={true}
        placeholderText='enter new branch name'
        lineNumberGutterVisible={false}
        showInvisibles={false}
        scrollPastEnd={false}
      />
    etch.initialize(this)
    this.subscriptions = new CompositeDisposable(
      atom.commands.add('.git-BranchView-editor atom-text-editor[mini]', {
        'tool-panel:unfocus': this.cancelCreateNewBranch,
        'core:cancel': this.cancelCreateNewBranch,
        'core:confirm': this.createBranch
      })
    )
    this.createNew = false
  }

  update (props) {
    this.props = Object.assign({}, this.props, props)
    this.createNew = false
    return etch.update(this)
  }

  didSelectItem () {
    const branchName = this.refs.list.selectedOptions[0].text
    this.props.checkout(branchName)
  }

  createBranch (e) {
    if (e) e.stopImmediatePropagation()
    if (this.createNew) {
      const branchName = this.refs.editor.getText().trim()
      this.props.checkout(branchName, {createNew: true})
    } else {
      this.createNew = true
      return etch.update(this)
    }
  }

  render () {
    const newBranchEditor = (

        {this.textEditorWidget}

    )

    const selectBranchView = (
      <select ref='list' className='git-BranchView-item git-BranchView-select input-select' onchange={this.didSelectItem}>
        {this.props.branches.map(branch => {
          return <option value={branch} selected={branch === this.props.branchName}>{branch}</option>
        })}
      </select>
    )

    return (

        { this.createNew ? newBranchEditor : selectBranchView }
        <button ref='newBranchButton' className='git-BranchView-item git-BranchView-button btn'
                onclick={this.createBranch}> Create New Branch </button>

    )
  }

  destroy () {
    this.subscriptions.dispose()
    etch.destroy(this)
  }
}
<commit_msg>Exit create branch text editor with with `tool-panel:unfocus` and `core:cancel`<commit_after>/** @babel */
/** @jsx etch.dom */

import etch from 'etch'
import {CompositeDisposable} from 'atom'

export default class BranchView {
  constructor (props) {
    this.props = props
    this.didSelectItem = this.didSelectItem.bind(this)
    this.createBranch = this.createBranch.bind(this)
    this.cancelCreateNewBranch = this.cancelCreateNewBranch.bind(this)
    const TextEditor = props.workspace.buildTextEditor
    this.textEditorWidget =
      <TextEditor
        ref='editor'
        mini={true}
        softWrapped={true}
        placeholderText='enter new branch name'
        lineNumberGutterVisible={false}
        showInvisibles={false}
        scrollPastEnd={false}
      />
    etch.initialize(this)
    this.subscriptions = new CompositeDisposable(
      atom.commands.add('.git-BranchView-editor atom-text-editor[mini]', {
        'tool-panel:unfocus': this.cancelCreateNewBranch,
        'core:cancel': this.cancelCreateNewBranch,
        'core:confirm': this.createBranch
      })
    )
    this.createNew = false
  }

  update (props) {
    this.props = Object.assign({}, this.props, props)
    this.createNew = false
    return etch.update(this)
  }

  didSelectItem () {
    const branchName = this.refs.list.selectedOptions[0].text
    this.props.checkout(branchName)
  }

  createBranch (e) {
    if (e) e.stopImmediatePropagation()
    if (this.createNew) {
      const branchName = this.refs.editor.getText().trim()
      this.props.checkout(branchName, {createNew: true})
    } else {
      this.createNew = true
      return etch.update(this)
    }
  }

  cancelCreateNewBranch () {
    this.createNew = false
    etch.update(this)
  }

  render () {
    const newBranchEditor = (

        {this.textEditorWidget}

    )

    const selectBranchView = (
      <select ref='list' className='git-BranchView-item git-BranchView-select input-select' onchange={this.didSelectItem}>
        {this.props.branches.map(branch => {
          return <option value={branch} selected={branch === this.props.branchName}>{branch}</option>
        })}
      </select>
    )

    return (

        { this.createNew ? newBranchEditor : selectBranchView }
        <button ref='newBranchButton' className='git-BranchView-item git-BranchView-button btn'
                onclick={this.createBranch}> Create New Branch </button>

    )
  }

  destroy () {
    this.subscriptions.dispose()
    etch.destroy(this)
  }
}
<|endoftext|>