<commit_before>'use strict';

//https://github.com/angular/protractor/blob/master/docs/api.md
//GetAttribute() returns "boolean" values and will return either "true" or null

describe('Registration process and similar', function(){

    var HomePage = require('../../app/home/home-page');
    var AuthPage = require('../../app/home/auth/auth-page');
    var credentials = require('./config/credentials').credentials;
    var home = new HomePage();
    var auth = new AuthPage();
    var start = home.start;
    var login = auth.login;
    var profile = home.account.profile;
    var registrationForm = start.registration;

    it('should be able to see the registration form', function() {
        start.visitPage();

        // we are logged in
        expect(registrationForm.isDisplayed()).toBe(false);
        auth.doLogout();
        start.visitPage();

        // we are logged out now
        expect(registrationForm.isDisplayed()).toBe(true);
    });

    it('should fail to register', function() {
        registrationForm.register('', '', '', '', '', '');
        expect(registrationForm.form.errors.firstnameRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.lastnameRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.emailRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.passwordRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.confirmationRequired.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test@28msec.com', '', '');
        expect(registrationForm.form.errors.passwordRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.confirmationRequired.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test@28msec.com', '12345', '1234');
        expect(registrationForm.form.errors.passwordsDontMatch.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test@28msec.com', '123', '123');
        expect(registrationForm.form.errors.passwordTooShort.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test28msec.com', 'abc123', 'abc123');
        expect(registrationForm.form.errors.emailInvalid.isDisplayed()).toBe(true);
    });

    it('should be able to register', function() {
        registrationForm.register('Test', 'User', 'admin+test@28msec.com', credentials.testPassword, credentials.testPassword);
        expect(registrationForm.form.errors.emailInUse.isPresent()).toBe(false);
        // should have automatically logged us in
        expect(profile.form.isDisplayed()).toBe(true);

        start.visitPage();
        expect(registrationForm.isDisplayed()).toBe(false);
    });

    it('should not be able to register again', function() {
        auth.doLogout();
        start.visitPage();
        expect(registrationForm.isDisplayed()).toBe(true);
        registrationForm.register('Test', 'User', 'admin+test@28msec.com', credentials.testPassword, credentials.testPassword);
        expect(registrationForm.form.errors.emailInUse.isDisplayed()).toBe(true);
    });

    // reset
    it('should be able to log in as support user', function() {
        login.visitPage();
        login.login('support@28.io', credentials.testPassword);
        login.getCurrentUrl().then(function(url) {
            expect(url.substring(url.length - '/account'.length)).toBe('/account');
        });
    });

});

<commit_msg>added test for password reset<commit_after>'use strict';

//https://github.com/angular/protractor/blob/master/docs/api.md
//GetAttribute() returns "boolean" values and will return either "true" or null

describe('Registration process and similar', function(){

    var HomePage = require('../../app/home/home-page');
    var AuthPage = require('../../app/home/auth/auth-page');
    var credentials = require('./config/credentials').credentials;
    var home = new HomePage();
    var auth = new AuthPage();
    var start = home.start;
    var login = auth.login;
    var reset = auth.reset;
    var profile = home.account.profile;
    var registrationForm = start.registration;

    it('should be able to see the registration form', function() {
        start.visitPage();

        // we are logged in
        expect(registrationForm.isDisplayed()).toBe(false);
        auth.doLogout();
        start.visitPage();

        // we are logged out now
        expect(registrationForm.isDisplayed()).toBe(true);
    });

    it('should fail to register', function() {
        registrationForm.register('', '', '', '', '', '');
        expect(registrationForm.form.errors.firstnameRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.lastnameRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.emailRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.passwordRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.confirmationRequired.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test@28msec.com', '', '');
        expect(registrationForm.form.errors.passwordRequired.isDisplayed()).toBe(true);
        expect(registrationForm.form.errors.confirmationRequired.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test@28msec.com', '12345', '1234');
        expect(registrationForm.form.errors.passwordsDontMatch.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test@28msec.com', '123', '123');
        expect(registrationForm.form.errors.passwordTooShort.isDisplayed()).toBe(true);

        registrationForm.register('Test', 'User', 'admin+test28msec.com', 'abc123', 'abc123');
        expect(registrationForm.form.errors.emailInvalid.isDisplayed()).toBe(true);
    });

    it('should be able to register', function() {
        registrationForm.register('Test', 'User', 'admin+test@28msec.com', credentials.testPassword, credentials.testPassword);
        expect(registrationForm.form.errors.emailInUse.isPresent()).toBe(false);
        // should have automatically logged us in
        expect(profile.form.isDisplayed()).toBe(true);

        start.visitPage();
        expect(registrationForm.isDisplayed()).toBe(false);
    });

    it('should not be able to register again', function() {
        auth.doLogout();
        start.visitPage();
        expect(registrationForm.isDisplayed()).toBe(true);
        registrationForm.register('Test', 'User', 'admin+test@28msec.com', credentials.testPassword, credentials.testPassword);
        expect(registrationForm.form.errors.emailInUse.isDisplayed()).toBe(true);
    });

    it('should be able to request password reset', function() {
        login.visitPage();
        login.showPasswordReset();
        expect(login.formForgotPassword.isDisplayed()).toBe(true);

        login.requestResetPassword('');
        expect(this.form.errors.forgotEmailRequired.isDisplayed()).toBe(true);

        login.requestResetPassword('admin+test28msec.com');
        expect(this.form.errors.forgotEmailInvalid.isDisplayed()).toBe(true);

        login.requestResetPassword('admin+test@28msec.com');
        expect(home.alert.header.getText()).toBe('Help on the way!');

        reset.visitPage('admin+test@28msec.com','84736f6d-4c70-4a69-8ef8-2444f4ee4646');
        expect(reset.changeForm.isDisplayed()).toBe(true);

        reset.resetPassword('', '');
        expect(reset.form.errors.passwordRequired.isDisplayed()).toBe(true);
        expect(reset.form.errors.passwordRepeatRequired.isDisplayed()).toBe(true);

        reset.resetPassword('123', '123');
        expect(reset.form.errors.passwordMinLength.isDisplayed()).toBe(true);

        reset.resetPassword('12345', '123');
        expect(reset.form.errors.passwordRepeatDoesntMatch.isDisplayed()).toBe(true);

        reset.resetPassword('12345', '12345');
        expect(home.error.header.getText()).toBe('Error'); // token is not valid
    });

    // reset
    it('should be able to log in as support user', function() {
        login.visitPage();
        login.login('support@28.io', credentials.testPassword);
        login.getCurrentUrl().then(function(url) {
            expect(url.substring(url.length - '/account'.length)).toBe('/account');
        });
    });

});

<|endoftext|>


<commit_before>CodeMirror.defineMode("clike", function(config, parserConfig) {
  var indentUnit = config.indentUnit, keywords = parserConfig.keywords,
      cpp = parserConfig.useCPP, multiLineStrings = parserConfig.multiLineStrings,
      $vars = parserConfig.$vars, atAnnotations = parserConfig.atAnnotations;
  var isOperatorChar = /[+\-*&%=<>!?|]/;

  function chain(stream, state, f) {
    state.tokenize = f;
    return f(stream, state);
  }

  var type;
  function ret(tp, style) {
    type = tp;
    return style;
  }

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == '"' || ch == "'")
      return chain(stream, state, tokenString(ch));
    else if (/[\[\]{}\(\),;\:\.]/.test(ch))
      return ret(ch);
    else if (ch == "#" && cpp && state.startOfLine) {
      stream.skipToEnd();
      return ret("directive", "meta");
    }
    else if (/\d/.test(ch)) {
      stream.eatWhile(/[\w\.]/)
      return ret("number", "number");
    }
    else if (ch == "/") {
      if (stream.eat("*")) {
        return chain(stream, state, tokenComment);
      }
      else if (stream.eat("/")) {
        stream.skipToEnd();
        return ret("comment", "comment");
      }
      else {
        stream.eatWhile(isOperatorChar);
        return ret("operator");
      }
    }
    else if (isOperatorChar.test(ch)) {
      stream.eatWhile(isOperatorChar);
      return ret("operator");
    }
    else if (atAnnotations && ch == "@") {
        stream.eatWhile(/[\w\$_]/);
        return ret("annotation", "meta");
    }
    else if ($vars && ch == "$") {
      stream.eatWhile(/[\w\$_]/);
      return ret("word", "variable");
    }
    else {
      stream.eatWhile(/[\w\$_]/);
      if (keywords && keywords.propertyIsEnumerable(stream.current())) return ret("keyword", "keyword");
      return ret("word");
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && next == "\\";
      }
      if (end || !(escaped || multiLineStrings))
        state.tokenize = tokenBase;
      return ret("string", "string");
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ret("comment", "comment");
  }

  function Context(indented, column, type, align, prev) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.align = align;
    this.prev = prev;
  }

  function pushContext(state, col, type) {
    return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
    return state.context = state.context.prev;
  }

  // Interface

  return {
    startState: function(basecolumn) {
      return {
        tokenize: tokenBase,
        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
        indented: 0,
        startOfLine: true
      };
    },

    token: function(stream, state) {
      var ctx = state.context;
      if (stream.sol()) {
        if (ctx.align == null) ctx.align = false;
        state.indented = stream.indentation();
        state.startOfLine = true;
      }
      if (stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);
      if (type == "comment") return style;
      if (ctx.align == null) ctx.align = true;

      if ((type == ";" || type == ":") && ctx.type == "statement") popContext(state);
      else if (type == "{") pushContext(state, stream.column(), "}");
      else if (type == "[") pushContext(state, stream.column(), "]");
      else if (type == "(") pushContext(state, stream.column(), ")");
      else if (type == "}") {
        if (ctx.type == "statement") ctx = popContext(state);
        if (ctx.type == "}") ctx = popContext(state);
        if (ctx.type == "statement") ctx = popContext(state);
      }
      else if (type == ctx.type) popContext(state);
      else if (ctx.type == "}" || ctx.type == "top") pushContext(state, stream.column(), "statement");
      state.startOfLine = false;
      return style;
    },

    indent: function(state, textAfter) {
      if (state.tokenize != tokenBase) return 0;
      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type;
      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
      else return ctx.indented + (closing ? 0 : indentUnit);
    },

    electricChars: "{}"
  };
});

(function() {
  function keywords(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }
  var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
    "double static else struct entry switch extern typedef float union for unsigned " +
    "goto while enum void const signed volatile";

  CodeMirror.defineMIME("text/x-csrc", {
    name: "clike",
    useCPP: true,
    keywords: keywords(cKeywords)
  });
  CodeMirror.defineMIME("text/x-c++src", {
    name: "clike",
    useCPP: true,
    keywords: keywords(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
                       "static_cast typeid catch false operator template typename class friend private " +
                       "this using const_cast inline public throw virtual delete mutable protected true " +
                       "wchar_t")
  });
  CodeMirror.defineMIME("text/x-java", {
    name: "clike",
    atAnnotations: true,
    keywords: keywords("abstract assert boolean break byte case catch char class const continue default " +
                       "do double else enum extends false final finally float for goto if implements import " +
                       "instanceof int interface long native new null package private protected public " +
                       "return short static strictfp super switch synchronized this throw throws transient " +
                       "true try void volatile while")
  });
}());
<commit_msg>Add support for C#-style verbatim strings to c-like mode<commit_after>CodeMirror.defineMode("clike", function(config, parserConfig) {
  var indentUnit = config.indentUnit, keywords = parserConfig.keywords,
      cpp = parserConfig.useCPP, multiLineStrings = parserConfig.multiLineStrings,
      $vars = parserConfig.$vars, atAnnotations = parserConfig.atAnnotations,
      atStrings = parserConfig.atStrings;
  var isOperatorChar = /[+\-*&%=<>!?|]/;

  function chain(stream, state, f) {
    state.tokenize = f;
    return f(stream, state);
  }

  var type;
  function ret(tp, style) {
    type = tp;
    return style;
  }

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == '"' || ch == "'")
      return chain(stream, state, tokenString(ch));
    else if (/[\[\]{}\(\),;\:\.]/.test(ch))
      return ret(ch);
    else if (ch == "#" && cpp && state.startOfLine) {
      stream.skipToEnd();
      return ret("directive", "meta");
    }
    else if (/\d/.test(ch)) {
      stream.eatWhile(/[\w\.]/)
      return ret("number", "number");
    }
    else if (ch == "/") {
      if (stream.eat("*")) {
        return chain(stream, state, tokenComment);
      }
      else if (stream.eat("/")) {
        stream.skipToEnd();
        return ret("comment", "comment");
      }
      else {
        stream.eatWhile(isOperatorChar);
        return ret("operator");
      }
    }
    else if (isOperatorChar.test(ch)) {
      stream.eatWhile(isOperatorChar);
      return ret("operator");
    }
    else if (atAnnotations && ch == "@") {
        stream.eatWhile(/[\w\$_]/);
        return ret("annotation", "meta");
    }
    else if (atStrings && ch == "@" && stream.eat('"')) {
      return chain(stream, state, tokenAtString);
    }
    else if ($vars && ch == "$") {
      stream.eatWhile(/[\w\$_]/);
      return ret("word", "variable");
    }
    else {
      stream.eatWhile(/[\w\$_]/);
      if (keywords && keywords.propertyIsEnumerable(stream.current())) return ret("keyword", "keyword");
      return ret("word");
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && next == "\\";
      }
      if (end || !(escaped || multiLineStrings))
        state.tokenize = tokenBase;
      return ret("string", "string");
    };
  }

  // C#-style strings where "" escapes a quote.
  function tokenAtString(stream, state) {
    var next;
    while ((next = stream.next()) != null) {
      if (next == '"' && !stream.eat('"')) {
        state.tokenize = tokenBase;
        break;
      }
    }
    return ret("string", "string");
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ret("comment", "comment");
  }

  function Context(indented, column, type, align, prev) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.align = align;
    this.prev = prev;
  }

  function pushContext(state, col, type) {
    return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
    return state.context = state.context.prev;
  }

  // Interface

  return {
    startState: function(basecolumn) {
      return {
        tokenize: tokenBase,
        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
        indented: 0,
        startOfLine: true
      };
    },

    token: function(stream, state) {
      var ctx = state.context;
      if (stream.sol()) {
        if (ctx.align == null) ctx.align = false;
        state.indented = stream.indentation();
        state.startOfLine = true;
      }
      if (stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);
      if (type == "comment") return style;
      if (ctx.align == null) ctx.align = true;

      if ((type == ";" || type == ":") && ctx.type == "statement") popContext(state);
      else if (type == "{") pushContext(state, stream.column(), "}");
      else if (type == "[") pushContext(state, stream.column(), "]");
      else if (type == "(") pushContext(state, stream.column(), ")");
      else if (type == "}") {
        if (ctx.type == "statement") ctx = popContext(state);
        if (ctx.type == "}") ctx = popContext(state);
        if (ctx.type == "statement") ctx = popContext(state);
      }
      else if (type == ctx.type) popContext(state);
      else if (ctx.type == "}" || ctx.type == "top") pushContext(state, stream.column(), "statement");
      state.startOfLine = false;
      return style;
    },

    indent: function(state, textAfter) {
      if (state.tokenize != tokenBase) return 0;
      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type;
      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
      else return ctx.indented + (closing ? 0 : indentUnit);
    },

    electricChars: "{}"
  };
});

