<commit_before>"use strict";
var Utils = {
  makeNullProto: function() {
    return {__proto__: null};
  },
  _onXHR: function () {
    if (this.readyState === 4 && this.status === 200) {
      this.onsuccess(this.responseText);
    }
  },
  fetchHttpContents: function(url, success) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.onreadystatechange = this._onXHR;
    req.onsuccess = success;
    req.send();
    return req;
  },
  _escapeRe: /[&<>]/g,
  _escapeCallback: function(c, n) {
    n = c.charCodeAt(0);
    return (n === 60) ? "<" : (n === 62) ? ">" : "&";
  },
  escapeHtml: function(s) {
    return s.replace(this._escapeRe, this._escapeCallback);
  },
  // "javascript" should be treated specially
  _nonUrlPrefixes: { about: 1, blob: 1, data: 1, mailto: 1, "view-source": 1 },
  _chromePrefixes: { "chrome-extension": 1, "chrome-search": 1 },
  _urlPrefix: /^[a-z]{3,}:\/\//,
  hasOrdinaryUrlPrefix: function(url) {
    return this._urlPrefix.test(url);
  },
  // url: only accept real tab's
  isRefusingIncognito: function(url) {
    url = url.toLowerCase();
    if (url.startsWith('chrome://')) {
      return !url.startsWith("chrome://downloads");
    }
    return !url.startsWith(Settings.CONST.ChromeInnerNewTab) && url.startsWith('chrome');
  },
  _nonENTlds: ".\u4e2d\u56fd.\u516c\u53f8.\u4f01\u4e1a",
  _tlds: ["", "",
    ".ac.ad.ae.af.ag.ai.al.am.an.ao.aq.ar.as.at.au.aw.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.eh.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.ss.st.su.sv.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tp.tr.tt.tv.tw.tz.ua.ug.uk.um.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.yu.za.zm.zw",
    ".biz.cat.com.dev.edu.gov.int.mil.mtn.net.org.pro.tel.top.xxx.xyz",
    ".aero.arpa.asia.club.coop.info.jobs.mobi.name.post.wang",
    ".local",
    ".museum.travel"
  ],
  _hostRe: /^([^:]+(:[^:]+)?@)?([^:]+|\[[^\]]+\])(:\d{2,5})?$/,
  _ipRe: /^(?:\d{1,3}\.){3}\d{1,3}$/,
  spacesRe: /[\s\u3000]+/g,
  _nonENTldRe: /[^a-z]/,
  _jsNotEscapeRe: /["\[\]{}\u00ff-\uffff]|%(?![\dA-F]{2}|[\da-f]{2})/,
  filePathRe: /^['"]?((?:[A-Za-z]:[\\/]|\/(?:Users|home|root)\/)[^'"]*)['"]?$/,
  convertToUrl: function(string, keyword) {
    if (string.substring(0, 11).toLowerCase() === "javascript:") {
      if (Settings.CONST.ChromeVersion < 46 && string.indexOf('%', 11) > 0
          && !this._jsNotEscapeRe.test(string)) {
        string = this.decodeURLPart(string);
      }
      return string;
    }
    var type = -1, expected = 1, index, index2, oldString, arr;
    // NOTE: here '\u3000' is changed to ' ', which may cause a 404 (for url)
    // NOTE: here a mulit-line string is be changed to single-line,
    //       which may be better
    oldString = string.replace(this.spacesRe, ' ').trim();
    string = oldString.toLowerCase();
    if ((index = string.indexOf(' ')) > 0) {
      string = string.substring(0, index);
    }
    if ((index = string.indexOf(':')) === 0) { type = 2; }
    else if (index === -1 || string.substring(index, index + 3) !== "://") {
      if (index !== -1 && string.substring(0, index) in this._nonUrlPrefixes) {
        index2 = string.length;
        type = index2 < oldString.length || index2 <= index
          || string.charCodeAt(index + 1) === 47 ? 2 : 0;
      } else if (string.startsWith("//")) {
        string = string.substring(2);
        expected = 3; index2 = 2;
      } else {
        index2 = 0;
      }
      if (type !== -1) {}
      else if ((index = string.indexOf('/')) <= 0) {
        if (index === 0 || string.length < oldString.length - index2) { type = 2; }
      } else if (string.length >= oldString.length - index2 ||
          ((index2 = string.charCodeAt(index + 1)) > 32 && index2 !== 47)) {
        string = string.substring(0, index);
      } else {
        type = 2;
      }
    }
    else if ((index2 = string.indexOf('/', index + 3)) === -1
        ? string.length < oldString.length
        : (expected = string.charCodeAt(index2 + 1), expected <= 32 || expected === 47 )
    ) {
      type = 2;
    }
    else if (this._nonENTldRe.test(string.substring(0, index))) {
      type = (string.substring(0, index) in this._chromePrefixes)
        && (index = string.charCodeAt(index + 3)) > 32 && index !== 47 ? 0 : 2;
    }
    else if (string.startsWith("file:")) {
      if (string.charCodeAt(7) !== 47) {
        type = 2;
      } else {
        index = string.charCodeAt(8);
        type = (index > 32 && index !== 47) ? 0 : 2; // `>32`: in case of NaN
      }
    }
    else if (string.startsWith("chrome:")) {
      type = string.length < oldString.length && string.indexOf('/', 9) === -1 ? 2 : 0;
    }
    else if (string.startsWith("vimium:")) {
      type = 0;
      oldString = chrome.runtime.getURL("/") + oldString.substring(9);
    } else {
      string = string.substring(index + 3, index2 !== -1 ? index2 : undefined);
      expected = 0;
    }

    if (type !== -1) {
    } else if (!(arr = this._hostRe.exec(string))) {
      type = 2;
    } else if ((string = arr[3]).indexOf(':') !== -1 || string.endsWith("localhost")) {
      type = expected;
    } else if ((index = string.lastIndexOf('.')) <= 0) {
      type = expected !== 1 ? expected : 2;
    } else if (this._ipRe.test(string)) {
      type = expected;
    } else if (!this.isTld(string.substring(index + 1))) {
      type = 2;
    } else if (expected !== 1 || string.length < oldString.length) {
      type = expected;
    } else if (arr[2] || arr[4] || !arr[1] || string.startsWith("ftp")) {
      type = 1;
    // the below means string is like "(?<=abc@)(uvw.)*xyz.tld"
    } else if (string.startsWith("mail") || string.indexOf(".mail") > 0
        || (index2 = string.indexOf(".")) === index) {
      type = 2;
    } else if (string.indexOf(".", ++index2) !== index) {
      type = 1;
    } else {
      type = this.isTld(string.substring(index2, index)) ? 2 : 1;
    }
    // window.type = type;
    return type === 0 ? oldString : type === 1
      ? ("http://" + oldString) : type === 3 ? ("http:" + oldString)
      : this.createSearchUrl(oldString.split(' '), keyword || "~");
  },
  isTld: function(tld) {
    if (this._nonENTldRe.test(tld)) {
      return this._nonENTlds.indexOf(tld) !== -1;
    } else if (tld.length < this._tlds.length) {
      return this._tlds[tld.length].indexOf(tld) > 0;
    }
    return false;
  },
  searchWordRe: /%[sS]/g,
  createSearchUrl: function(query, keyword) {
    query = this.createSearch(query, Settings.get("searchEngineMap")[keyword]).url;
    if (keyword != "~") {
      query = this.convertToUrl(query);
    }
    return query;
  },
  createSearch: function(query, pattern, $S) {
    var queryStr;
    if ($S != null ? ($S === true) : pattern.$S) {
      $S = query.join(' ');
    }
    if (pattern.$s) {
      queryStr = query.map(encodeURIComponent).join('+');
    }
    return {
      url: pattern.url.replace(this.searchWordRe, function(s) {
        return (s === "%s") ? queryStr : $S;
      }),
      $s: queryStr,
      $S: $S
    };
  },
  decodeURLPart: function(url) {
    try {
      url = decodeURIComponent(url);
    } catch (e) {}
    return url;
  },
  parseSearchEngines: function(str, map) {
    var ids, pair, key, val, obj, _i, _len, ind, rSlash = /[^\\]\//, rules = [],
    rEscapeSpace = /\\\s/g, rSpace = /\s/, rEscapeS = /\\s/g, rColon = /\\:/g,
    a = str.replace(/\\\n/g, '').split('\n'),
    func = function(key) {
      return (key = key.trim()) && (map[key] = obj);
    };
    for (_i = 0, _len = a.length; _i < _len; _i++) {
      val = a[_i].trim();
      if (!(val.charCodeAt(0) > 35)) { continue; } // mask: /[ !"#]/
      ind = 0;
      do {
        ind = val.indexOf(":", ind + 1);
      } while (val.charCodeAt(ind - 1)  === 92);
      if (ind <= 0 || !(key = val.substring(0, ind).trimRight())) continue;
      val = val.substring(ind + 1).trimLeft();
      if (!val) continue;
      val = val.replace(rEscapeSpace, "\\s");
      ind = val.search(rSpace);
      if (ind > 0) {
        str = val.substring(ind + 1).trimLeft();
        val = val.substring(0, ind);
        ind = str.indexOf("re=");
      } else {
        str = "";
      }
      val = val.replace(rEscapeS, " ");
      obj = {
        $S: val.indexOf("%S") + 1,
        $s: val.indexOf("%s") + 1,
        name: null,
        url: val
      };
      ids = key.replace(rColon, ":").split('|').filter(func);
      if (ids.length === 0) continue;
      if (ind === -1) {
        if (pair = this.reparseSearchUrl(obj)) {
          pair.push(ids[0]);
          rules.push(pair);
        }
      } else if (str.charCodeAt(ind + 3) === 47) {
        key = ind > 0 ? str.substring(0, ind).trimRight() : "";
        str = str.substring(ind + 4);
        ind = str.search(rSlash) + 1;
        val = str.substring(0, ind);
        str = str.substring(ind + 1);
        ind = str.search(rSpace);
        val = this.makeRegexp(val, ind >= 0 ? str.substring(0, ind) : str);
        if (val) {
          rules.push([key, val, ids[0]]);
        }
        str = ind >= 0 ? str.substring(ind + 1).trimLeft() : "";
      } else {
        str = str.substring(ind + 3).trimLeft();
      }
      obj.name = str ? this.decodeURLPart(str) : ids[ids.length - 1];
    }
    return rules;
  },
  reparseSearchUrl: function (pattern) {
    var url, ind = pattern.$s || pattern.$S, prefix, str, ind2;
    if (!ind) { return; }
    url = pattern.url.toLowerCase();
    if (!(this.hasOrdinaryUrlPrefix(url) || url.startsWith("chrome-"))) { return; }
    prefix = url.substring(0, ind - 1);
    if (ind = (prefix.lastIndexOf("?") + 1) || (prefix.lastIndexOf("#") + 1)) {
      str = prefix.substring(ind);
      if (ind2 = str.lastIndexOf("&") + 1) {
        str = str.substring(ind2);
      }
      if (str && str !== "=" && !str.endsWith("/")) {
        return this.makeReparser(prefix.substring(0, ind - 1), "[?#&]", str, "([^&#]*)")
      }
    }
    url = url.substring(prefix.length + 2);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      url = url.substring(0, ind);
    }
    return this.makeReparser(prefix, "^([^?#]*)", url, "");
  },
  escapeAllRe: /[\$\(\)\*\+\.\?\[\\\]\^\{\|\}]/g,
  _spaceOrPlusRe: /\\\+|%20| /g,
  makeReparser: function(head, prefix, matched_body, suffix) {
    matched_body = matched_body.replace(this.escapeAllRe, "\\$&"
      ).replace(this._spaceOrPlusRe, "(?:\\+|%20)");
    if (head.startsWith("https://")) {
      head = "http" + head.substring(5);
    } else if (head.startsWith("vimium://")) {
      head = chrome.runtime.getURL("/") + head.substring(9);
    }
    return [head, new RegExp(prefix + matched_body + suffix, "i")];
  },
  makeRegexp: function(pattern, suffix) {
    try {
      return new RegExp(pattern, suffix);
    } catch (e) {
      console.log("%c/%s/%s%c %s", "color:#C41A16;"
        , pattern, suffix, "color:auto;", "is not a valid regexp.");
    }
    return null;
  },
  Decoder: null,
  upperRe: /[A-Z]/
};

if (!String.prototype.startsWith) {
String.prototype.startsWith = function(s) {
  return this.length >= s.length && this.lastIndexOf(s, 0) === 0;
};
String.prototype.endsWith || (String.prototype.endsWith = function(s) {
  var i = this.length - s.length;
  return i >= 0 && this.indexOf(s, i) === i;
});
}
<commit_msg>a small change: reparseSearchUrl: simpler logic<commit_after>"use strict";
var Utils = {
  makeNullProto: function() {
    return {__proto__: null};
  },
  _onXHR: function () {
    if (this.readyState === 4 && this.status === 200) {
      this.onsuccess(this.responseText);
    }
  },
  fetchHttpContents: function(url, success) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.onreadystatechange = this._onXHR;
    req.onsuccess = success;
    req.send();
    return req;
  },
  _escapeRe: /[&<>]/g,
  _escapeCallback: function(c, n) {
    n = c.charCodeAt(0);
    return (n === 60) ? "<" : (n === 62) ? ">" : "&";
  },
  escapeHtml: function(s) {
    return s.replace(this._escapeRe, this._escapeCallback);
  },
  // "javascript" should be treated specially
  _nonUrlPrefixes: { about: 1, blob: 1, data: 1, mailto: 1, "view-source": 1 },
  _chromePrefixes: { "chrome-extension": 1, "chrome-search": 1 },
  _urlPrefix: /^[a-z]{3,}:\/\//,
  hasOrdinaryUrlPrefix: function(url) {
    return this._urlPrefix.test(url);
  },
  // url: only accept real tab's
  isRefusingIncognito: function(url) {
    url = url.toLowerCase();
    if (url.startsWith('chrome://')) {
      return !url.startsWith("chrome://downloads");
    }
    return !url.startsWith(Settings.CONST.ChromeInnerNewTab) && url.startsWith('chrome');
  },
  _nonENTlds: ".\u4e2d\u56fd.\u516c\u53f8.\u4f01\u4e1a",
  _tlds: ["", "",
    ".ac.ad.ae.af.ag.ai.al.am.an.ao.aq.ar.as.at.au.aw.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.eh.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.ss.st.su.sv.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tp.tr.tt.tv.tw.tz.ua.ug.uk.um.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.yu.za.zm.zw",
    ".biz.cat.com.dev.edu.gov.int.mil.mtn.net.org.pro.tel.top.xxx.xyz",
    ".aero.arpa.asia.club.coop.info.jobs.mobi.name.post.wang",
    ".local",
    ".museum.travel"
  ],
  _hostRe: /^([^:]+(:[^:]+)?@)?([^:]+|\[[^\]]+\])(:\d{2,5})?$/,
  _ipRe: /^(?:\d{1,3}\.){3}\d{1,3}$/,
  spacesRe: /[\s\u3000]+/g,
  _nonENTldRe: /[^a-z]/,
  _jsNotEscapeRe: /["\[\]{}\u00ff-\uffff]|%(?![\dA-F]{2}|[\da-f]{2})/,
  filePathRe: /^['"]?((?:[A-Za-z]:[\\/]|\/(?:Users|home|root)\/)[^'"]*)['"]?$/,
  convertToUrl: function(string, keyword) {
    if (string.substring(0, 11).toLowerCase() === "javascript:") {
      if (Settings.CONST.ChromeVersion < 46 && string.indexOf('%', 11) > 0
          && !this._jsNotEscapeRe.test(string)) {
        string = this.decodeURLPart(string);
      }
      return string;
    }
    var type = -1, expected = 1, index, index2, oldString, arr;
    // NOTE: here '\u3000' is changed to ' ', which may cause a 404 (for url)
    // NOTE: here a mulit-line string is be changed to single-line,
    //       which may be better
    oldString = string.replace(this.spacesRe, ' ').trim();
    string = oldString.toLowerCase();
    if ((index = string.indexOf(' ')) > 0) {
      string = string.substring(0, index);
    }
    if ((index = string.indexOf(':')) === 0) { type = 2; }
    else if (index === -1 || string.substring(index, index + 3) !== "://") {
      if (index !== -1 && string.substring(0, index) in this._nonUrlPrefixes) {
        index2 = string.length;
        type = index2 < oldString.length || index2 <= index
          || string.charCodeAt(index + 1) === 47 ? 2 : 0;
      } else if (string.startsWith("//")) {
        string = string.substring(2);
        expected = 3; index2 = 2;
      } else {
        index2 = 0;
      }
      if (type !== -1) {}
      else if ((index = string.indexOf('/')) <= 0) {
        if (index === 0 || string.length < oldString.length - index2) { type = 2; }
      } else if (string.length >= oldString.length - index2 ||
          ((index2 = string.charCodeAt(index + 1)) > 32 && index2 !== 47)) {
        string = string.substring(0, index);
      } else {
        type = 2;
      }
    }
    else if ((index2 = string.indexOf('/', index + 3)) === -1
        ? string.length < oldString.length
        : (expected = string.charCodeAt(index2 + 1), expected <= 32 || expected === 47 )
    ) {
      type = 2;
    }
    else if (this._nonENTldRe.test(string.substring(0, index))) {
      type = (string.substring(0, index) in this._chromePrefixes)
        && (index = string.charCodeAt(index + 3)) > 32 && index !== 47 ? 0 : 2;
    }
    else if (string.startsWith("file:")) {
      if (string.charCodeAt(7) !== 47) {
        type = 2;
      } else {
        index = string.charCodeAt(8);
        type = (index > 32 && index !== 47) ? 0 : 2; // `>32`: in case of NaN
      }
    }
    else if (string.startsWith("chrome:")) {
      type = string.length < oldString.length && string.indexOf('/', 9) === -1 ? 2 : 0;
    }
    else if (string.startsWith("vimium:")) {
      type = 0;
      oldString = chrome.runtime.getURL("/") + oldString.substring(9);
    } else {
      string = string.substring(index + 3, index2 !== -1 ? index2 : undefined);
      expected = 0;
    }

    if (type !== -1) {
    } else if (!(arr = this._hostRe.exec(string))) {
      type = 2;
    } else if ((string = arr[3]).indexOf(':') !== -1 || string.endsWith("localhost")) {
      type = expected;
    } else if ((index = string.lastIndexOf('.')) <= 0) {
      type = expected !== 1 ? expected : 2;
    } else if (this._ipRe.test(string)) {
      type = expected;
    } else if (!this.isTld(string.substring(index + 1))) {
      type = 2;
    } else if (expected !== 1 || string.length < oldString.length) {
      type = expected;
    } else if (arr[2] || arr[4] || !arr[1] || string.startsWith("ftp")) {
      type = 1;
    // the below means string is like "(?<=abc@)(uvw.)*xyz.tld"
    } else if (string.startsWith("mail") || string.indexOf(".mail") > 0
        || (index2 = string.indexOf(".")) === index) {
      type = 2;
    } else if (string.indexOf(".", ++index2) !== index) {
      type = 1;
    } else {
      type = this.isTld(string.substring(index2, index)) ? 2 : 1;
    }
    // window.type = type;
    return type === 0 ? oldString : type === 1
      ? ("http://" + oldString) : type === 3 ? ("http:" + oldString)
      : this.createSearchUrl(oldString.split(' '), keyword || "~");
  },
  isTld: function(tld) {
    if (this._nonENTldRe.test(tld)) {
      return this._nonENTlds.indexOf(tld) !== -1;
    } else if (tld.length < this._tlds.length) {
      return this._tlds[tld.length].indexOf(tld) > 0;
    }
    return false;
  },
  searchWordRe: /%[sS]/g,
  createSearchUrl: function(query, keyword) {
    query = this.createSearch(query, Settings.get("searchEngineMap")[keyword]).url;
    if (keyword != "~") {
      query = this.convertToUrl(query);
    }
    return query;
  },
  createSearch: function(query, pattern, $S) {
    var queryStr;
    if ($S != null ? ($S === true) : pattern.$S) {
      $S = query.join(' ');
    }
    if (pattern.$s) {
      queryStr = query.map(encodeURIComponent).join('+');
    }
    return {
      url: pattern.url.replace(this.searchWordRe, function(s) {
        return (s === "%s") ? queryStr : $S;
      }),
      $s: queryStr,
      $S: $S
    };
  },
  decodeURLPart: function(url) {
    try {
      url = decodeURIComponent(url);
    } catch (e) {}
    return url;
  },
  parseSearchEngines: function(str, map) {
    var ids, pair, key, val, obj, _i, _len, ind, rSlash = /[^\\]\//, rules = [],
    rEscapeSpace = /\\\s/g, rSpace = /\s/, rEscapeS = /\\s/g, rColon = /\\:/g,
    a = str.replace(/\\\n/g, '').split('\n'),
    func = function(key) {
      return (key = key.trim()) && (map[key] = obj);
    };
    for (_i = 0, _len = a.length; _i < _len; _i++) {
      val = a[_i].trim();
      if (!(val.charCodeAt(0) > 35)) { continue; } // mask: /[ !"#]/
      ind = 0;
      do {
        ind = val.indexOf(":", ind + 1);
      } while (val.charCodeAt(ind - 1)  === 92);
      if (ind <= 0 || !(key = val.substring(0, ind).trimRight())) continue;
      val = val.substring(ind + 1).trimLeft();
      if (!val) continue;
      val = val.replace(rEscapeSpace, "\\s");
      ind = val.search(rSpace);
      if (ind > 0) {
        str = val.substring(ind + 1).trimLeft();
        val = val.substring(0, ind);
        ind = str.indexOf("re=");
      } else {
        str = "";
      }
      val = val.replace(rEscapeS, " ");
      obj = {
        $S: val.indexOf("%S") + 1,
        $s: val.indexOf("%s") + 1,
        name: null,
        url: val
      };
      ids = key.replace(rColon, ":").split('|').filter(func);
      if (ids.length === 0) continue;
      if (ind === -1) {
        if (pair = this.reparseSearchUrl(obj)) {
          pair.push(ids[0]);
          rules.push(pair);
        }
      } else if (str.charCodeAt(ind + 3) === 47) {
        key = ind > 0 ? str.substring(0, ind).trimRight() : "";
        str = str.substring(ind + 4);
        ind = str.search(rSlash) + 1;
        val = str.substring(0, ind);
        str = str.substring(ind + 1);
        ind = str.search(rSpace);
        val = this.makeRegexp(val, ind >= 0 ? str.substring(0, ind) : str);
        if (val) {
          rules.push([key, val, ids[0]]);
        }
        str = ind >= 0 ? str.substring(ind + 1).trimLeft() : "";
      } else {
        str = str.substring(ind + 3).trimLeft();
      }
      obj.name = str ? this.decodeURLPart(str) : ids[ids.length - 1];
    }
    return rules;
  },
  reparseSearchUrl: function (pattern) {
    var url, ind = pattern.$s || pattern.$S, prefix, str, ind2;
    if (!ind) { return; }
    url = pattern.url.toLowerCase();
    if (!(this.hasOrdinaryUrlPrefix(url) || url.startsWith("chrome-"))) { return; }
    prefix = url.substring(0, ind - 1);
    if (ind = (prefix.lastIndexOf("?") + 1) || (prefix.lastIndexOf("#") + 1)) {
      str = prefix.substring(ind);
      if (ind2 = str.lastIndexOf("&") + 1) {
        str = str.substring(ind2);
      }
      if (str && str.indexOf("=") >= 1) {
        return this.makeReparser(prefix.substring(0, ind - 1), "[?#&]", str, "([^&#]*)")
      }
    }
    url = url.substring(prefix.length + 2);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      url = url.substring(0, ind);
    }
    return this.makeReparser(prefix, "^([^?#]*)", url, "");
  },
  escapeAllRe: /[\$\(\)\*\+\.\?\[\\\]\^\{\|\}]/g,
  _spaceOrPlusRe: /\\\+|%20| /g,
  makeReparser: function(head, prefix, matched_body, suffix) {
    matched_body = matched_body.replace(this.escapeAllRe, "\\$&"
      ).replace(this._spaceOrPlusRe, "(?:\\+|%20)");
    if (head.startsWith("https://")) {
      head = "http" + head.substring(5);
    } else if (head.startsWith("vimium://")) {
      head = chrome.runtime.getURL("/") + head.substring(9);
    }
    return [head, new RegExp(prefix + matched_body + suffix, "i")];
  },
  makeRegexp: function(pattern, suffix) {
    try {
      return new RegExp(pattern, suffix);
    } catch (e) {
      console.log("%c/%s/%s%c %s", "color:#C41A16;"
        , pattern, suffix, "color:auto;", "is not a valid regexp.");
    }
    return null;
  },
  Decoder: null,
  upperRe: /[A-Z]/
};