(function() {
  function keywords(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }
  var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
    "double static else struct entry switch extern typedef float union for unsigned " +
    "goto while enum void const signed volatile";

  CodeMirror.defineMIME("text/x-csrc", {
    name: "clike",
    useCPP: true,
    keywords: keywords(cKeywords)
  });
  CodeMirror.defineMIME("text/x-c++src", {
    name: "clike",
    useCPP: true,
    keywords: keywords(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
                       "static_cast typeid catch false operator template typename class friend private " +
                       "this using const_cast inline public throw virtual delete mutable protected true " +
                       "wchar_t")
  });
  CodeMirror.defineMIME("text/x-java", {
    name: "clike",
    atAnnotations: true,
    keywords: keywords("abstract assert boolean break byte case catch char class const continue default " +
                       "do double else enum extends false final finally float for goto if implements import " +
                       "instanceof int interface long native new null package private protected public " +
                       "return short static strictfp super switch synchronized this throw throws transient " +
                       "true try void volatile while")
  });
}());
<|endoftext|>


<commit_before>(function() {
  'use strict';

  function _merge(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
  }

  var Wheel = function(options) {
    var _this = this,
        defaults,
        s,
        ctx,
        canvas;

   defaults = {
      el: null,
      members: ['Member 1', 'Member 2', 'Member 3', 'Member 4'],
      colors: ['#C7181D', '#FCB937', '#A1B836', '#371979', '#C7181D', '#FCB937', '#A1B836', '#371979'],
      radius: 250,
      startAngle: 0
    };

    // s for settings
    s = _merge(defaults, options);

    s.width = s.height = s.radius * 2;
    s.insideRadius = (s.width / 5);
    s.outsideRadius = (s.width / 2) - 10;

    s.startAngle = (s.startAngle === 'random' ? Math.floor(Math.random() * 360) : s.startAngle);
    s.arc = Math.PI / (s.members.length / (s.members.length / (s.members.length / 2)));
    s.spinTimeout =  null;
    s.spinTime =  0;
    s.spinTimeTotal =  0;
    s.spinAngleStart =  null;
    s.textRadius = 160;

    this.draw = function() {
        var angle,
            text,
            i;

        canvas = document.getElementById(s.el);
        canvas.width = s.width;
        canvas.height = s.height;
        if (canvas.getContext) {

          ctx = canvas.getContext('2d');
          ctx.clearRect(0, 0, s.width, s.height);

          ctx.strokeStyle = 'black';
          ctx.lineWidth = 2;

          ctx.font = '16px sans-serif';

          for (i = 0; i < s.members.length; i++) {
            angle = s.startAngle + i * s.arc;

            ctx.fillStyle = s.colors[i];
            ctx.beginPath();
            ctx.arc(s.width / 2, s.height / 2, s.outsideRadius, angle, angle + s.arc, false);
            ctx.arc(s.width / 2, s.height / 2, s.insideRadius, angle + s.arc, angle, true);
            ctx.stroke();
            ctx.fill();
            ctx.save();

            ctx.shadowOffsetX = -1;
            ctx.shadowOffsetY = -1;
            ctx.shadowBlur = 0;
            ctx.fillStyle = "black";
            ctx.translate((s.width / 2) + Math.cos(angle + s.arc / 2) * s.textRadius, (s.height / 2) + Math.sin(angle + s.arc / 2) * s.textRadius);
            ctx.rotate(s.angle + s.arc / 2 + Math.PI / 2);
            text = s.members[i];
            ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
            ctx.restore();
          }

          //Arrow
          ctx.fillStyle = "black";
          ctx.beginPath();
          ctx.moveTo(250 - 4, 250 - (s.outsideRadius + 5));
          ctx.lineTo(250 + 4, 250 - (s.outsideRadius + 5));
          ctx.lineTo(250 + 4, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 + 9, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 + 0, 250 - (s.outsideRadius - 13));
          ctx.lineTo(250 - 9, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 - 4, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 - 4, 250 - (s.outsideRadius + 5));
          ctx.fill();
        }
      };

      this.easeOut = function(t, b, c, d) {
        var ts,
            tc;

        ts = (t/=d)*t;
        tc = ts*t;
        return b+c*(tc + -3*ts + 3*t);
      };

      this.rotate = function() {
        var spinAngle;
        s.spinTime += 30;
        console.log(s.spinTime);
        if((s.spinTime + 5000) >= s.spinTimeTotal) {
          _this.stop();
          return;
        }
        spinAngle = s.spinAngleStart - _this.easeOut(s.spinTime, 0, s.spinAngleStart, s.spinTimeTotal);
        s.startAngle += (spinAngle * Math.PI / 180);
        _this.draw();
        s.spinTimeout = setTimeout(_this.rotate, 30);
      };

      this.spin = function(cb) {
          _this.cb = cb;
          s.spinAngleStart = Math.random() * 10 + 10;
          s.spinTime = 0;
          s.spinTimeTotal = Math.random() * 3 + 4 * 3000;
          console.log('spinTimeTotal: %d', s.spinTimeTotal);
          _this.rotate();
      };

      this.stop = function() {
        var degrees;
        var arcd;
        var index;

        clearTimeout(s.spinTimeout);
        degrees = s.startAngle * 180 / Math.PI + 90;
        arcd = s.arc * 180 / Math.PI;
        index = Math.floor((360 - degrees % 360) / arcd);
        ctx.save();
        _this.done(s.members[index]);
      };

      this.done = function(member) {
        console.log(member);
        _this.cb(member);
      };

    return {
      init: _this.draw,
      spin: _this.spin
    };
  };

  window.Wheel = window.Wheel || Wheel;

})();
<commit_msg>remove console logs<commit_after>(function() {
  'use strict';

  function _merge(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
  }

  var Wheel = function(options) {
    var _this = this,
        defaults,
        s,
        ctx,
        canvas;

   defaults = {
      el: null,
      members: ['Member 1', 'Member 2', 'Member 3', 'Member 4'],
      colors: ['#C7181D', '#FCB937', '#A1B836', '#371979', '#C7181D', '#FCB937', '#A1B836', '#371979'],
      radius: 250,
      startAngle: 0
    };

    // s for settings
    s = _merge(defaults, options);

    s.width = s.height = s.radius * 2;
    s.insideRadius = (s.width / 5);
    s.outsideRadius = (s.width / 2) - 10;

    s.startAngle = (s.startAngle === 'random' ? Math.floor(Math.random() * 360) : s.startAngle);
    s.arc = Math.PI / (s.members.length / (s.members.length / (s.members.length / 2)));
    s.spinTimeout =  null;
    s.spinTime =  0;
    s.spinTimeTotal =  0;
    s.spinAngleStart =  null;
    s.textRadius = 160;

    this.draw = function() {
        var angle,
            text,
            i;

        canvas = document.getElementById(s.el);
        canvas.width = s.width;
        canvas.height = s.height;
        if (canvas.getContext) {

          ctx = canvas.getContext('2d');
          ctx.clearRect(0, 0, s.width, s.height);

          ctx.strokeStyle = 'black';
          ctx.lineWidth = 2;

          ctx.font = '16px sans-serif';

          for (i = 0; i < s.members.length; i++) {
            angle = s.startAngle + i * s.arc;

            ctx.fillStyle = s.colors[i];
            ctx.beginPath();
            ctx.arc(s.width / 2, s.height / 2, s.outsideRadius, angle, angle + s.arc, false);
            ctx.arc(s.width / 2, s.height / 2, s.insideRadius, angle + s.arc, angle, true);
            ctx.stroke();
            ctx.fill();
            ctx.save();

            ctx.shadowOffsetX = -1;
            ctx.shadowOffsetY = -1;
            ctx.shadowBlur = 0;
            ctx.fillStyle = "black";
            ctx.translate((s.width / 2) + Math.cos(angle + s.arc / 2) * s.textRadius, (s.height / 2) + Math.sin(angle + s.arc / 2) * s.textRadius);
            ctx.rotate(s.angle + s.arc / 2 + Math.PI / 2);
            text = s.members[i];
            ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
            ctx.restore();
          }

          //Arrow
          ctx.fillStyle = "black";
          ctx.beginPath();
          ctx.moveTo(250 - 4, 250 - (s.outsideRadius + 5));
          ctx.lineTo(250 + 4, 250 - (s.outsideRadius + 5));
          ctx.lineTo(250 + 4, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 + 9, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 + 0, 250 - (s.outsideRadius - 13));
          ctx.lineTo(250 - 9, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 - 4, 250 - (s.outsideRadius - 5));
          ctx.lineTo(250 - 4, 250 - (s.outsideRadius + 5));
          ctx.fill();
        }
      };

      this.easeOut = function(t, b, c, d) {
        var ts,
            tc;

        ts = (t/=d)*t;
        tc = ts*t;
        return b+c*(tc + -3*ts + 3*t);
      };

      this.rotate = function() {
        var spinAngle;
        s.spinTime += 30;
        if((s.spinTime + 5000) >= s.spinTimeTotal) {
          _this.stop();
          return;
        }
        spinAngle = s.spinAngleStart - _this.easeOut(s.spinTime, 0, s.spinAngleStart, s.spinTimeTotal);
        s.startAngle += (spinAngle * Math.PI / 180);
        _this.draw();
        s.spinTimeout = setTimeout(_this.rotate, 30);
      };

      this.spin = function(cb) {
          _this.cb = cb;
          s.spinAngleStart = Math.random() * 10 + 10;
          s.spinTime = 0;
          s.spinTimeTotal = Math.random() * 3 + 4 * 3000;
          _this.rotate();
      };

      this.stop = function() {
        var degrees;
        var arcd;
        var index;

        clearTimeout(s.spinTimeout);
        degrees = s.startAngle * 180 / Math.PI + 90;
        arcd = s.arc * 180 / Math.PI;
        index = Math.floor((360 - degrees % 360) / arcd);
        ctx.save();
        _this.done(s.members[index]);
      };

      this.done = function(member) {
        _this.cb(member);
      };

    return {
      init: _this.draw,
      spin: _this.spin
    };
  };

  window.Wheel = window.Wheel || Wheel;

})();
<|endoftext|>