if (!String.prototype.startsWith) {
String.prototype.startsWith = function(s) {
  return this.length >= s.length && this.lastIndexOf(s, 0) === 0;
};
String.prototype.endsWith || (String.prototype.endsWith = function(s) {
  var i = this.length - s.length;
  return i >= 0 && this.indexOf(s, i) === i;
});
}
<|endoftext|>


<commit_before>const {
  addFields,
  addArguments,
  createTypeFetcher,
} = require('olymp-graphql/server');
const { get, set, lowerFirst } = require('lodash');

export default {
  // aggregation
  name: 'relation',
  description: 'Marks a type as a relative.',
  resolveStatic: {
    enter(node, directive, { resolvers, parent, ancestors, ast }) {
      const isList = node.type.kind === 'ListType';
      const type = isList ? node.type.type : node.type;

      const argProperty =
        directive.arguments.length &&
        directive.arguments.find(x => x.name.value === 'property');
      const argRelationType =
        directive.arguments.length &&
        directive.arguments.find(x => x.name.value === 'type');
      const relationType = get(
        argRelationType,
        'value.value',
        isList ? '1-n' : '1-1'
      );

      const leftType = ancestors[ancestors.length - 1].name.value;
      const leftTable = ancestors[
        ancestors.length - 1
      ].name.value.toLowerCase();
      const leftField = node.name.value;
      const leftNode = parent;
      const rightType = type.name.value;
      const rightTable = type.name.value.toLowerCase();
      const rightField =
        get(argProperty, 'value.value') || lowerFirst(leftTable);
      const rightNode = createTypeFetcher(
        node => get(node, 'type.name.value') === rightType
      )(ast);

      // one-to-one / one-to-many
      // Only add xxxId field to store/access the id
      if (relationType === '1-1') {
        addFields(ast, leftNode, `${leftField}Id: String`);
        set(resolvers, `${leftType}.${leftField}`, (source, args, { monk }) =>
          monk.collection(rightTable).findOne({
            id: source[`${leftField}Id`],
          })
        );
      } else if (relationType === '1-n') {
        // Add list accessor and xxxIds field since dealing with many
        // addInputTypes(rightTable, ast);
        /* addArguments(
          ast,
          node,
          `query: ${rightType}Query, sort: ${rightType}Sort, limit: Int, skip: Int`
        );*/
        addFields(ast, leftNode, `${leftField}Id: String`);
        set(resolvers, `${leftType}.${leftField}`, (source, args, { monk }) =>
          monk.collection('item').findOne({
            id: source[`${leftField}Id`],
            _type: rightTable,
          })
        );
        addFields(ast, leftNode, `${rightField}: [${leftType}]`);
        set(resolvers, `${rightType}.${rightField}`, (source, args, { monk }) =>
          monk.collection(leftTable).find({ [`${leftField}Id`]: source.id })
        );
      }

      /* if (rightField) {
        const rightNode = ast.definitions.find(
          x => x.name && x.name.value === node.type.name.value
        );

        if (relationType === '1-n') {
          addFields(ast, rightNode, `${rightField}: [${leftType}]`);
          set(resolvers, `${rightType}.${rightField}`, (source, args, { monk }) =>
            monk.collection(leftTable).find({})
          );
        } else if (relationType === '1-1') {
          addFields(ast, rightNode, `${rightField}: ${leftType}`);
          set(resolvers, `${rightType}.${rightField}`, (source, args, { monk }) =>
            monk.collection(leftTable).findOne({})
          );
        }
      }*/
    },
  },
};
<commit_msg>fix relation<commit_after>const {
  addFields,
  addArguments,
  createTypeFetcher,
} = require('olymp-graphql/server');
const { get, set, lowerFirst } = require('lodash');

export default {
  // aggregation
  name: 'relation',
  description: 'Marks a type as a relative.',
  resolveStatic: {
    enter(node, directive, { resolvers, parent, ancestors, ast }) {
      const isList = node.type.kind === 'ListType';
      const type = isList ? node.type.type : node.type;

      const argProperty =
        directive.arguments.length &&
        directive.arguments.find(x => x.name.value === 'property');
      const argRelationType =
        directive.arguments.length &&
        directive.arguments.find(x => x.name.value === 'type');
      const relationType = get(
        argRelationType,
        'value.value',
        isList ? '1-n' : '1-1'
      );

      const leftType = ancestors[ancestors.length - 1].name.value;
      const leftTable = ancestors[
        ancestors.length - 1
      ].name.value.toLowerCase();
      const leftField = node.name.value;
      const leftNode = parent;
      const rightType = type.name.value;
      const rightTable = type.name.value.toLowerCase();
      const rightField =
        get(argProperty, 'value.value') || lowerFirst(leftTable);
      const rightNode = createTypeFetcher(
        node => get(node, 'type.name.value') === rightType
      )(ast);

      // one-to-one / one-to-many
      // Only add xxxId field to store/access the id
      if (relationType === '1-1') {
        console.log(relationType, `${leftType}.${leftField}`);
        addFields(ast, leftNode, `${leftField}Id: String`);
        set(resolvers, `${leftType}.${leftField}`, (source, args, { monk }) =>
          monk.collection('item').findOne({
            id: source[`${leftField}Id`],
            _type: rightTable,
          })
        );
      } else if (relationType === '1-n') {
        // Add list accessor and xxxIds field since dealing with many
        // addInputTypes(rightTable, ast);
        /* addArguments(
          ast,
          node,
          `query: ${rightType}Query, sort: ${rightType}Sort, limit: Int, skip: Int`
        );*/
        addFields(ast, leftNode, `${leftField}Id: String`);
        set(resolvers, `${leftType}.${leftField}`, (source, args, { monk }) =>
          monk.collection('item').findOne({
            id: source[`${leftField}Id`],
            _type: rightTable,
          })
        );
        addFields(ast, leftNode, `${rightField}: [${leftType}]`);
        set(resolvers, `${rightType}.${rightField}`, (source, args, { monk }) =>
          monk.collection(leftTable).find({ [`${leftField}Id`]: source.id })
        );
      }

      /* if (rightField) {
        const rightNode = ast.definitions.find(
          x => x.name && x.name.value === node.type.name.value
        );

        if (relationType === '1-n') {
          addFields(ast, rightNode, `${rightField}: [${leftType}]`);
          set(resolvers, `${rightType}.${rightField}`, (source, args, { monk }) =>
            monk.collection(leftTable).find({})
          );
        } else if (relationType === '1-1') {
          addFields(ast, rightNode, `${rightField}: ${leftType}`);
          set(resolvers, `${rightType}.${rightField}`, (source, args, { monk }) =>
            monk.collection(leftTable).findOne({})
          );
        }
      }*/
    },
  },
};
<|endoftext|>


<commit_before>'use strict';

// Lock interactive feature while animating
function disableInteractiveness() {
  Game.Image.allowInteraction = false;
}

// Unlock interactive feature
function enableInteractiveness() {
  Game.Image.allowInteraction = true;
}