<commit_before>var util = require('./util/util');
var validation = require('./util/validation');
var moment = require('moment-timezone');

module.exports = function(sequelize, DataTypes) {
  var name = 'Recording';

  var attributes = {
    // Raw file data.
    rawFileKey: DataTypes.STRING,
    rawFileSize: DataTypes.INTEGER,
    // Processing fields. Fields set by and for the processing.
    fileKey: DataTypes.STRING,
    fileSize: DataTypes.STRING,
    fileMimeType: DataTypes.STRING,
    processingStartTime: DataTypes.DATE,
    processingMeta: DataTypes.JSONB,
    processingState: DataTypes.STRING,
    passedFilter: DataTypes.BOOLEAN,
    // recording metadata.
    duration: DataTypes.INTEGER,
    recordingDateTime: DataTypes.DATE,
    location: {
      type: DataTypes.GEOMETRY,
      set: util.geometrySetter,
      validate: { isLatLon: validation.isLatLon },
    },
    version: DataTypes.STRING,
    // Battery relevant fields.
    batteryLevel: DataTypes.DOUBLE,
    batteryCharging: DataTypes.STRING,
    airplaneModeOn: DataTypes.BOOLEAN,
    // Other fields
    jobKey: DataTypes.STRING,
    type: DataTypes.STRING,
    public: { type: DataTypes.BOOLEAN, defaultValue: false},
    additionalMetadata: DataTypes.JSONB,
  };

  var models = sequelize.models;

  /**
    * Return one or more recordings for a user matching the query
    * arguments given.
    */
  var query = async function(user, where, taggedOnly, offset, limit, order) {
    // If query should be filtered by tagged or not or ignored.
    var sqlLiteral = '';
    var tagRequired = false;
    if (taggedOnly == true) {
      tagRequired = true;
    } else if (taggedOnly == false) {
      sqlLiteral = 'NOT EXISTS (SELECT * FROM   "Tags" WHERE  "Tags".id = "Recording".id)';
      tagRequired = false;
    }

    if (order == null) {
      order = [
        // Sort by recordingDatetime but handle the case of the
        // timestamp being missing and fallback to sorting by id.
        [sequelize.fn("COALESCE", sequelize.col('recordingDateTime'), '1970-01-01'), "DESC"],
        ["id", "DESC"],
      ];
    }

    var q = {
      where: {
        "$and": [
          where, // User query
          await recordingsFor(user),
          sequelize.literal(sqlLiteral),
        ],
      },
      order: order,
      include: [
        { model: models.Group },
        { model: models.Tag, required: tagRequired },
        { model: models.Device, where: {}, attributes: ["devicename", "id"] },
      ],
      limit: limit,
      offset: offset,
      attributes: userGetAttributes,
    };
    return this.findAndCount(q);
  }

  /**
   * Return a single recording for a user.
   */
  var getOne = async function(user, id) {
    var query = {
      where: {
        "$and": [
          { id: id },
          await recordingsFor(user),
        ],
      },
      include: [
        { model: models.Tag, },
        { model: models.Device, where: {}, attributes: ["devicename", "id"] },
      ],
      attributes: this.userGetAttributes.concat(['rawFileKey']),
    };

    return await this.findOne(query);
  };

  var recordingsFor = async function(user) {
    var deviceIds = await user.getDeviceIds();
    var groupIds = await user.getGroupsIds();
    return await {"$or": [
      {public: true},
      {GroupId: {"$in": groupIds}},
      {DeviceId: {"$in": deviceIds}},
    ]};
  };

  var options = {
    classMethods: {
      addAssociations: addAssociations,
      query: query,
      getOne: getOne,
      processingAttributes: processingAttributes,
      processingStates: processingStates,
      apiSettableFields: apiSettableFields,
      userGetAttributes: userGetAttributes,
    },
    instanceMethods: {
      canGetRaw: canGetRaw,
      getFileName: getFileName,
      getUserPermissions: getUserPermissions,
    },
  };

  return sequelize.define(name, attributes, options);
}

/**
 * Returns JSON describing what the user can do to the recording.
 * Permission types: DELETE, TAG, VIEW,
 * //TODO This will be edited in the future when recordings can be public.
 */
function getUserPermissions(user) {
  // For now if the user is in the group that owns the recording they have all
  // permission. This will be changed in the future.
  var permissions = {
    canDelete: false,
    canTag: false,
    canView: false,
  }
  var recording = this;
  return new Promise(async (resolve, reject) => {
    var groupIds = await user.getGroupsIds();
    if (groupIds.indexOf(recording.GroupId) !== -1) {
      permissions.canDelete = true;
      permissions.canTag = true;
      permissions.canView = true;
    }
    return resolve(permissions);
  });
}

function canGetRaw() {
  if (this.get('type') == 'thermalRaw')
    return true;
  return false;
}

function getFileName() {
  var ext = "";
  if (this.fileMimeType == 'video/mp4') ext = ".mp4"
  return moment(new Date(this.recordingDateTime)).tz("Pacific/Auckland")
    .format("YYYYMMDD-HHmmss") + ext;
}

var userGetAttributes = [
  'id',
  'rawFileSize',
  'fileSize',
  'fileMimeType',
  'processingState',
  'duration',
  'recordingDateTime',
  'location',
  'version',
  'batteryLevel',
  'batteryCharging',
  'airplaneModeOn',
  'type',
  'additionalMetadata',
  'GroupId',
  'fileKey'
];

var apiSettableFields = [
  'type',
  'duration',
  'recordingDateTime',
  'location',
  'version',
  'batteryCharging',
  'batteryLevel',
  'airplaneModeOn',
  'additionalMetadata',
  'processingMeta',
];

var processingStates = {
  thermalRaw: ['toMp4', 'FINISHED'],
}

var processingAttributes = [
  'id',
  'rawFileKey',
  'fileKey',
  'processingMeta',
  'processingState',
  'jobKey',
  'type',
];

function addAssociations(models) {
  models.Recording.belongsTo(models.Group);
  models.Recording.belongsTo(models.Device);
  models.Recording.hasMany(models.Tag);
}
<commit_msg>Fix tagged/not-tagged query<commit_after>var util = require('./util/util');
var validation = require('./util/validation');
var moment = require('moment-timezone');

module.exports = function(sequelize, DataTypes) {
  var name = 'Recording';

  var attributes = {
    // Raw file data.
    rawFileKey: DataTypes.STRING,
    rawFileSize: DataTypes.INTEGER,
    // Processing fields. Fields set by and for the processing.
    fileKey: DataTypes.STRING,
    fileSize: DataTypes.STRING,
    fileMimeType: DataTypes.STRING,
    processingStartTime: DataTypes.DATE,
    processingMeta: DataTypes.JSONB,
    processingState: DataTypes.STRING,
    passedFilter: DataTypes.BOOLEAN,
    // recording metadata.
    duration: DataTypes.INTEGER,
    recordingDateTime: DataTypes.DATE,
    location: {
      type: DataTypes.GEOMETRY,
      set: util.geometrySetter,
      validate: { isLatLon: validation.isLatLon },
    },
    version: DataTypes.STRING,
    // Battery relevant fields.
    batteryLevel: DataTypes.DOUBLE,
    batteryCharging: DataTypes.STRING,
    airplaneModeOn: DataTypes.BOOLEAN,
    // Other fields
    jobKey: DataTypes.STRING,
    type: DataTypes.STRING,
    public: { type: DataTypes.BOOLEAN, defaultValue: false},
    additionalMetadata: DataTypes.JSONB,
  };

  var models = sequelize.models;

  /**
    * Return one or more recordings for a user matching the query
    * arguments given.
    */
  var query = async function(user, where, taggedOnly, offset, limit, order) {
    // If query should be filtered by tagged or not or ignored.
    var sqlLiteral = '';
    var tagRequired = false;
    if (taggedOnly == true) {
      tagRequired = true;
    } else if (taggedOnly == false) {
      sqlLiteral = 'NOT EXISTS (SELECT * FROM "Tags" WHERE  "Tags"."RecordingId" = "Recording".id)';
      tagRequired = false;
    }

    if (order == null) {
      order = [
        // Sort by recordingDatetime but handle the case of the
        // timestamp being missing and fallback to sorting by id.
        [sequelize.fn("COALESCE", sequelize.col('recordingDateTime'), '1970-01-01'), "DESC"],
        ["id", "DESC"],
      ];
    }

    var q = {
      where: {
        "$and": [
          where, // User query
          await recordingsFor(user),
          sequelize.literal(sqlLiteral),
        ],
      },
      order: order,
      include: [
        { model: models.Group },
        { model: models.Tag, required: tagRequired },
        { model: models.Device, where: {}, attributes: ["devicename", "id"] },
      ],
      limit: limit,
      offset: offset,
      attributes: userGetAttributes,
    };
    return this.findAndCount(q);
  }

  /**
   * Return a single recording for a user.
   */
  var getOne = async function(user, id) {
    var query = {
      where: {
        "$and": [
          { id: id },
          await recordingsFor(user),
        ],
      },
      include: [
        { model: models.Tag, },
        { model: models.Device, where: {}, attributes: ["devicename", "id"] },
      ],
      attributes: this.userGetAttributes.concat(['rawFileKey']),
    };

    return await this.findOne(query);
  };

  var recordingsFor = async function(user) {
    var deviceIds = await user.getDeviceIds();
    var groupIds = await user.getGroupsIds();
    return await {"$or": [
      {public: true},
      {GroupId: {"$in": groupIds}},
      {DeviceId: {"$in": deviceIds}},
    ]};
  };

  var options = {
    classMethods: {
      addAssociations: addAssociations,
      query: query,
      getOne: getOne,
      processingAttributes: processingAttributes,
      processingStates: processingStates,
      apiSettableFields: apiSettableFields,
      userGetAttributes: userGetAttributes,
    },
    instanceMethods: {
      canGetRaw: canGetRaw,
      getFileName: getFileName,
      getUserPermissions: getUserPermissions,
    },
  };

  return sequelize.define(name, attributes, options);
}

/**
 * Returns JSON describing what the user can do to the recording.
 * Permission types: DELETE, TAG, VIEW,
 * //TODO This will be edited in the future when recordings can be public.
 */
function getUserPermissions(user) {
  // For now if the user is in the group that owns the recording they have all
  // permission. This will be changed in the future.
  var permissions = {
    canDelete: false,
    canTag: false,
    canView: false,
  }
  var recording = this;
  return new Promise(async (resolve, reject) => {
    var groupIds = await user.getGroupsIds();
    if (groupIds.indexOf(recording.GroupId) !== -1) {
      permissions.canDelete = true;
      permissions.canTag = true;
      permissions.canView = true;
    }
    return resolve(permissions);
  });
}

function canGetRaw() {
  if (this.get('type') == 'thermalRaw')
    return true;
  return false;
}

function getFileName() {
  var ext = "";
  if (this.fileMimeType == 'video/mp4') ext = ".mp4"
  return moment(new Date(this.recordingDateTime)).tz("Pacific/Auckland")
    .format("YYYYMMDD-HHmmss") + ext;
}

var userGetAttributes = [
  'id',
  'rawFileSize',
  'fileSize',
  'fileMimeType',
  'processingState',
  'duration',
  'recordingDateTime',
  'location',
  'version',
  'batteryLevel',
  'batteryCharging',
  'airplaneModeOn',
  'type',
  'additionalMetadata',
  'GroupId',
  'fileKey'
];

var apiSettableFields = [
  'type',
  'duration',
  'recordingDateTime',
  'location',
  'version',
  'batteryCharging',
  'batteryLevel',
  'airplaneModeOn',
  'additionalMetadata',
  'processingMeta',
];

var processingStates = {
  thermalRaw: ['toMp4', 'FINISHED'],
}

var processingAttributes = [
  'id',
  'rawFileKey',
  'fileKey',
  'processingMeta',
  'processingState',
  'jobKey',
  'type',
];

function addAssociations(models) {
  models.Recording.belongsTo(models.Group);
  models.Recording.belongsTo(models.Device);
  models.Recording.hasMany(models.Tag);
}
<|endoftext|>


<commit_before>/* @flow */
'use strict';
import React, { Component, PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
	xAxisContainer: {
		flexDirection: 'row',
		flex: 0,
		backgroundColor: 'transparent',
		justifyContent: 'space-between',
	},
	axisText: {
		flex: 1,
		backgroundColor: 'transparent',
	},
});

export default class XAxis extends Component {

	static propTypes = {
		axisColor: PropTypes.any.isRequired,
		axisLabelColor: PropTypes.any.isRequired,
		axisLineWidth: PropTypes.number.isRequired,
		data: PropTypes.arrayOf(PropTypes.array),
		showXAxisLabels: PropTypes.bool.isRequired,
		style: PropTypes.any,
		width: PropTypes.number.isRequired,
		align: PropTypes.string,
		labelFontSize: PropTypes.number.isRequired,
		xAxisTransform: PropTypes.func,
	};
	static defaultProps = {
		align: 'center',
	};

	render() {
		const data = this.props.data || [];
		let transform = (d) => d;
		if (this.props.xAxisTransform && typeof this.props.xAxisTransform === 'function') {
			transform = this.props.xAxisTransform;
		}
		return (
			<View
				style={[
					styles.xAxisContainer,
					{
						borderTopColor: this.props.axisColor,
						borderTopWidth: this.props.axisLineWidth,
					},
				]}
			>
			{(() => {
				if (!this.props.showXAxisLabels) return null;
				return data.map((d, i) => {
					const item = transform(d[0]);
					if (typeof item !== 'number' && !item) return null;
					return (
						<Text
							key={i}
							style={[
								styles.axisText,
								{
									textAlign: this.props.align,
									color: this.props.axisLabelColor,
									fontSize: this.props.labelFontSize,
								},
							]}
						>{item}</Text>
				);
				});
			})()}
			</View>
		);
	}
}
<commit_msg>Fix shifted Y-Axis bug #102<commit_after>/* @flow */
'use strict';
import React, { Component, PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
	xAxisContainer: {
		flexDirection: 'row',
		flex: 0,
		backgroundColor: 'transparent',
		justifyContent: 'space-between',
	},
	axisText: {
		flex: 1,
		backgroundColor: 'transparent',
	},
});

export default class XAxis extends Component {

	static propTypes = {
		axisColor: PropTypes.any.isRequired,
		axisLabelColor: PropTypes.any.isRequired,
		axisLineWidth: PropTypes.number.isRequired,
		data: PropTypes.arrayOf(PropTypes.array),
		showXAxisLabels: PropTypes.bool.isRequired,
		style: PropTypes.any,
		width: PropTypes.number.isRequired,
		align: PropTypes.string,
		labelFontSize: PropTypes.number.isRequired,
		xAxisTransform: PropTypes.func,
	};
	static defaultProps = {
		align: 'center',
	};

	render() {
		const data = this.props.data || [];
		let transform = (d) => d;
		if (this.props.xAxisTransform && typeof this.props.xAxisTransform === 'function') {
			transform = this.props.xAxisTransform;
		}
		return (
			<View
				style={[
					styles.xAxisContainer,
					{
						borderTopColor: this.props.axisColor,
						borderTopWidth: this.props.axisLineWidth,
					},
					this.props.style,
				]}
			>
			{(() => {
				if (!this.props.showXAxisLabels) return null;
				return data.map((d, i) => {
					const item = transform(d[0]);
					if (typeof item !== 'number' && !item) return null;
					return (
						<Text
							key={i}
							style={[
								styles.axisText,
								{
									textAlign: this.props.align,
									color: this.props.axisLabelColor,
									fontSize: this.props.labelFontSize,
								},
							]}
						>{item}</Text>
				);
				});
			})()}
			</View>
		);
	}
}
<|endoftext|>