Game.Image = function(texture) {
  // Class initialization
  arguments[0] = resources["img/" + arguments[0]].texture;
  PIXI.Sprite.apply(this, arguments); // Getting the PIXI.Sprite arguments and allowing to run its constructor
  this.anchor.set(0.5, 0.5); // Default anchor at center
  this.interactive = false;

  // PROPERTIES
  // Static properties
  Game.Image.allowInteraction = true;

  // Public properties
  this.z_order = 5;

  // Private properties
  var animationDelay = 33; // delay between frames of "Change value" methods
  var objInstance = this; // reference to this object

  // METHODS
  // Public methods
  // Set value methods (changes instantly)
  this.setPosition = function(coordX, coordY) {
    this.x = coordX;
    this.y = coordY;
  }
  this.setScale = function(newScale) {
    this.scale.set(newScale, newScale);
  }
  this.setAlpha = function(newAlpha) {
    this.alpha = newAlpha;
  }
  this.setZorder = function(newZorder) {
    this.z_order = newZorder;
  }
  this.setTint = function(red, green, blue) {
    this.tint = (red << 16) + (green << 8) + blue;
  }
  this.setBrightness = function(newBrightness) {
    this.setTint(newBrightness, newBrightness, newBrightness);
  }
  this.setRotation = function(newRotation) {
    this.rotation = newRotation * (Math.PI / 180); // Changing from radians to degree
  }
  this.setHeight = function(newHeight) {
    this.height = newHeight;
    this.scale.x = this.scale.y;
  }
  this.setWidth = function(newWidth) {
    this.width = newWidth;
    this.scale.y = this.scale.x;
  }
  this.setAnchor = function(anchorX, anchorY) {
    this.anchor.set(anchorX, anchorY);
  }
  this.setInteractive = function(isInteractive) {
    this.interactive = isInteractive;
  }

  // Get value methods
  this.getScale = function() {
    return this.scale.x;
  }
  this.getBrightness = function() {
    return this.tint / 65793;
  }

  // Change value methods (animations that change properties within time)
  this.changeAlpha = function(newAlpha, time) {
    this.filters = null;
    var elapsedTime = 0;
    var initialAlpha = this.alpha;
    var fadeInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < time) {
        objInstance.alpha = initialAlpha + (newAlpha - initialAlpha) * (elapsedTime / time);
      }
      else {
        objInstance.alpha = newAlpha;
        clearInterval(fadeInterval); // Stop calling itself
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.changeBrightness = function(newBrightness, time) {
    this.filters = null;
    var elapsedTime = 0;
    var animationTime = time;
    var initialBrightness = this.getBrightness();
    var changeBrightnessInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < animationTime) {
        objInstance.setBrightness(initialBrightness + Math.round((newBrightness - initialBrightness) * (elapsedTime / animationTime)));
      }
      else {
        objInstance.setBrightness(newBrightness);
        clearInterval(changeBrightnessInterval); // Stop calling itself
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.changeScale = function(newScale, time) {
    objInstance.filters = null;
    var elapsedTime = 0;
    var animationTime = time;
    var initialScale = objInstance.getScale();
    var changeScaleInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < animationTime) {
        objInstance.setScale(initialScale + ((newScale - initialScale) * (elapsedTime / animationTime)));
      }
      else {
        objInstance.setScale(newScale);
        clearInterval(changeScaleInterval); // Stop calling itself
        updateGlowRectangle();
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.move = function(newX, newY, time) {
    var elapsedTime = 0;
    var animationTime = time;
    var initialPosition = {x: this.x, y: this.y};
    objInstance.filters = null;
    var moveInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < animationTime) {
        var movement = moveFunction(elapsedTime, animationTime);
        objInstance.setPosition(initialPosition.x + ((newX - initialPosition.x) * movement), initialPosition.y + ((newY - initialPosition.y) * movement));
      }
      else {
        objInstance.setPosition(newX, newY);
        clearInterval(moveInterval); // Stop calling itself
        updateGlowRectangle();
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.addGlow = function(strength = 10) {
    updateGlowRectangle();
    // distance, outerStrength, innerStrength, color, quality
    this.filters = [new PIXI.filters.GlowFilter(strength, 2, 1, 0xFFFFFF, 1)];
    UpdateScreen();
  }

  this.removeGlow = function() {
    this.filters = null;
    UpdateScreen();
  }

  // Enable-Disable Methods
  this.disable = function() {
    this.filters = null;
    this.visible = false;
  }
  this.enable = function() {
    this.visible = true;
    UpdateScreen();
  }

  // Implementing the mouseover and mouseout methods
  this.mouseover = function(mouse) {
    if (Game.Image.allowInteraction && this.onMouseOver != null)
      setTimeout(function() {
        objInstance.onMouseOver();
      }, 25);
  }
  this.mouseout = function(mouse) {
    if (Game.Image.allowInteraction && this.onMouseOut != null)
      this.onMouseOut();
  }
  this.click = function(mouse) {
    if (Game.Image.allowInteraction && this.onClick != null) {
      this.onClick();
    }
  }

  // Return the graphic(s) to be drawn
  this.draw = function(stage) {
    stage.addChild(this);
  }

  // Private methods
  // Glow area
  var updateGlowRectangle = function() {
    objInstance.filterArea = new Rectangle( objInstance.x - objInstance.width/2 - 15,
                                            objInstance.y - objInstance.height/2 - 15,
                                            objInstance.width + 30,
                                            objInstance.height + 30);
  }

  // Returns values between 0 and 1
  // 0 is the initial position
  // 1 is the final position
  var moveFunction = function(elapsedTime, animationTime) {
    var x = elapsedTime / animationTime;
    return 0.5*Math.sin((10*x/Math.PI) - 0.5*Math.PI)+0.5;
  }

}

Game.Image.prototype = Object.create(PIXI.Sprite.prototype); // Inherance from PIXI.Sprite
Game.Image.prototype.constructor = Game.Image;
<commit_msg>fixed some bugs of mouseout method on Image class<commit_after>'use strict';

// Lock interactive feature while animating
function disableInteractiveness() {
  Game.Image.allowInteraction = false;
}

// Unlock interactive feature
function enableInteractiveness() {
  Game.Image.allowInteraction = true;
}

Game.Image = function(texture) {
  // Class initialization
  arguments[0] = resources["img/" + arguments[0]].texture;
  PIXI.Sprite.apply(this, arguments); // Getting the PIXI.Sprite arguments and allowing to run its constructor
  this.anchor.set(0.5, 0.5); // Default anchor at center
  this.interactive = false;

  // PROPERTIES
  // Static properties
  Game.Image.allowInteraction = true;

  // Public properties
  this.z_order = 5;

  // Private properties
  var animationDelay = 33; // delay between frames of "Change value" methods
  var objInstance = this; // reference to this object

  // METHODS
  // Public methods
  // Set value methods (changes instantly)
  this.setPosition = function(coordX, coordY) {
    this.x = coordX;
    this.y = coordY;
  }
  this.setScale = function(newScale) {
    this.scale.set(newScale, newScale);
  }
  this.setAlpha = function(newAlpha) {
    this.alpha = newAlpha;
  }
  this.setZorder = function(newZorder) {
    this.z_order = newZorder;
  }
  this.setTint = function(red, green, blue) {
    this.tint = (red << 16) + (green << 8) + blue;
  }
  this.setBrightness = function(newBrightness) {
    this.setTint(newBrightness, newBrightness, newBrightness);
  }
  this.setRotation = function(newRotation) {
    this.rotation = newRotation * (Math.PI / 180); // Changing from radians to degree
  }
  this.setHeight = function(newHeight) {
    this.height = newHeight;
    this.scale.x = this.scale.y;
  }
  this.setWidth = function(newWidth) {
    this.width = newWidth;
    this.scale.y = this.scale.x;
  }
  this.setAnchor = function(anchorX, anchorY) {
    this.anchor.set(anchorX, anchorY);
  }
  this.setInteractive = function(isInteractive) {
    this.interactive = isInteractive;
  }

  // Get value methods
  this.getScale = function() {
    return this.scale.x;
  }
  this.getBrightness = function() {
    return this.tint / 65793;
  }

  // Change value methods (animations that change properties within time)
  this.changeAlpha = function(newAlpha, time) {
    this.filters = null;
    var elapsedTime = 0;
    var initialAlpha = this.alpha;
    var fadeInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < time) {
        objInstance.alpha = initialAlpha + (newAlpha - initialAlpha) * (elapsedTime / time);
      }
      else {
        objInstance.alpha = newAlpha;
        clearInterval(fadeInterval); // Stop calling itself
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.changeBrightness = function(newBrightness, time) {
    this.filters = null;
    var elapsedTime = 0;
    var animationTime = time;
    var initialBrightness = this.getBrightness();
    var changeBrightnessInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < animationTime) {
        objInstance.setBrightness(initialBrightness + Math.round((newBrightness - initialBrightness) * (elapsedTime / animationTime)));
      }
      else {
        objInstance.setBrightness(newBrightness);
        clearInterval(changeBrightnessInterval); // Stop calling itself
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.changeScale = function(newScale, time) {
    objInstance.filters = null;
    var elapsedTime = 0;
    var animationTime = time;
    var initialScale = objInstance.getScale();
    var changeScaleInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < animationTime) {
        objInstance.setScale(initialScale + ((newScale - initialScale) * (elapsedTime / animationTime)));
      }
      else {
        objInstance.setScale(newScale);
        clearInterval(changeScaleInterval); // Stop calling itself
        updateGlowRectangle();
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.move = function(newX, newY, time) {
    var elapsedTime = 0;
    var animationTime = time;
    var initialPosition = {x: this.x, y: this.y};
    objInstance.filters = null;
    var moveInterval = setInterval( function() {
      elapsedTime += animationDelay;
      if (elapsedTime < animationTime) {
        var movement = moveFunction(elapsedTime, animationTime);
        objInstance.setPosition(initialPosition.x + ((newX - initialPosition.x) * movement), initialPosition.y + ((newY - initialPosition.y) * movement));
      }
      else {
        objInstance.setPosition(newX, newY);
        clearInterval(moveInterval); // Stop calling itself
        updateGlowRectangle();
      }
      UpdateScreen();
    }, animationDelay);
  }

  this.addGlow = function(strength = 10) {
    updateGlowRectangle();
    // distance, outerStrength, innerStrength, color, quality
    this.filters = [new PIXI.filters.GlowFilter(strength, 2, 1, 0xFFFFFF, 1)];
    UpdateScreen();
  }

  this.removeGlow = function() {
    this.filters = null;
    UpdateScreen();
  }

  // Enable-Disable Methods
  this.disable = function() {
    this.filters = null;
    this.visible = false;
  }
  this.enable = function() {
    this.visible = true;
    UpdateScreen();
  }

  // Implementing the mouseover and mouseout methods
  this.mouseover = function(mouse) {
    if (Game.Image.allowInteraction && this.onMouseOver != null)
      setTimeout(function() {
        objInstance.onMouseOver();
      }, 10);
  }
  this.mouseout = function(mouse) {
    if (Game.Image.allowInteraction && this.onMouseOut != null)
      this.onMouseOut();
  }
  this.click = function(mouse) {
    if (Game.Image.allowInteraction && this.onClick != null) {
      this.onClick();
    }
  }

  // Return the graphic(s) to be drawn
  this.draw = function(stage) {
    stage.addChild(this);
  }

  // Private methods
  // Glow area
  var updateGlowRectangle = function() {
    objInstance.filterArea = new Rectangle( objInstance.x - objInstance.width/2 - 15,
                                            objInstance.y - objInstance.height/2 - 15,
                                            objInstance.width + 30,
                                            objInstance.height + 30);
  }

  // Returns values between 0 and 1
  // 0 is the initial position
  // 1 is the final position
  var moveFunction = function(elapsedTime, animationTime) {
    var x = elapsedTime / animationTime;
    return 0.5*Math.sin((10*x/Math.PI) - 0.5*Math.PI)+0.5;
  }

}

Game.Image.prototype = Object.create(PIXI.Sprite.prototype); // Inherance from PIXI.Sprite
Game.Image.prototype.constructor = Game.Image;
<|endoftext|>


<commit_before>/**
 * Props params:
 *
 * playCallback:    Function to be called with response from server. should take one parameter.
 * calc:            Only used when testing hardware.
 * postURL:         The url after the globally set url.
 * formDataBuilder  Function to create formdata containing information to send. Function takes:.
 *                                                                                video(blob) as first param
 *                                                                                filename as second param.
 * recButtonID:     [Optional] Button to start recording video. If left out it autorecords on render.
 * stopButtonID:    Id of the button to stop recording video. Might post video as well(read about postButtonID).
 * postButtonID:    [Optional] Id of the post video button. If left out the stop button posts the video to server.
 * replay:          replay="true" if you want the recording to be playable in the same video tag.
 * fileName:        The name the video recording should have.
 * camOnLoad:       camOnLoad="true" If the camera is to start before recording. User will have to click
 *                  stopbutton to be able to reuse camera.
 * autoRecord:      autoRecord="true" if the camera should start recording when class is instantiated.
 *
 *
 * watch HardwareTest.js for example of use.
 */

var Recorder = React.createClass({
    componentDidMount: function() {
        var props = this.props;

        //used for hw testing
        var blobsize;
        var sendTime;

        var cameraStartOnLoad = (typeof props.camOnLoad === "undefined") ?
                        false : props.camOnLoad == "true";
        var cameraStarted = false;
        var startRecordButtonExists = (typeof props.recButtonID !== "undefined");
        var shouldAutoRecord = (typeof props.autoRecord === "undefined") ?
                        !startRecordButtonExists : props.autoRecord == "true";

        var replay = props.replay == "true";
        var stopButton = document.getElementById(props.stopButtonID);
        var previewElement;
        var recordAudio, recordVideo;
        var mediaStream;

        if(startRecordButtonExists) {
            var recordButton = document.getElementById(props.recButtonID);
            if(cameraStarted) {
                recordButton.disabled = true;
            }
        }

        if(typeof props.calc !== "undefined")
            previewElement = document.getElementById('prev-test');
        else
            previewElement = document.getElementById('preview');

        navigator.getUserMedia = ( navigator.getUserMedia ||
                                  navigator.webkitGetUserMedia ||
        navigator.mediaDevices.getUserMedia ||
                                  navigator.msGetUserMedia);

        if(cameraStartOnLoad) {
            startCamera();
        }

        /* The onclick function for the start record button if it exists. */
        if(startRecordButtonExists) {
            recordButton.onclick = startRecord;
        }

        /* The onclick function for the stop record button. */
        stopButton.onclick = stopRecording;

        /* Will start recording and start the webcam if not enabled. */
        function startRecord() {
            if(!cameraStarted) {
                startCamera();
                window.setTimeout(function() {
                    recordAudio.startRecording();
                    recordingStarted();
                }, 1000);
            } else {
                recordAudio.startRecording();
                recordingStarted();
            }
        }

        function recordingStarted() {
            if(startRecordButtonExists) {
                recordButton.disabled = true;
            }
            stopButton.disabled = false;

            if(typeof props.calc !== "undefined") {
                document.getElementById("test-rec-text").innerHTML = "🔴";
            }
            else {
                document.getElementById("rec-text").innerHTML = "🔴";
            }
        }

        /* Start stream from webcam and start recording if autoRecording is true,
         * will record with forced low settings for smaller files. */
        function startCamera () {
            navigator.getUserMedia({
                audio: true,
                video: {
                    mandatory: {
                        minWidth: 160,
                        maxWidth: 320,
                        minHeight: 120,
                        maxHeight: 240,
                        minFrameRate: 5,
                        maxFrameRate: 10
                    }
                }
            }, function (stream) {
                mediaStream = stream;
                previewElement.src = window.URL.createObjectURL(mediaStream);
                previewElement.removeAttribute("controls");
                previewElement.setAttribute("muted", "muted");
                window.setTimeout(function() { previewElement.play(); }, 200);

                recordAudio = RecordRTC(mediaStream, {
                    onAudioProcessStarted: function () {
                        recordVideo.startRecording();
                    }
                });

                recordVideo = RecordRTC(mediaStream, {
                    type: 'video'
                });

                if(startRecordButtonExists && cameraStartOnLoad) {
                    recordButton.disabled = false;
                }

                if(shouldAutoRecord) {
                    startRecord();
                }
                cameraStarted = true;
            }, function (error) {
                alert("Problem occured, make sure camera is not\nused elsewhere and that you are connected\nby https.");
            });
        }

        /* Closes the webcam stream and post to server if auto recording is on. */
        function stopRecording() {
            if(!shouldAutoRecord){
                recordButton.disabled = false;
            }

            stopButton.disabled = true;

            previewElement.src = '';

            var postbutton = null;
            if (typeof props.postButtonID !== "undefined") {
                postbutton = document.getElementById(props.postButtonID);
            }

            recordVideo.stopRecording(function (url) {
                if(replay) {
                    previewElement.src = url;
                    previewElement.setAttribute("controls","controls");
                    previewElement.removeAttribute("muted");
                }

                if(postbutton == null) {
                    if(props.siteView !== null) {
                        PostBlob(recordVideo.getBlob(), props.siteView);
                    } else {
                        PostBlob(recordVideo.getBlob());
                    }
                }
                else {
                    previewElement.src = url;
                    previewElement.setAttribute("controls","controls");
                    previewElement.removeAttribute("muted");
                    postbutton.disabled = false;
                    postbutton.onclick = function () {
                        if(props.siteView !== null) {
                            PostBlob(recordVideo.getBlob(), props.siteView);
                        } else {
                            PostBlob(recordVideo.getBlob());
                        }
                    }
                }
                mediaStream.stop();
                mediaStream = null;
                if(typeof props.calc !== "undefined") {
                    document.getElementById("test-rec-text").innerHTML = "⭕";
                }
                else {
                    document.getElementById("rec-text").innerHTML = "⭕";
                }
                cameraStarted = false;
            });
            var hasModal = document.getElementById("assignment-modal");
            if (hasModal !== null) {
                hasModal.style.display = 'none';
            }
        }

        /* Post to the server */
        function PostBlob(blob, siteView) {
            // FormData - data to be sent to the server
            var formData = props.formDataBuilder(blob,props.fileName);

            //used for hw testing
            if(typeof props.calc !== "undefined") {
              blobsize = blob.size / 1048576;
              sendTime = Date.now();
            }

            //call xhr with full url, data and callback function
            xhr(props.postURL, formData, props.playCallback);
        }

        /* Function for sending XMLHttpRequests. */
        function xhr(url, data, callback) {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200) {
                    callback(request.responseText);
                } else if(request.readyState == 4 && request.status !== 200) {
                    alert(request.responseText);
                }
            };

            if(typeof props.calc !== "undefined") {
                request.upload.onloadstart = function () {
                    $("#internet-speed").text("Uploading...");
                }
                request.onloadstart = function () {
                    $("#internet-speed").text("Uploading...");
                }
            }
            request.onload = function(){
                if(typeof props.calc !== "undefined") {
                    if(request.status == 404)
                        $("#internet-speed").text("Upload failed, no server connection.");
                    else if(request.status == 408)
                        $("#internet-speed").text("Connection timed out.");
                    else
                        props.calc(blobsize,sendTime);
                }
                else if(request.status == 404) {
                    alert("Upload failed, no server connection.");
                }
                else if(request.status == 408) {
                    alert("Connection timed out.");
                }
            }

            request.open('POST', url,true);
            request.send(data);
        }

        /* Showing recording-light on load (not recording) */

        if(typeof props.calc !== "undefined") {
            document.getElementById("test-rec-text").innerHTML = "⭕";
        }
        else {
            document.getElementById("rec-text").innerHTML = "⭕";
        }
    },
    render: function() {
        var id;
        var pId;
        var contId;
        console.log(this.props.contID);
        console.log(this.props);
        console.log(typeof this.props.contID);
        if(typeof this.props.contID === "undefined"){
            contId = "prev-container";
        }
        else {
            contId = this.prop.contID;
        }
        if(typeof this.props.calc !== "undefined") {
            id="prev-test";
            pId="test-rec-text";

        }
        else {
            id="preview";
            pId="rec-text";

        }

        return (

                    <video id={id} muted ></video>

        );
    }
});

window.Recorder = Recorder;<commit_msg>misspell error<commit_after>/**
 * Props params:
 *
 * playCallback:    Function to be called with response from server. should take one parameter.
 * calc:            Only used when testing hardware.
 * postURL:         The url after the globally set url.
 * formDataBuilder  Function to create formdata containing information to send. Function takes:.
 *                                                                                video(blob) as first param
 *                                                                                filename as second param.
 * recButtonID:     [Optional] Button to start recording video. If left out it autorecords on render.
 * stopButtonID:    Id of the button to stop recording video. Might post video as well(read about postButtonID).
 * postButtonID:    [Optional] Id of the post video button. If left out the stop button posts the video to server.
 * replay:          replay="true" if you want the recording to be playable in the same video tag.
 * fileName:        The name the video recording should have.
 * camOnLoad:       camOnLoad="true" If the camera is to start before recording. User will have to click
 *                  stopbutton to be able to reuse camera.
 * autoRecord:      autoRecord="true" if the camera should start recording when class is instantiated.
 *
 *
 * watch HardwareTest.js for example of use.
 */

var Recorder = React.createClass({
    componentDidMount: function() {
        var props = this.props;

        //used for hw testing
        var blobsize;
        var sendTime;

        var cameraStartOnLoad = (typeof props.camOnLoad === "undefined") ?
                        false : props.camOnLoad == "true";
        var cameraStarted = false;
        var startRecordButtonExists = (typeof props.recButtonID !== "undefined");
        var shouldAutoRecord = (typeof props.autoRecord === "undefined") ?
                        !startRecordButtonExists : props.autoRecord == "true";

        var replay = props.replay == "true";
        var stopButton = document.getElementById(props.stopButtonID);
        var previewElement;
        var recordAudio, recordVideo;
        var mediaStream;

        if(startRecordButtonExists) {
            var recordButton = document.getElementById(props.recButtonID);
            if(cameraStarted) {
                recordButton.disabled = true;
            }
        }

        if(typeof props.calc !== "undefined")
            previewElement = document.getElementById('prev-test');
        else
            previewElement = document.getElementById('preview');

        navigator.getUserMedia = ( navigator.getUserMedia ||
                                  navigator.webkitGetUserMedia ||
        navigator.mediaDevices.getUserMedia ||
                                  navigator.msGetUserMedia);

        if(cameraStartOnLoad) {
            startCamera();
        }

        /* The onclick function for the start record button if it exists. */
        if(startRecordButtonExists) {
            recordButton.onclick = startRecord;
        }

        /* The onclick function for the stop record button. */
        stopButton.onclick = stopRecording;

        /* Will start recording and start the webcam if not enabled. */
        function startRecord() {
            if(!cameraStarted) {
                startCamera();
                window.setTimeout(function() {
                    recordAudio.startRecording();
                    recordingStarted();
                }, 1000);
            } else {
                recordAudio.startRecording();
                recordingStarted();
            }
        }

        function recordingStarted() {
            if(startRecordButtonExists) {
                recordButton.disabled = true;
            }
            stopButton.disabled = false;

            if(typeof props.calc !== "undefined") {
                document.getElementById("test-rec-text").innerHTML = "🔴";
            }
            else {
                document.getElementById("rec-text").innerHTML = "🔴";
            }
        }

        /* Start stream from webcam and start recording if autoRecording is true,
         * will record with forced low settings for smaller files. */
        function startCamera () {
            navigator.getUserMedia({
                audio: true,
                video: {
                    mandatory: {
                        minWidth: 160,
                        maxWidth: 320,
                        minHeight: 120,
                        maxHeight: 240,
                        minFrameRate: 5,
                        maxFrameRate: 10
                    }
                }
            }, function (stream) {
                mediaStream = stream;
                previewElement.src = window.URL.createObjectURL(mediaStream);
                previewElement.removeAttribute("controls");
                previewElement.setAttribute("muted", "muted");
                window.setTimeout(function() { previewElement.play(); }, 200);

                recordAudio = RecordRTC(mediaStream, {
                    onAudioProcessStarted: function () {
                        recordVideo.startRecording();
                    }
                });

                recordVideo = RecordRTC(mediaStream, {
                    type: 'video'
                });

                if(startRecordButtonExists && cameraStartOnLoad) {
                    recordButton.disabled = false;
                }

                if(shouldAutoRecord) {
                    startRecord();
                }
                cameraStarted = true;
            }, function (error) {
                alert("Problem occured, make sure camera is not\nused elsewhere and that you are connected\nby https.");
            });
        }

        /* Closes the webcam stream and post to server if auto recording is on. */
        function stopRecording() {
            if(!shouldAutoRecord){
                recordButton.disabled = false;
            }

            stopButton.disabled = true;

            previewElement.src = '';

            var postbutton = null;
            if (typeof props.postButtonID !== "undefined") {
                postbutton = document.getElementById(props.postButtonID);
            }

            recordVideo.stopRecording(function (url) {
                if(replay) {
                    previewElement.src = url;
                    previewElement.setAttribute("controls","controls");
                    previewElement.removeAttribute("muted");
                }

                if(postbutton == null) {
                    if(props.siteView !== null) {
                        PostBlob(recordVideo.getBlob(), props.siteView);
                    } else {
                        PostBlob(recordVideo.getBlob());
                    }
                }
                else {
                    previewElement.src = url;
                    previewElement.setAttribute("controls","controls");
                    previewElement.removeAttribute("muted");
                    postbutton.disabled = false;
                    postbutton.onclick = function () {
                        if(props.siteView !== null) {
                            PostBlob(recordVideo.getBlob(), props.siteView);
                        } else {
                            PostBlob(recordVideo.getBlob());
                        }
                    }
                }
                mediaStream.stop();
                mediaStream = null;
                if(typeof props.calc !== "undefined") {
                    document.getElementById("test-rec-text").innerHTML = "⭕";
                }
                else {
                    document.getElementById("rec-text").innerHTML = "⭕";
                }
                cameraStarted = false;
            });
            var hasModal = document.getElementById("assignment-modal");
            if (hasModal !== null) {
                hasModal.style.display = 'none';
            }
        }

        /* Post to the server */
        function PostBlob(blob, siteView) {
            // FormData - data to be sent to the server
            var formData = props.formDataBuilder(blob,props.fileName);

            //used for hw testing
            if(typeof props.calc !== "undefined") {
              blobsize = blob.size / 1048576;
              sendTime = Date.now();
            }

            //call xhr with full url, data and callback function
            xhr(props.postURL, formData, props.playCallback);
        }

        /* Function for sending XMLHttpRequests. */
        function xhr(url, data, callback) {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200) {
                    callback(request.responseText);
                } else if(request.readyState == 4 && request.status !== 200) {
                    alert(request.responseText);
                }
            };

            if(typeof props.calc !== "undefined") {
                request.upload.onloadstart = function () {
                    $("#internet-speed").text("Uploading...");
                }
                request.onloadstart = function () {
                    $("#internet-speed").text("Uploading...");
                }
            }
            request.onload = function(){
                if(typeof props.calc !== "undefined") {
                    if(request.status == 404)
                        $("#internet-speed").text("Upload failed, no server connection.");
                    else if(request.status == 408)
                        $("#internet-speed").text("Connection timed out.");
                    else
                        props.calc(blobsize,sendTime);
                }
                else if(request.status == 404) {
                    alert("Upload failed, no server connection.");
                }
                else if(request.status == 408) {
                    alert("Connection timed out.");
                }
            }

            request.open('POST', url,true);
            request.send(data);
        }

        /* Showing recording-light on load (not recording) */

        if(typeof props.calc !== "undefined") {
            document.getElementById("test-rec-text").innerHTML = "⭕";
        }
        else {
            document.getElementById("rec-text").innerHTML = "⭕";
        }
    },
    render: function() {
        var id;
        var pId;
        var contId;

        if(typeof this.props.contID === "undefined"){
            contId = "prev-container";
        }
        else {
            contId = this.props.contID;
        }
        if(typeof this.props.calc !== "undefined") {
            id="prev-test";
            pId="test-rec-text";

        }
        else {
            id="preview";
            pId="rec-text";

        }

        return (

                    <video id={id} muted ></video>

        );
    }
});

window.Recorder = Recorder;<|endoftext|>


<commit_before>/**
 * @file lyrics command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const request = require('request');

exports.run = (Bastion, message, args) => {
  if (!args.song) {
    /**
     * The command was ran with invalid parameters.
     * @fires commandUsage
     */
    return Bastion.emit('commandUsage', message, this.help);
  }

  request({
    headers: {
      'Accept': 'Accept: application/json'
    },
    uri: `https://api.musixmatch.com/ws/1.1/matcher.lyrics.get?format=json&q_track=${encodeURIComponent(args.song)}&apikey=${Bastion.credentials.musixmatchAPIKey}`
  }, (err, response, body) => {
    if (err) {
      /**
       * Error condition is encountered.
       * @fires error
       */
      return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'connection'), Bastion.strings.error(message.guild.language, 'connection', true), message.channel);
    }
    if (response.statusCode === 200) {
      try {
        body = JSON.parse(body);
        if (body.message.header.status_code === 200) {
          message.channel.send({
            embed: {
              color: Bastion.colors.BLUE,
              title: `${args.song.join(' ').toTitleCase()} - Lyrics`,
              description: body.message.body.lyrics.lyrics_body.replace('******* This Lyrics is NOT for Commercial use *******', `View full lyrics at [musixmatch.com](${body.message.body.lyrics.backlink_url} 'Musixmatch - The world's largest lyrics catlog)`),
              footer: {
                text: `Powered by Musixmatch | Language: ${body.message.body.lyrics.lyrics_language_description.toTitleCase()}`
              }
            }
          }).catch(e => {
            Bastion.log.error(e);
          });
        }
        else if (body.message.header.status_code === 404) {
          /**
          * Error condition is encountered.
          * @fires error
          */
          return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'notFound'), Bastion.strings.error(message.guild.language, 'notFound', true, 'song lyrics'), message.channel);
        }
        // TODO: Show error messages for every status codes
      }
      catch (e) {
        /**
         * Error condition is encountered.
         * @fires error
         */
        return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'parseError'), Bastion.strings.error(message.guild.language, 'parse', true), message.channel);
      }
    }
    else {
      /**
       * Error condition is encountered.
       * @fires error
       */
      return Bastion.emit('error', response.statusCode, response.statusMessage, message.channel);
    }
  });
};