<commit_before>var pgDefault = function pgDefault(queryString, queryOptions, defaultLimit) {
  var schema = queryOptions.schema;
  var table = queryOptions.table;
  var searchField = queryOptions.searchField;
  var gid = queryOptions.gid || 'gid';
  var sqlSearchField = searchField ? table + '."' + searchField + '" AS "NAMN",' : "";
  var fields = queryOptions.fields;
  var geometryField = queryOptions.geometryName || "geom";
  var centroid = 'ST_AsText(ST_PointOnSurface(' + table + '."' + geometryField + '")) AS "GEOM" ';
  var sqlFields = fields ? fields.join(',') + "," : "";
  var type = " '" + table + "'" + ' AS "TYPE", ';
  var condition = queryString;
  var searchString;
  var limitNumber = queryOptions.limit || defaultLimit || 1000;
  var limit = ' LIMIT ' + limitNumber.toString() + ' ';

  searchString =
    'SELECT ' +
    sqlSearchField +
    ' ' + table + '."' + gid + '" AS "GID", ' +
    type +
    centroid +
    ' FROM ' + schema + '.' + table +
    ' WHERE LOWER(' + table + '."' + searchField + '"' + ") ILIKE LOWER('" + condition + "%')" +
    ' ORDER BY ' + table + '."' + searchField + '"' +
    limit + ';';

  return searchString;
}

module.exports = pgDefault;
<commit_msg>Cast the searchField field to text in pgdefault.js to allow numeric fields<commit_after>var pgDefault = function pgDefault(queryString, queryOptions, defaultLimit) {
  var schema = queryOptions.schema;
  var table = queryOptions.table;
  var searchField = queryOptions.searchField;
  var gid = queryOptions.gid || 'gid';
  var sqlSearchField = searchField ? 'CAST(' + table + '."' + searchField + '" AS TEXT) AS "NAMN",' : "";
  var fields = queryOptions.fields;
  var geometryField = queryOptions.geometryName || "geom";
  var centroid = 'ST_AsText(ST_PointOnSurface(' + table + '."' + geometryField + '")) AS "GEOM" ';
  var sqlFields = fields ? fields.join(',') + "," : "";
  var type = " '" + table + "'" + ' AS "TYPE", ';
  var condition = queryString;
  var searchString;
  var limitNumber = queryOptions.limit || defaultLimit || 1000;
  var limit = ' LIMIT ' + limitNumber.toString() + ' ';

  searchString =
    'SELECT ' +
    sqlSearchField +
    ' ' + table + '."' + gid + '" AS "GID", ' +
    type +
    centroid +
    ' FROM ' + schema + '.' + table +
    ' WHERE LOWER(CAST(' + table + '."' + searchField + '"' + " AS TEXT)) ILIKE LOWER('" + condition + "%')" +
    ' ORDER BY ' + table + '."' + searchField + '"' +
    limit + ';';

  return searchString;
}

module.exports = pgDefault;
<|endoftext|>


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

var Schema = mongoose.Schema,
  ObjectId = Schema.ObjectId;

var workspacesSchema = mongoose.Schema({
  _id: {type: String},
  rows: [{
    rowId: String,
    rawAudio: String,
    audioBlocks: [{
      length: Number,
      row_offset: Number,
      file_offset: Number,
      flags: [{
        start_time: Number,
        duration: Number,
        type: String
      }]
    }]
  }]
});

module.exports = mongoose.model('Workspace', howlsSchema);
<commit_msg>Updates workspace model<commit_after>var mongoose = require("mongoose") ;

var Schema = mongoose.Schema,
  ObjectId = Schema.ObjectId;

var workspacesSchema = mongoose.Schema({
  _id: {type: String},
  rows: [{
    rowId: String,
    rawAudio: String,
    audioBlocks: [{
      length: Number,
      row_offset: Number,
      file_offset: Number,
      flags: [{
        start_time: Number,
        duration: Number,
        type: String
      }]
    }]
  }]
});

module.exports = mongoose.model('Workspace', workspaceSchema);
<|endoftext|>


<commit_before>/**
 * StopFlash
 *
 * https://github.com/JWhile/StopFlash
 *
 * stopflash.js
 */

// class StopFlashUI extends Builder
function StopFlashUI()
{
    this.super('div');

    this.mainTab = new Builder('div');

    this.content = new StopFlashTabs()
        .className('content')
        .addTab(this.mainTab)
        .addTab(new Builder('div')
            .text('Whitelist tab'))
        .addTab(new Builder('div')
            .text('Options tab'));

    var self = this;

    this.append(new Builder('div')
            .className('head')
            .append(new Builder('p')
                .className('logo')
                .html('STP Flash')))
        .append(new Builder('div')
            .className('menu')
            .append(new Builder('a')
                .text('Home')
                .event('click', function()
                {
                    self.content.setTab(0);
                }))
            .append(new Builder('a')
                .text('Whitelist')
                .event('click', function()
                {
                    self.content.setTab(1);
                }))
            .append(new Builder('a')
                .text('Options')
                .event('click', function()
                {
                    self.content.setTab(2);
                })))
        .append(this.content)
        .append(new Builder('div')
            .className('foot')
            .html('https://github.com/JWhile/StopFlash'));
}
// function setElements(Array<Object> elements):void
StopFlashUI.prototype.setElements = function(elements)
{
    this.mainTab.clear();

    if(elements != null && elements.length > 0)
    {
        var self = this;

        for(var i = 0, e; i < elements.length; ++i)
        {
            e = elements[i];

            this.mainTab.append(new Builder('div')
                .className('flash-element')
                .append(new Builder('div')
                    .className('flash-menu')
                    .append(new Builder('a')
                        .text(e.blocked? 'Débloquer' : 'Bloquer')
                        .event('click', function()
                        {
                            //
                        }))
                    .append(new Builder('a')
                        .text(e.whitelist? '- Whitelist' : '+ Whitelist')
                        .event('click', function()
                        {
                            //
                        })))
                .append(new Builder('p')
                    .className('flash-url')
                    .text(e.url))
                .append(new Builder('span')
                    .className('flash-type')
                    .text(e.type)));
        }
    }
    else
    {
        this.mainTab.append(new Builder('p').text('Aucun element trouvé sur cette page'));
    }
};
fus.extend(StopFlashUI, Builder);

// class StopFlashTabs extends Builder
function StopFlashTabs()
{
    this.super('div');

    this.tabs = []; // :Array<Builder>
}
// function addTab(Builder builder):@Chainable
StopFlashTabs.prototype.addTab = function(builder)
{
    this.tabs.push(new Builder('div')
        .className('tab')
        .css('left', (this.tabs.length * 300) +'px')
        .append(builder.className('tab-content'))
        .insert(this));

    return this;
};
// function setTab(int index):@Chainable
StopFlashTabs.prototype.setTab = function(index)
{
    for(var i = 0; i < this.tabs.length; ++i)
    {
        if(index === i)
        {
            this.tabs[i].css('position', 'relative')
                    .css('opacity', '1');
        }
        else
        {
            this.tabs[i].css('position', '')
                    .css('opacity', '0.3');
        }
    }

    this.css('left', '-'+ (index * 300) +'px');

    return this;
};
fus.extend(StopFlashTabs, Builder);

// main
var ui = new StopFlashUI()
    .insert(document.body);

ui.content.setTab(0);

ui.setElements(null);

chrome.tabs.query({'highlighted': true, 'currentWindow': true}, function(tabs)
{
    var port = chrome.runtime.connect({'name': 'stopflashPopup'});

    port.onMessage.addListener(function(rep)
    {
        if(rep['stopflashData'])
        {
            ui.setElements(rep['stopflashData']);
        }
    });

    port.postMessage({'stopflashInit': tabs[0].id});
});
<commit_msg>Add class StopFlashPopup & move main code in<commit_after>/**
 * StopFlash
 *
 * https://github.com/JWhile/StopFlash
 *
 * stopflash.js
 */

// class StopFlashPopup
function StopFlashPopup(doc)
{
    this.ui = new StopFlashUI()
            .insert(doc.body);

    this.ui.content.setTab(0);

    this.ui.setElements(null);

    var self = this;

    chrome.tabs.query({'highlighted': true, 'currentWindow': true}, function(tabs)
    {
        var port = chrome.runtime.connect({'name': 'stopflashPopup'});

        port.onMessage.addListener(function(rep)
        {
            if(rep['stopflashData'])
            {
                self.ui.setElements(rep['stopflashData']);
            }
        });

        port.postMessage({'stopflashInit': tabs[0].id});
    });
}

// class StopFlashUI extends Builder
function StopFlashUI()
{
    this.super('div');

    this.mainTab = new Builder('div');

    this.content = new StopFlashTabs()
        .className('content')
        .addTab(this.mainTab)
        .addTab(new Builder('div')
            .text('Whitelist tab'))
        .addTab(new Builder('div')
            .text('Options tab'));

    var self = this;

    this.append(new Builder('div')
            .className('head')
            .append(new Builder('p')
                .className('logo')
                .html('STP Flash')))
        .append(new Builder('div')
            .className('menu')
            .append(new Builder('a')
                .text('Home')
                .event('click', function()
                {
                    self.content.setTab(0);
                }))
            .append(new Builder('a')
                .text('Whitelist')
                .event('click', function()
                {
                    self.content.setTab(1);
                }))
            .append(new Builder('a')
                .text('Options')
                .event('click', function()
                {
                    self.content.setTab(2);
                })))
        .append(this.content)
        .append(new Builder('div')
            .className('foot')
            .html('https://github.com/JWhile/StopFlash'));
}
// function setElements(Array<Object> elements):void
StopFlashUI.prototype.setElements = function(elements)
{
    this.mainTab.clear();

    if(elements != null && elements.length > 0)
    {
        var self = this;

        for(var i = 0, e; i < elements.length; ++i)
        {
            e = elements[i];

            this.mainTab.append(new Builder('div')
                .className('flash-element')
                .append(new Builder('div')
                    .className('flash-menu')
                    .append(new Builder('a')
                        .text(e.blocked? 'Débloquer' : 'Bloquer')
                        .event('click', function()
                        {
                            //
                        }))
                    .append(new Builder('a')
                        .text(e.whitelist? '- Whitelist' : '+ Whitelist')
                        .event('click', function()
                        {
                            //
                        })))
                .append(new Builder('p')
                    .className('flash-url')
                    .text(e.url))
                .append(new Builder('span')
                    .className('flash-type')
                    .text(e.type)));
        }
    }
    else
    {
        this.mainTab.append(new Builder('p').text('Aucun element trouvé sur cette page'));
    }
};
fus.extend(StopFlashUI, Builder);

// class StopFlashTabs extends Builder
function StopFlashTabs()
{
    this.super('div');

    this.tabs = []; // :Array<Builder>
}
// function addTab(Builder builder):@Chainable
StopFlashTabs.prototype.addTab = function(builder)
{
    this.tabs.push(new Builder('div')
        .className('tab')
        .css('left', (this.tabs.length * 300) +'px')
        .append(builder.className('tab-content'))
        .insert(this));

    return this;
};
// function setTab(int index):@Chainable
StopFlashTabs.prototype.setTab = function(index)
{
    for(var i = 0; i < this.tabs.length; ++i)
    {
        if(index === i)
        {
            this.tabs[i].css('position', 'relative')
                    .css('opacity', '1');
        }
        else
        {
            this.tabs[i].css('position', '')
                    .css('opacity', '0.3');
        }
    }

    this.css('left', '-'+ (index * 300) +'px');

    return this;
};
fus.extend(StopFlashTabs, Builder);

// main
var popup = new StopFlashPopup(document);
<|endoftext|>


<commit_before>define(['appSettings', 'connectionManager'], function (appSettings, connectionManager) {
    'use strict';

    var isSyncing;

    return {

        sync: function (options) {

            console.log('localSync.sync starting...');

            if (isSyncing) {
                return Promise.resolve();
            }

            isSyncing = true;

            return new Promise(function (resolve, reject) {

                require(['multiserversync'], function (MultiServerSync) {

                    options = options || {};

                    options.cameraUploadServers = appSettings.cameraUploadServers();

                    new MultiServerSync().sync(connectionManager, options).then(function () {

                        isSyncing = null;
                        resolve();

                    }, function (err) {

                        isSyncing = null;
                        reject(err);
                    });
                });

            });
        }
    };

});<commit_msg>update localsync.js<commit_after>define(['connectionManager'], function (connectionManager) {
    'use strict';

    var isSyncing;

    return {

        sync: function (options) {

            console.log('localSync.sync starting...');

            if (isSyncing) {
                return Promise.resolve();
            }

            isSyncing = true;

            return new Promise(function (resolve, reject) {

                require(['multiserversync'], function (MultiServerSync) {

                    options = options || {};

                    // TODO, get from appSettings
                    options.cameraUploadServers = [];

                    new MultiServerSync().sync(connectionManager, options).then(function () {

                        isSyncing = null;
                        resolve();

                    }, function (err) {

                        isSyncing = null;
                        reject(err);
                    });
                });

            });
        }
    };

});<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/', express.static('public'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

io = require('socket.io')();

app.io=io;
//app.arduino=require('./arduino');

var broker=require('./broker');
broker.subscribe();

module.exports = app;<commit_msg>add port listen<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

app = express();
var port = process.env.PORT || 3000;
app.listen(port);
console.log("Listening on port " + port);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/', express.static('public'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

io = require('socket.io')();

app.io=io;
//app.arduino=require('./arduino');

var broker=require('./broker');
broker.subscribe();

module.exports = app;<|endoftext|>


<commit_before>var renderer;
var renderers = {};
var effect;
renderers['3d'] = ["../../node_modules/three/examples/js/renderers/CSS3DRenderer.js"];
renderers['vr'] = ["../../node_modules/three/examples/js/renderers/CSS3DStereoRenderer.js"];

var activeRenderer = null;

function changeRenderer(renderer) {
	activeRenderer = renderer;
	jQuery('.group-renderer').removeClass('active');
	jQuery('#' + renderer).addClass('active');
}

function loadRenderer(type) {
	delete THREE.CSS3DRenderer;
	delete THREE.CSS3DStereoRenderer;
	for ( var i = 0; i < renderers[type].length; i ++ ) {
		loadJS(renderers[type][i], updateRenderer, document.body);
	}
}

function initRenderer( type ) {
	switch ( type ) {
		case '3d':
			if ( typeof(THREE.CSS3DRenderer) !== 'function' ) {
				loadRenderer( type );
			} else {
				if (renderer instanceof THREE.CSS3DRenderer) {
					renderer.render( scene, camera );
				}
				else {
					renderer = new THREE.CSS3DRenderer();
					reset();
					renderer.domElement.style.position = 'absolute';
					container = document.getElementById( 'container' );
					container.appendChild( renderer.domElement );
					renderer.setSize( window.innerWidth, window.innerHeight );
				}
			}
			break;

		case 'vr':
			if ( typeof(THREE.CSS3DStereoRenderer) !== 'function' ) {
				loadRenderer( type );
			} else {
				if (renderer instanceof THREE.CSS3DStereoRenderer) {
					effect.render( scene, camera );
				}
				else {
					renderer = new THREE.CSS3DStereoRenderer();
					reset();
					renderer.setSize( window.innerWidth, window.innerHeight );
					element = renderer.domElement;
					container = document.getElementById('container');
					container.appendChild(element);

					effect = new THREE.StereoEffect( renderer );
					effect.setSize( window.innerWidth, window.innerHeight );
					effect.setEyeSeparation(3);
				}
			}
			break;
	}
}

function updateRenderer() {
	initRenderer(activeRenderer);
}
<commit_msg>Use require<commit_after>var renderer;
var effect;
var activeRenderer = null;

function changeRenderer(_renderer) {
	activeRenderer = _renderer;
	jQuery('.group-renderer').removeClass('active');
	jQuery('#' + _renderer).addClass('active');
}

function updateRenderer() {
	render(activeRenderer);
}

function render( type ) {
	switch ( type ) {
		case '3d':
			require(['CSS3DRenderer'], function () {
				if (renderer instanceof THREE.CSS3DRenderer) {
					renderer.render( scene, camera );
				}
				else {
					renderer = new THREE.CSS3DRenderer();
					reset();
					renderer.domElement.style.position = 'absolute';
					container = document.getElementById( 'container' );
					container.appendChild( renderer.domElement );
					renderer.setSize( window.innerWidth, window.innerHeight );
				}
			});
			break;

		case 'vr':
			require(['CSS3DStereoRenderer'], function () {
				if (renderer instanceof THREE.CSS3DStereoRenderer) {
					effect.render( scene, camera );
				}
				else {
					renderer = new THREE.CSS3DStereoRenderer();
					reset();
					renderer.setSize( window.innerWidth, window.innerHeight );
					element = renderer.domElement;
					container = document.getElementById('container');
					container.appendChild(element);

					effect = new THREE.StereoEffect( renderer );
					effect.setSize( window.innerWidth, window.innerHeight );
					effect.setEyeSeparation(3);
				}
			});
			break;
	}
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    grunt.registerTask('dev', ['concat', 'sass', 'imagemin', 'autoprefixer', 'cssmin', 'copy']);
    grunt.registerTask('watch:dev', function() {
        console.log(grunt.config.get(['watch']).dev);
        grunt.config('watch', grunt.config.get(['watch']).dev);
        grunt.task.run('watch');
    });
};
<commit_msg>remove some debugging...<commit_after>module.exports = function(grunt) {
    grunt.registerTask('dev', ['concat', 'sass', 'imagemin', 'autoprefixer', 'cssmin', 'copy']);
    grunt.registerTask('watch:dev', function() {
        grunt.config('watch', grunt.config.get(['watch']).dev);
        grunt.task.run('watch');
    });
};
<|endoftext|>


<commit_before>var Promise = require('es6-promise').Promise;
var replaceStream = require('replacestream');
var shell = require("shelljs");
var prompt = require("prompt");
var init = require('./init');
var log = require('./utils/log');
var exec = require('./utils/exec').exec;
var fs = require('./utils/fs');
var bower = require('./utils/bower');

function npmGlobalPath() {
    return shell.exec('npm config get prefix', {silent:true}).output.replace(/\s+$/g, '') + "/lib/node_modules" ;
}

function renameFiles(component){
    return Promise.all([
        fs.rename('./dot.gitignore', 'dot',''),
        fs.rename('./**/main.*', 'main',component)
    ]);
}