exports.config = {
  aliases: [],
  enabled: true,
  argsDefinitions: [
    { name: 'song', type: String, multiple: true, defaultOption: true }
  ]
};

exports.help = {
  name: 'lyrics',
  botPermission: '',
  userPermission: '',
  usage: 'lyrics <SONG_NAME> [Artist Name>]',
  example: [ 'lyrics Something just like this', 'lyrics Shape of you - Ed Sheeran' ]
};
<commit_msg>Fixed a typo in lyrics comamnd<commit_after>/**
 * @file lyrics command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const request = require('request');

exports.run = (Bastion, message, args) => {
  if (!args.song) {
    /**
     * The command was ran with invalid parameters.
     * @fires commandUsage
     */
    return Bastion.emit('commandUsage', message, this.help);
  }

  request({
    headers: {
      'Accept': 'Accept: application/json'
    },
    uri: `https://api.musixmatch.com/ws/1.1/matcher.lyrics.get?format=json&q_track=${encodeURIComponent(args.song)}&apikey=${Bastion.credentials.musixmatchAPIKey}`
  }, (err, response, body) => {
    if (err) {
      /**
       * Error condition is encountered.
       * @fires error
       */
      return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'connection'), Bastion.strings.error(message.guild.language, 'connection', true), message.channel);
    }
    if (response.statusCode === 200) {
      try {
        body = JSON.parse(body);
        if (body.message.header.status_code === 200) {
          message.channel.send({
            embed: {
              color: Bastion.colors.BLUE,
              title: `${args.song.join(' ').toTitleCase()} - Lyrics`,
              description: body.message.body.lyrics.lyrics_body.replace('******* This Lyrics is NOT for Commercial use *******', `View full lyrics at [musixmatch.com](${body.message.body.lyrics.backlink_url} 'Musixmatch')`),
              footer: {
                text: `Powered by Musixmatch | Language: ${body.message.body.lyrics.lyrics_language_description.toTitleCase()}`
              }
            }
          }).catch(e => {
            Bastion.log.error(e);
          });
        }
        else if (body.message.header.status_code === 404) {
          /**
          * Error condition is encountered.
          * @fires error
          */
          return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'notFound'), Bastion.strings.error(message.guild.language, 'notFound', true, 'song lyrics'), message.channel);
        }
        // TODO: Show error messages for every status codes
      }
      catch (e) {
        /**
         * Error condition is encountered.
         * @fires error
         */
        return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'parseError'), Bastion.strings.error(message.guild.language, 'parse', true), message.channel);
      }
    }
    else {
      /**
       * Error condition is encountered.
       * @fires error
       */
      return Bastion.emit('error', response.statusCode, response.statusMessage, message.channel);
    }
  });
};