function createStructure(dir, component, repo, author){
    log.info("\nCopying Component Files ... \n");
    return fs.copyDirectory(dir, './' + component,
        function(read, write, file){
            read.pipe(replaceStream('{{ component }}', component))
                .pipe(replaceStream('{{ git.username }}', repo.match(/.com\:(.*)\//)[1]))
                .pipe(replaceStream('{{ git.author }}', author))
                .pipe(write);
    });
}

function newComponent(dir, component, repo, author) {
    return createStructure(dir, component, repo, author).then(function(output) {
        shell.cd(component);
        return renameFiles(component);
    }).then(function(output){
        return init.git(repo);
    }).then(function(output){
        log.onSuccess(output);
        return init.ghPages();
    }).then(function(output){
        log.onSuccess(output);
        return installNpms();
    }).then(function(output){
        log.onSuccess(output);
        log.info("\nInstalling Bower Modules ... \n");
        return bower.install();
    }).then(function(){
        log.info([
            'Ready!',
            ' * Please go to your new directory : `cd ' + component + '`',
            ' * view the basic site : `component serve`',
            ' * to see more tasks please see : `https://github.com/skyglobal/component-helper/blob/master/API.md`'
        ].join('\n'));
    }).catch(log.onError);
}

function installNpms(){
    log.info("\nInstalling Node Modules ... \n");
    return exec('npm',['install']).then(function(output){
        log.onSuccess(output);
    }).catch(log.onError);
}

function createAll(componentName){
    console.log("Creating new component " + componentName);
    return new Promise(function(resolve, reject){
        prompt.start();
        prompt.get([{
            description: 'GitHub Repository SSH URL',
            name: 'repo'
        }], function(err, result) {
            if (!result) return;
            var gitUrlMatch = result.repo.match(/.com\:(.*)\//);

            var author = shell.exec('git config user.name', {silent:true}).output.replace(/\s+$/g, '');
            var moduleDir = npmGlobalPath() + '/component-helper/component-structure';

            if (!gitUrlMatch){
                reject('Github Repository URL must be a url');
            }
            if (fs.existsSync(componentName)){
                reject('Component `' + componentName + '` already exists');
            }
            newComponent(moduleDir, componentName, result.repo, author)
                .then(resolve).catch(reject);
        });
    });
}

module.exports = createAll;<commit_msg>turn off colours to ensure all terminal types can see prompts fixes #33<commit_after>var Promise = require('es6-promise').Promise;
var replaceStream = require('replacestream');
var shell = require("shelljs");
var prompt = require("prompt");
var init = require('./init');
var log = require('./utils/log');
var exec = require('./utils/exec').exec;
var fs = require('./utils/fs');
var bower = require('./utils/bower');

function npmGlobalPath() {
    return shell.exec('npm config get prefix', {silent:true}).output.replace(/\s+$/g, '') + "/lib/node_modules" ;
}

function renameFiles(component){
    return Promise.all([
        fs.rename('./dot.gitignore', 'dot',''),
        fs.rename('./**/main.*', 'main',component)
    ]);
}

function createStructure(dir, component, repo, author){
    log.info("\nCopying Component Files ... \n");
    return fs.copyDirectory(dir, './' + component,
        function(read, write, file){
            read.pipe(replaceStream('{{ component }}', component))
                .pipe(replaceStream('{{ git.username }}', repo.match(/.com\:(.*)\//)[1]))
                .pipe(replaceStream('{{ git.author }}', author))
                .pipe(write);
    });
}

function newComponent(dir, component, repo, author) {
    return createStructure(dir, component, repo, author).then(function(output) {
        shell.cd(component);
        return renameFiles(component);
    }).then(function(output){
        return init.git(repo);
    }).then(function(output){
        log.onSuccess(output);
        return init.ghPages();
    }).then(function(output){
        log.onSuccess(output);
        return installNpms();
    }).then(function(output){
        log.onSuccess(output);
        log.info("\nInstalling Bower Modules ... \n");
        return bower.install();
    }).then(function(){
        log.info([
            'Ready!',
            ' * Please go to your new directory : `cd ' + component + '`',
            ' * view the basic site : `component serve`',
            ' * to see more tasks please see : `https://github.com/skyglobal/component-helper/blob/master/API.md`'
        ].join('\n'));
    }).catch(log.onError);
}

function installNpms(){
    log.info("\nInstalling Node Modules ... \n");
    return exec('npm',['install']).then(function(output){
        log.onSuccess(output);
    }).catch(log.onError);
}

function createAll(componentName){
    console.log("Creating new component " + componentName);
    return new Promise(function(resolve, reject){
        prompt.colors = false;
        prompt.start();
        prompt.get([{
            description: 'GitHub Repository SSH URL',
            name: 'repo'
        }], function(err, result) {
            if (!result) return;
            var gitUrlMatch = result.repo.match(/.com\:(.*)\//);

            var author = shell.exec('git config user.name', {silent:true}).output.replace(/\s+$/g, '');
            var moduleDir = npmGlobalPath() + '/component-helper/component-structure';

            if (!gitUrlMatch){
                reject('Github Repository URL must be a url');
            }
            if (fs.existsSync(componentName)){
                reject('Component `' + componentName + '` already exists');
            }
            newComponent(moduleDir, componentName, result.repo, author)
                .then(resolve).catch(reject);
        });
    });
}

module.exports = createAll;<|endoftext|>


<commit_before>jest.autoMockOff();

import React from 'react';
import TestUtils from 'react-addons-test-utils';

const Table = require('../js/components/table.jsx').default;

describe('Test table component', () => {
  var column, data, checkboxOnChange, checkboxInitialize, table;
  beforeEach(() => {
    column = [{
      title: 'ID',
      key: 'id',
      width: '150px',
      dataIndex: 'id',
      sortBy: 'number',
      filter: [{
        name: 'id大于等于4',
        key: '1',
        filter: function(item) {
          if (item.id >= 4) {
            return true;
          }
        }
      }, {
        name: 'id小于4',
        key: '2',
        filter: function(item) {
          if (item.id < 4) {
            return true;
          }
        }
      }]
    }, {
      title: 'Category',
      key: 'category',
      width: '120px',
      dataIndex: 'category',
      sortBy: 'string'
    }, {
      title: 'Flavor',
      key: 'flavor',
      width: '70px',
      dataIndex: 'flavor',
      sortBy: 'string'
    }, {
      title: 'Level',
      key: 'level',
      dataIndex: 'level',
      filter: [{
        name: 'level 1',
        key: '1',
        filter: function(item) {
          return item.level.localeCompare('First Level') === 0 ? true : false;
        }
      }, {
        name: 'level 2',
        key: '2',
        filter: function(item) {
          return item.level.localeCompare('Second Level') === 0 ? true : false;
        }
      }, {
        name: 'level 3',
        key: '3',
        filter: function(item) {
          return item.level.localeCompare('Third Level') === 0 ? true : false;
        }
      }, {
        name: 'level 4',
        key: '4',
        filter: function(item) {
          return item.level.localeCompare('Fourth Level') === 0 ? true : false;
        }
      }],
      sortBy: function(item1, item2) {
        var weight = ['First Level', 'Second Level', 'Third Level', 'Fourth Level'];
        if (weight.indexOf(item1.level) > weight.indexOf(item2.level)) {
          return 1;
        } else if (weight.indexOf(item1.level) < weight.indexOf(item2.level)) {
          return -1;
        } else {
          return 0;
        }
      }
    }, {
      title: 'CPU',
      key: 'cpu',
      dataIndex: 'cpu',
      sortBy: 'number',
      width: '50px'
    }, {
      title: 'Price',
      key: 'price',
      dataIndex: 'price',
      sortBy: 'number'
    }, {
      title: 'Double Price',
      sortBy: function(item1, item2) {
        if (item1.price * 2 > item2.price * 2) {
          return 1;
        } else if (item1.price * 2 < item2.price * 2) {
          return -1;
        } else {
          return 0;
        }
      },
      render: function(col, item, index) {
        return
{item.price * 2}
;
      }
    }, {
      title: 'Data Print',
      key: 'data_print',
      printData: function(col, item, e) {
        console.log('event:', e, 'GET COLUMN:', col, ' DATA:', item);
      },
      render: function(col, item, index) {
        if (item.id > 4) {
          return
Printing Disabled
;
        } else {
          return
{'Print ID ' + item.id}
;
        }
      }
    }];

    data = [{
      id: 1,
      category: 'Micro-1',
      flavor: 'Micro',
      level: 'First Level',
      cpu: '1',
      price: '0.056'
    }, {
      id: 2,
      category: 'Standard-3',
      flavor: 'Standard',
      level: 'Second Level',
      cpu: '3',
      price: '0.444'
    }, {
      id: 3,
      category: 'Micro-2',
      flavor: 'Micro',
      level: 'Third Level',
      cpu: '5',
      price: '0.056'
    }, {
      id: 4,
      category: 'Standard-2',
      flavor: 'Standard',
      level: 'Fourth Level',
      cpu: '4',
      price: '0.444'
    }, {
      id: 5,
      category: 'Micro-3',
      flavor: 'Micro',
      level: 'Second Level',
      cpu: '1',
      price: '0.056'
    }, {
      id: 6,
      category: 'Standard-1',
      flavor: 'Standard',
      level: 'Third Level',
      cpu: '7',
      price: '0.444'
    }];

    checkboxOnChange = jest.genMockFunction();
    checkboxInitialize = jest.genMockFunction();

    table = TestUtils.renderIntoDocument(

    );
  });

  it('renders table component', () => {
    var headNum = TestUtils.scryRenderedDOMComponentsWithClass(table, 'table-header').length,
      rowsNum = TestUtils.scryRenderedDOMComponentsWithClass(table, 'row').length;

    expect(headNum).toEqual(1);
    expect(rowsNum).toEqual(data.length);
    expect(checkboxInitialize.mock.calls.length).toEqual(data.length);
  });

  it('clicks checkbox and return checked data', () => {
    var checkIndex = 0,
      clickNode = TestUtils.scryRenderedDOMComponentsWithTag(table, 'INPUT')[checkIndex + 1];

    TestUtils.Simulate.change(clickNode);

    expect(checkboxOnChange).toBeCalled();
    expect(checkboxOnChange.mock.calls[0][0]).toBe(false);
    expect(checkboxOnChange.mock.calls[0][1]).toEqual(data[checkIndex]);
  });

  it('sorts by desc id value', () => {
    var descById = TestUtils.scryRenderedDOMComponentsWithClass(table, 'arrow-down')[0];

    TestUtils.Simulate.click(descById);

    var idValue = TestUtils.scryRenderedDOMComponentsWithClass(table, 'row')[0].childNodes[1].innerHTML;

    expect(idValue).toEqual('6');
  });

});
<commit_msg>fix table testcase bug<commit_after>jest.autoMockOff();

import React from 'react';
import TestUtils from 'react-addons-test-utils';

const Table = require('../js/components/table.jsx').default;

describe('Test table component', () => {
  var column, data, checkboxOnChange, checkboxInitialize, table;
  beforeEach(() => {
    column = [{
      title: 'ID',
      key: 'id',
      width: '150px',
      dataIndex: 'id',
      sortBy: 'number',
      filter: [{
        name: 'id大于等于4',
        key: '1',
        filter: function(item) {
          if (item.id >= 4) {
            return true;
          }
        }
      }, {
        name: 'id小于4',
        key: '2',
        filter: function(item) {
          if (item.id < 4) {
            return true;
          }
        }
      }]
    }, {
      title: 'Category',
      key: 'category',
      width: '120px',
      dataIndex: 'category',
      sortBy: 'string'
    }, {
      title: 'Flavor',
      key: 'flavor',
      width: '70px',
      dataIndex: 'flavor',
      sortBy: 'string'
    }, {
      title: 'Level',
      key: 'level',
      dataIndex: 'level',
      filter: [{
        name: 'level 1',
        key: '1',
        filter: function(item) {
          return item.level.localeCompare('First Level') === 0 ? true : false;
        }
      }, {
        name: 'level 2',
        key: '2',
        filter: function(item) {
          return item.level.localeCompare('Second Level') === 0 ? true : false;
        }
      }, {
        name: 'level 3',
        key: '3',
        filter: function(item) {
          return item.level.localeCompare('Third Level') === 0 ? true : false;
        }
      }, {
        name: 'level 4',
        key: '4',
        filter: function(item) {
          return item.level.localeCompare('Fourth Level') === 0 ? true : false;
        }
      }],
      sortBy: function(item1, item2) {
        var weight = ['First Level', 'Second Level', 'Third Level', 'Fourth Level'];
        if (weight.indexOf(item1.level) > weight.indexOf(item2.level)) {
          return 1;
        } else if (weight.indexOf(item1.level) < weight.indexOf(item2.level)) {
          return -1;
        } else {
          return 0;
        }
      }
    }, {
      title: 'CPU',
      key: 'cpu',
      dataIndex: 'cpu',
      sortBy: 'number',
      width: '50px'
    }, {
      title: 'Price',
      key: 'price',
      dataIndex: 'price',
      sortBy: 'number'
    }, {
      title: 'Double Price',
      key: 'double_price',
      sortBy: function(item1, item2) {
        if (item1.price * 2 > item2.price * 2) {
          return 1;
        } else if (item1.price * 2 < item2.price * 2) {
          return -1;
        } else {
          return 0;
        }
      },
      render: function(col, item, index) {
        return
{item.price * 2}
;
      }
    }, {
      title: 'Data Print',
      key: 'data_print',
      printData: function(col, item, e) {
        console.log('event:', e, 'GET COLUMN:', col, ' DATA:', item);
      },
      render: function(col, item, index) {
        if (item.id > 4) {
          return
Printing Disabled
;
        } else {
          return
{'Print ID ' + item.id}
;
        }
      }
    }];

    data = [{
      id: 1,
      category: 'Micro-1',
      flavor: 'Micro',
      level: 'First Level',
      cpu: '1',
      price: '0.056'
    }, {
      id: 2,
      category: 'Standard-3',
      flavor: 'Standard',
      level: 'Second Level',
      cpu: '3',
      price: '0.444'
    }, {
      id: 3,
      category: 'Micro-2',
      flavor: 'Micro',
      level: 'Third Level',
      cpu: '5',
      price: '0.056'
    }, {
      id: 4,
      category: 'Standard-2',
      flavor: 'Standard',
      level: 'Fourth Level',
      cpu: '4',
      price: '0.444'
    }, {
      id: 5,
      category: 'Micro-3',
      flavor: 'Micro',
      level: 'Second Level',
      cpu: '1',
      price: '0.056'
    }, {
      id: 6,
      category: 'Standard-1',
      flavor: 'Standard',
      level: 'Third Level',
      cpu: '7',
      price: '0.444'
    }];

    checkboxOnChange = jest.genMockFunction();
    checkboxInitialize = jest.genMockFunction();

    table = TestUtils.renderIntoDocument(

    );
  });

  it('renders table component', () => {
    var headNum = TestUtils.scryRenderedDOMComponentsWithClass(table, 'table-header').length,
      rowsNum = TestUtils.scryRenderedDOMComponentsWithClass(table, 'row').length;

    expect(headNum).toEqual(1);
    expect(rowsNum).toEqual(data.length);
    expect(checkboxInitialize.mock.calls.length).toEqual(data.length);
  });

  it('clicks checkbox and return checked data', () => {
    var checkIndex = 0,
      clickNode = TestUtils.scryRenderedDOMComponentsWithTag(table, 'INPUT')[checkIndex + 1];

    TestUtils.Simulate.change(clickNode);

    expect(checkboxOnChange).toBeCalled();
    expect(checkboxOnChange.mock.calls[0][0]).toBe(false);
    expect(checkboxOnChange.mock.calls[0][1]).toEqual(data[checkIndex]);
  });

  it('sorts by desc id value', () => {
    var descById = TestUtils.scryRenderedDOMComponentsWithClass(table, 'arrow-down')[0];

    TestUtils.Simulate.click(descById);

    var idValue = TestUtils.scryRenderedDOMComponentsWithClass(table, 'row')[0].childNodes[1].innerHTML;

    expect(idValue).toEqual('6');
  });

});
<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Chris Danford
Licensed under the MIT license.
*/

var fs = require('fs'),
  path = require('path'),
  crypto = require('crypto');

module.exports = function(grunt) {
  grunt.registerMultiTask('ver', 'Add hashes to file names and update references to renamed files', function() {
    grunt.helper('ver', this.data.phases, this.data.version, this.data.forceVersion);
  });

  // Expose as a helper for possible consumption by other tasks.
  grunt.registerHelper('ver', function(phases, versionFilePath, forceVersion) {
    grunt.verbose.or.writeln('Run with --verbose for details.');
    var versions = {},  // map from original file name to version info
      simpleVersions = {};

    phases.forEach(function(phase) {
      var files = phase.files,
        references = phase.references,
        numFilesRenamed = 0;

      grunt.log.writeln('Versioning files.').writeflags(files);
      grunt.file.expandFiles(files).sort().forEach(function(f) {
        var version = forceVersion || grunt.helper('hash', f).slice(0, 8),
          basename = path.basename(f),
          parts = basename.split('.'),
          renamedBasename,
          renamedPath;

        // inject the version just before the file extension
        parts.splice(parts.length-1, 0, version);

        renamedBasename = parts.join('.');
        renamedPath = path.join(path.dirname(f), renamedBasename);

        fs.renameSync(f, renamedPath);
        grunt.verbose.write(f + ' ').ok(renamedBasename);

        versions[f] = {
          basename: basename,
          version: version,
          renamedBasename: renamedBasename,
          renamedPath: renamedPath,
        };
        simpleVersions[f] = renamedPath;
        numFilesRenamed++;
      });
      grunt.log.write('Renamed ' + numFilesRenamed + ' files ').ok();

      if (references) {
        var totalReferences = 0;
        var totalReferencingFiles = 0;
        grunt.log.writeln('Replacing references.').writeflags(references);
        grunt.file.expandFiles(references).sort().forEach(function(f) {
          var content = grunt.file.read(f).toString(),
            replacedToCount = {},
            replacedKeys;

          Object.keys(versions).forEach(function(key) {
            var to = versions[key],
              regex = new RegExp('\\b' + to.basename + '\\b', 'g');

            content = content.replace(regex, function(match) {
              if (match in replacedToCount) {
                replacedToCount[match]++;
              } else {
                replacedToCount[match] = 1;
              }
              return to.renamedBasename;
            });
          });

          replacedKeys = Object.keys(replacedToCount);
          if (replacedKeys.length > 0) {
            grunt.file.write(f, content);
            grunt.verbose.write(f + ' ').ok('replaced: ' + replacedKeys.join(', '));
            totalReferences++;
          }
          totalReferencingFiles++;
        });
        grunt.log.write('Replaced ' + totalReferences + ' in ' + totalReferencingFiles + ' files ').ok();
      }
    });

    if (versionFilePath) {
      grunt.log.writeln('Writing version file.');
      grunt.file.write(versionFilePath, JSON.stringify(simpleVersions, null, ' '));
      grunt.log.write(versionFilePath + ' ').ok();
    }
  });

  // This helper is a basic wrapper around crypto.createHash.
  grunt.registerHelper('hash', function(filePath, algorithm, encoding) {
    algorithm = algorithm || 'md5';
    encoding = encoding || 'hex';
    var hash = crypto.createHash(algorithm);

    grunt.log.verbose.writeln('Hashing ' + filePath + '.');
    hash.update(grunt.file.read(filePath));
    return hash.digest(encoding);
  });

};
<commit_msg>Add Grunt 0.4 support<commit_after>/*
Copyright (c) 2012 Chris Danford
Licensed under the MIT license.
*/

var fs = require('fs'),
  path = require('path'),
  crypto = require('crypto');

module.exports = function(grunt) {
  grunt.registerMultiTask('ver', 'Add hashes to file names and update references to renamed files', function() {
    ver(this.data.phases, this.data.version, this.data.forceVersion);
  });

  // Expose as a helper for possible consumption by other tasks.
  function ver(phases, versionFilePath, forceVersion) {
    grunt.verbose.or.writeln('Run with --verbose for details.');
    var versions = {},  // map from original file name to version info
      simpleVersions = {};

    phases.forEach(function(phase) {
      var files = phase.files,
        references = phase.references,
        numFilesRenamed = 0;

      grunt.log.writeln('Versioning files.').writeflags(files);
      grunt.file.expand({filter: 'isFile'}, files).sort().forEach(function(f) {
        var version = forceVersion || hash(f).slice(0, 8),
          basename = path.basename(f),
          parts = basename.split('.'),
          renamedBasename,
          renamedPath;

        // inject the version just before the file extension
        parts.splice(parts.length-1, 0, version);

        renamedBasename = parts.join('.');
        renamedPath = path.join(path.dirname(f), renamedBasename);

        fs.renameSync(f, renamedPath);
        grunt.verbose.write(f + ' ').ok(renamedBasename);

        versions[f] = {
          basename: basename,
          version: version,
          renamedBasename: renamedBasename,
          renamedPath: renamedPath,
        };
        simpleVersions[f] = renamedPath;
        numFilesRenamed++;
      });
      grunt.log.write('Renamed ' + numFilesRenamed + ' files ').ok();

      if (references) {
        var totalReferences = 0;
        var totalReferencingFiles = 0;
        grunt.log.writeln('Replacing references.').writeflags(references);
        grunt.file.expand({filter: 'isFile'}, references).sort().forEach(function(f) {
          var content = grunt.file.read(f).toString(),
            replacedToCount = {},
            replacedKeys;

          Object.keys(versions).forEach(function(key) {
            var to = versions[key],
              regex = new RegExp('\\b' + to.basename + '\\b', 'g');

            content = content.replace(regex, function(match) {
              if (match in replacedToCount) {
                replacedToCount[match]++;
              } else {
                replacedToCount[match] = 1;
              }
              return to.renamedBasename;
            });
          });

          replacedKeys = Object.keys(replacedToCount);
          if (replacedKeys.length > 0) {
            grunt.file.write(f, content);
            grunt.verbose.write(f + ' ').ok('replaced: ' + replacedKeys.join(', '));
            totalReferences++;
          }
          totalReferencingFiles++;
        });
        grunt.log.write('Replaced ' + totalReferences + ' in ' + totalReferencingFiles + ' files ').ok();
      }
    });

    if (versionFilePath) {
      grunt.log.writeln('Writing version file.');
      grunt.file.write(versionFilePath, JSON.stringify(simpleVersions, null, ' '));
      grunt.log.write(versionFilePath + ' ').ok();
    }
  }

  // This helper is a basic wrapper around crypto.createHash.
  function hash(filePath, algorithm, encoding) {
    algorithm = algorithm || 'md5';
    encoding = encoding || 'hex';
    var hash = crypto.createHash(algorithm);

    grunt.log.verbose.writeln('Hashing ' + filePath + '.');
    hash.update(grunt.file.read(filePath));
    return hash.digest(encoding);
  }

};
<|endoftext|>