exports.config = {
  aliases: [],
  enabled: true,
  argsDefinitions: [
    { name: 'song', type: String, multiple: true, defaultOption: true }
  ]
};

exports.help = {
  name: 'lyrics',
  botPermission: '',
  userPermission: '',
  usage: 'lyrics <SONG_NAME> [Artist Name>]',
  example: [ 'lyrics Something just like this', 'lyrics Shape of you - Ed Sheeran' ]
};
<|endoftext|>


<commit_before>/* eslint no-console: 0 */

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const emailConfig = require('./emailConfig.json')

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 8989 : process.env.PORT;
const app = express();

if (isDeveloping) {
  const webpack = require('webpack');
  const config = require('./webpack.config.js');
  const webpackMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
  const compiler = webpack(config);
  const middleware = webpackMiddleware(compiler, {
    publicPath: config.output.publicPath,
    contentBase: 'src',
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false
    }
  });

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('*', function response(req, res) {
    res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'dist/index.html')));
    res.end();
  });
} else {
  app.use(express.static(__dirname + '/dist'));
  app.get('*', function response(req, res) {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
  });
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/sendMail', function(req, res){
  var subject = req.body.subject;
  var email = req.body.email;
  var message = req.body.message;

  var mailer = nodemailer.createTransport('smtps://'+ emailConfig.name +':'+ emailConfig.password +'@smtp.gmail.com');
  var mailOptions = {
    from: '"Jake.Tegtmeier.io" <'+ emailConfig.from +'>', // sender address
    to: ""+emailConfig.to, // list of receivers
    subject: subject, // Subject line
    text: "From:" + email + "----------->>
" + message, // plaintext body
  };

  mailer.sendMail(mailOptions, function(error, info){
    if(error){
      return console.log(error);
    }
    console.log('Message sent: ' + info.response)
  })
  res.end("yes");
})

app.listen(port, '0.0.0.0', function onStart(err) {
  if (err) {
    console.log(err);
  }
  console.info('==> 🌎 Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port);
});
<commit_msg>changed env vars for heroku<commit_after>/* eslint no-console: 0 */

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const emailConfig = require('./emailConfig.json')

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 8989 : process.env.PORT;
const app = express();

if (isDeveloping) {
  const webpack = require('webpack');
  const config = require('./webpack.config.js');
  const webpackMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
  const compiler = webpack(config);
  const middleware = webpackMiddleware(compiler, {
    publicPath: config.output.publicPath,
    contentBase: 'src',
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false
    }
  });

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('*', function response(req, res) {
    res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'dist/index.html')));
    res.end();
  });
} else {
  app.use(express.static(__dirname + '/dist'));
  app.get('*', function response(req, res) {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
  });
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/sendMail', function(req, res){
  var subject = req.body.subject;
  var email = req.body.email;
  var message = req.body.message;

  var mailer = nodemailer.createTransport('smtps://'+ ENV['EMAIL_NAME'] +':'+ ENV['EMAIL_PASS'] +'@smtp.gmail.com');
  var mailOptions = {
    from: '"Jake.Tegtmeier.io" <'+ ENV['EMAIL_FROM'] +'>', // sender address
    to: ""+ENV['EMAIL_TO'], // list of receivers
    subject: subject, // Subject line
    text: "From:" + email + "----------->>
" + message, // plaintext body
  };

  mailer.sendMail(mailOptions, function(error, info){
    if(error){
      return console.log(error);
    }
    console.log('Message sent: ' + info.response)
  })
  res.end("yes");
})

app.listen(port, '0.0.0.0', function onStart(err) {
  if (err) {
    console.log(err);
  }
  console.info('==> 🌎 Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port);
});
<|endoftext|>


<commit_before>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function generer() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);
groupe = 1;
    var logo = new Image();

    var numPErs =  (parseInt(localStorage.numGroupe));

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){
              var cont = 1;
              var logo = new Image();
         //     for (groupe = 1; groupe < 5; groupe++) {

                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo2 = new Image();
                 logo2.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_"+groupe+".PNG";
                 logo2.onload = function(){
                    pdf.addImage(logo2, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo3 = new Image();
                 logo3.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_"+groupe+".PNG";
                 logo3.onload = function(){
                    pdf.addImage(logo3, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo4 = new Image();
                 logo4.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_"+groupe+".PNG";
                 logo4.onload = function(){
                    pdf.addImage(logo4, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
           //   }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo5 = new Image();
                 logo5.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 logo5.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                logo.onload = function(){
                  pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }
alert("pdfPRET");
  pdf.output("dataurlnewwindow");
}
function visualiser() {

}
<commit_msg>Update dynamic_carousel.js<commit_after>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function generer() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);
groupe = 1;
    var logo = new Image();

    var numPErs =  (parseInt(localStorage.numGroupe));

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){
              var cont = 1;
              var logo = new Image();
         //     for (groupe = 1; groupe < 5; groupe++) {

                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo2 = new Image();
                 logo2.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_2.PNG";
                 logo2.onload = function(){
                    pdf.addImage(logo2, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo3 = new Image();
                 logo3.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_3.PNG";
                 logo3.onload = function(){
                    pdf.addImage(logo3, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo4 = new Image();
                 logo4.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_4.PNG";
                 logo4.onload = function(){
                    pdf.addImage(logo4, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
           //   }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo5 = new Image();
                 logo5.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 logo5.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                logo.onload = function(){
                  pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }
alert("pdfPRET");
  pdf.output("dataurlnewwindow");
}
function visualiser() {

}
<|endoftext|>