<commit_before>/**
 * a utility class that is used to update widgets based on a behaviour each time the the behaviour changes the callback
 * will be fired
 *
 * you may access the behaviour attached to the helper inside the callback
 *
 */
goog.provide('recoil.ui.WidgetHelper');

goog.require('recoil.frp.Behaviour');
goog.require('recoil.frp.Frp');
goog.require('recoil.frp.VisibleObserver');
goog.require('recoil.ui.WidgetScope');

/**
 * @template T
 * @param {!recoil.ui.WidgetScope} widgetScope gui scope
 * @param {Node} container when this is no longer visible updates will longer fire and memory will be cleaned up
 * @param {T} obj the this pointer callback will be called with
 * @param {function(this:T, !recoil.ui.WidgetHelper,...)} callback
 * @constructor
 */

recoil.ui.WidgetHelper = function(widgetScope, container, obj, callback) {
    this.observer_ = widgetScope.getObserver();
    this.frp_ = widgetScope.getFrp();
    this.component_ = container;
    var me = this;
    this.listenFunc_ = function(visible) {
        if (visible != me.isAttached_) {
            me.isAttached_ = visible;
            if (visible) {
                me.frp_.attach(/** @type {!recoil.frp.Behaviour} */ (me.attachedBehaviour_));
            } else {
                me.frp_.detach(/** @type {!recoil.frp.Behaviour} */ (me.attachedBehaviour_));
            }
        }
    };

    /**
     * @private
     * @final
     */
    this.callback_ = function() {
        if (me.component_ !== null) {
            recoil.util.invokeOneParamAndArray(obj, callback, me, me.behaviours_);
        }
    };
    /**
     * @type {!Array<!recoil.frp.Behaviour<T>>}
     * @private
     */
    this.behaviours_ = [];
    /**
     * @type {recoil.frp.Behaviour}
     * @private
     */
    this.attachedBehaviour_ = null;
    /**
     * @private
     * @type {boolean}
     */
    this.isAttached_ = false;
};

/**
 * @param {Node} container new container to watch the old one will no longer be observed
 */

recoil.ui.WidgetHelper.prototype.setComponent = function(container) {
    if (this.component_ === container) {
        return;
    }

    if (this.component_) {
        this.observer_.unlisten(this.component_, this.listenFunc_);
    }
    this.component_ = container;
    if (this.component_) {
        this.observer_.listen(this.component_, this.listenFunc_);
    }

};

/**
 * remove all the cheldren
 */
recoil.ui.WidgetHelper.prototype.clearContainer = function() {
    if (this.component_ !== null) {
        goog.dom.removeChildren(this.component_);
    }
};

/**
 * @return {!boolean} is the value good
 */
recoil.ui.WidgetHelper.prototype.isGood = function() {
    for (var key = 0; key < this.behaviours_.length; key++) {
        if (!this.behaviours_[key].metaGet().good()) {
            return false;
        }
    }

    return true;
};

/**
 * force the change to fire
 */
recoil.ui.WidgetHelper.prototype.forceUpdate = function() {
    if (this.behaviours_.length !== 0) {
        recoil.util.invokeOneParamAndArray(null, recoil.frp.Frp.access, this.callback_, this.behaviours_);
    }
};

/**
 * @param {...recoil.frp.Behaviour} var_behaviour
 *
 * note the node we are watch must be in the dom by now, the reason for this is if it isn't and is never added we will
 * have a leak observer maintains a list that can never be cleared also once it item is removed form the DOM and node
 * re-added within the same execution thread it will be considered disposed.
 *
 * this is because there are no weak references in javascript
 */

recoil.ui.WidgetHelper.prototype.attach = function(var_behaviour) {

    var newBehaviours = [];
    var same = arguments.length === this.behaviours_.length;
    for (var i = 0; i < arguments.length; i++) {
        newBehaviours.push(arguments[i]);
        same = same && arguments[i] === this.behaviours_[i];
    }
    if (same) {
        return;
    }

    var hadBehaviour = this.behaviours_.length !== 0;
    if (hadBehaviour) {
        if (this.isAttached_) {
            this.frp_.detach(/** @type {!recoil.frp.Behaviour} */(this.attachedBehaviour_));
        }
    }

    var me = this;
    this.behaviours_ = newBehaviours;
    this.attachedBehaviour_ = recoil.util.invokeOneParamAndArray(this.frp_, this.frp_.metaLiftB, this.callback_, this.behaviours_);

    if (hadBehaviour) {
        if (this.isAttached_) {
            this.frp_.attach(/** @type {!recoil.frp.Behaviour} */(this.attachedBehaviour_));
        }
    } else {
        this.isAttached_ = false;
        if (this.component_ !== null) {
            this.observer_.listen(this.component_, this.listenFunc_);
        }
    }
};

/**
 * gets the value of the first attached behaviour
 * @return {?}
 */
recoil.ui.WidgetHelper.prototype.value = function() {
    if (this.behaviours_.length > 0) {
        return this.behaviours_[0].get();
    }
    return null;
};
<commit_msg>add visible helper<commit_after>goog.provide('recoil.ui.VisibleHelper');
/**
 * a utility class that is used to update widgets based on a behaviour each time the the behaviour changes the callback
 * will be fired
 *
 * you may access the behaviour attached to the helper inside the callback
 *
 */
goog.provide('recoil.ui.WidgetHelper');

goog.require('recoil.frp.Behaviour');
goog.require('recoil.frp.Frp');
goog.require('recoil.frp.VisibleObserver');
goog.require('recoil.ui.WidgetScope');

/**
 * @template T
 * @param {!recoil.ui.WidgetScope} widgetScope gui scope
 * @param {Element} container when this is no longer visible updates will longer fire and memory will be cleaned up
 * @param {T} obj the this pointer callback will be called with
 * @param {function(this:T, !recoil.ui.WidgetHelper,...)} callback
 * @constructor
 */

recoil.ui.WidgetHelper = function(widgetScope, container, obj, callback) {
    this.observer_ = widgetScope.getObserver();
    this.frp_ = widgetScope.getFrp();
    this.component_ = container;
    var me = this;
    this.listenFunc_ = function(visible) {
        if (visible != me.isAttached_) {
            me.isAttached_ = visible;
            if (visible) {
                me.frp_.attach(/** @type {!recoil.frp.Behaviour} */ (me.attachedBehaviour_));
            } else {
                me.frp_.detach(/** @type {!recoil.frp.Behaviour} */ (me.attachedBehaviour_));
            }
        }
    };

    /**
     * @private
     * @final
     */
    this.callback_ = function() {
        if (me.component_ !== null) {
            recoil.util.invokeOneParamAndArray(obj, callback, me, me.behaviours_);
        }
    };
    /**
     * @type {!Array<!recoil.frp.Behaviour<T>>}
     * @private
     */
    this.behaviours_ = [];
    /**
     * @type {recoil.frp.Behaviour}
     * @private
     */
    this.attachedBehaviour_ = null;
    /**
     * @private
     * @type {boolean}
     */
    this.isAttached_ = false;
};

/**
 * @param {Node} container new container to watch the old one will no longer be observed
 */

recoil.ui.WidgetHelper.prototype.setComponent = function(container) {
    if (this.component_ === container) {
        return;
    }

    if (this.component_) {
        this.observer_.unlisten(this.component_, this.listenFunc_);
    }
    this.component_ = container;
    if (this.component_) {
        this.observer_.listen(this.component_, this.listenFunc_);
    }

};

/**
 * remove all the cheldren
 */
recoil.ui.WidgetHelper.prototype.clearContainer = function() {
    if (this.component_ !== null) {
        goog.dom.removeChildren(this.component_);
    }
};

/**
 * @return {!boolean} is the value good
 */
recoil.ui.WidgetHelper.prototype.isGood = function() {
    for (var key = 0; key < this.behaviours_.length; key++) {
        if (!this.behaviours_[key].metaGet().good()) {
            return false;
        }
    }

    return true;
};

/**
 * force the change to fire
 */
recoil.ui.WidgetHelper.prototype.forceUpdate = function() {
    if (this.behaviours_.length !== 0) {
        recoil.util.invokeOneParamAndArray(null, recoil.frp.Frp.access, this.callback_, this.behaviours_);
    }
};

/**
 * @param {...recoil.frp.Behaviour} var_behaviour
 *
 * note the node we are watch must be in the dom by now, the reason for this is if it isn't and is never added we will
 * have a leak observer maintains a list that can never be cleared also once it item is removed form the DOM and node
 * re-added within the same execution thread it will be considered disposed.
 *
 * this is because there are no weak references in javascript
 */

recoil.ui.WidgetHelper.prototype.attach = function(var_behaviour) {

    var newBehaviours = [];
    var same = arguments.length === this.behaviours_.length;
    for (var i = 0; i < arguments.length; i++) {
        newBehaviours.push(arguments[i]);
        same = same && arguments[i] === this.behaviours_[i];
    }
    if (same) {
        return;
    }

    var hadBehaviour = this.behaviours_.length !== 0;
    if (hadBehaviour) {
        if (this.isAttached_) {
            this.frp_.detach(/** @type {!recoil.frp.Behaviour} */(this.attachedBehaviour_));
        }
    }

    var me = this;
    this.behaviours_ = newBehaviours;
    this.attachedBehaviour_ = recoil.util.invokeOneParamAndArray(this.frp_, this.frp_.metaLiftB, this.callback_, this.behaviours_);

    if (hadBehaviour) {
        if (this.isAttached_) {
            this.frp_.attach(/** @type {!recoil.frp.Behaviour} */(this.attachedBehaviour_));
        }
    } else {
        this.isAttached_ = false;
        if (this.component_ !== null) {
            this.observer_.listen(this.component_, this.listenFunc_);
        }
    }
};

/**
 * gets the value of the first attached behaviour
 * @return {?}
 */
recoil.ui.WidgetHelper.prototype.value = function() {
    if (this.behaviours_.length > 0) {
        return this.behaviours_[0].get();
    }
    return null;
};

/**
 * Note:
 *   the reason we need a container is because we attach to it, if we where to make
 *   this hidden we would no longer be listening to events for it and that would mean
 *   we could not make it visible again
 *
 * @param {!recoil.ui.WidgetScope} widgetScope gui scope
 * @param {!Element} container an item that is always visible doesn't really need to contain the items
 * @param {IArrayLike<!Element>} showElements these elements will be show when attach behaviour is true, otherwize hidden
 * @param {IArrayLike<!Element>=} opt_hideElements these elements will be hidden when attach behaviour is true, otherwize shown
 * @param {IArrayLike<!Element>=} opt_notGoodElements these elements will be shown when the behaviour is not good
 * @constructor
 */
recoil.ui.VisibleHelper = function(widgetScope, container, showElements, opt_hideElements, opt_notGoodElements) {
    this.show_ = showElements;
    this.hide_ = opt_hideElements || [];
    this.notGood_ = opt_notGoodElements || [];
    this.scope_ = widgetScope;

    this.helper_ = new recoil.ui.WidgetHelper(
        widgetScope, container, this,
        function(helper) {
            var me = this;
            if (helper.isGood()) {
            }
            else {
                this.show_.concat(this.hide_, this.notGood_).forEach(
                    function(el) {
                        var show = me.notGood_.indexOf(el) !== -1;
                        el.style.display = show ? '' : 'none';
                    }
                );

            }
        });
};
/**
 * @param {!recoil.frp.Behaviour<boolean>}  visible hide/show components
 */
recoil.ui.VisibleHelper.prototype.attach = function(visible) {
    this.visibleB_ = visible;
    this.helper_.attach(this.visibleB_);
};
<|endoftext|>


<commit_before>var MAGIC_REGEX = (function() {
  return new RegExp(require('fs')
                    .readFileSync(__dirname+'/magic-regex.txt', 'utf8')
                    .split('\n')
                    .map(function(line) {
                      return line.split('#')[0].trim()
                    })
                    .join('')
                   ,
                    'gi'
                   )
})()

function replaceURLs(text, fn) {
  if (typeof fn === 'string') {
    if (fn === 'html')
      fn = function(match, url) {
        url = url.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
        return ''+match+''
      }
    else if (fn === 'latex')
      fn = function(match, url) {
        url = url.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
        return '\\href{'+url+'}{'+match+'}'
      }
    else
      throw new Error('unknown replacer type')
  }
  return text.replace(MAGIC_REGEX, function(match) {
    var matchURL = match
    if (!/^[a-zA-Z]{1,6}:/.test(matchURL)) matchURL = 'http://' + matchURL
    return fn(match, matchURL)
  })
}

module.exports = replaceURLs
<commit_msg>eww, what the heck did I do back then? make my code do this stuff in a somewhat saner way<commit_after>var MAGIC_REGEX = (function() {
  return new RegExp(require('fs')
                    .readFileSync(__dirname+'/magic-regex.txt', 'utf8')
                    .split('\n')
                    .map(function(line) {
                      return line.split('#')[0].trim()
                    })
                    .join('')
                   ,
                    'gi'
                   )
})()

function replaceURLs(text, fn) {
  if (typeof fn === 'string') {
    if (fn === 'html')
      fn = function(match, url) {
        url = url.replace(/"/g, '"')
        return ''+match+''
      }
    else if (fn === 'latex')
      fn = function(match, url) {
        url = url.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
        return '\\href{'+url+'}{'+match+'}'
      }
    else
      throw new Error('unknown replacer type')
  }
  return text.replace(MAGIC_REGEX, function(match) {
    var matchURL = match
    if (!/^[a-zA-Z]{1,6}:/.test(matchURL)) matchURL = 'http://' + matchURL
    return fn(match, matchURL)
  })
}

module.exports = replaceURLs
<|endoftext|>


<commit_before>'use strict';

/* jshint undef:false, expr:true */

var chai = require('chai');
var expect = chai.expect;
var MemoryService = require('../lib/memory');
var Proto = require('uberproto');
var service;

describe('Memory Service', function () {
  beforeEach(function(done){
    service = Proto.create.call(MemoryService);
    service.create({
      id: 1,
      name: 'Test 1'
    }, function() {
      done();
    });
  });

  afterEach(function(done){
    service.remove(1, function(){
      done();
    });
  });

  describe('get', function () {

    it('should return an instance that exists', function (done){
      service.get(1, function(error, data) {
        expect(data.id).to.equal(1);
        expect(data.name).to.equal('Test 1');
        done();
      });
    });

    it('should return an error when requested instance doesn\'t exist', function (done){
      service.get(2, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });

  });

  describe('create', function () {

    it('should create a new instance', function (done) {
      service.create({
        id: 2,
        name: 'Test 2'
      }, function(error, data) {
        expect(data.id).to.equal(2);
        expect(data.name).to.equal('Test 2');
        done();
      });
    });

    it('should return an error when it can\'t create', function (done) {
      service.create({
        id: 1,
        name: 'Test 2'
      }, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });
  });

  describe('update', function () {

    it('should update an existing instance', function (done) {
      service.update(1, {
        name: 'Test 1 Updated'
      }, {}, function(error, data) {
        expect(data.id).to.equal(1);
        expect(data.name).to.equal('Test 1 Updated');
        done();
      });
    });

    it('should return an error on db when instance to update doesn\'t exist', function (done) {
      service.update(3, {
        name: 'Test 2'
      }, {}, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });

  });

  describe('remove', function () {

    it('should delete an existing instance', function (done) {
      service.remove(1, function(error, data) {
        expect(data.id).to.equal(1);
        expect(data.name).to.equal('Test 1');
        done();
      });
    });

    it('should return an error on db when instance to delete doesn\'t exist', function (done) {
      service.remove(3, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });

  });

  describe('find', function () {

    beforeEach(function(done){
      service.create({
        id: 2,
        name: 'Bob'
      }, function(){
        service.create({
          id: 3,
          name: 'Alice'
        }, function(){
          done();
        });
      });
    });

    afterEach(function(done){
      service.remove(2, function(){
        service.remove(3, function(){
          done();
        });
      });
    });

    it('should return all items', function(done){
      var expected = [
        {
          id: 1,
          name: 'Test 1'
        },
        {
          id: 2,
          name: 'Bob'
        },
        {
          id: 3,
          name: 'Alice'
        }
      ];

      service.find({ query: {} }, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should return all items sorted in ascending order by sort value', function(done){
      var expected = [
        {
          id: 3,
          name: 'Alice'
        },
        {
          id: 2,
          name: 'Bob'
        },
        {
          id: 1,
          name: 'Test 1'
        }
      ];

      var query = {
        query: { sort: 'name' }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should return all items sorted in descending order by sort value', function(done){
      var expected = [
        {
          id: 1,
          name: 'Test 1'
        },
        {
          id: 2,
          name: 'Bob'
        },
        {
          id: 3,
          name: 'Alice'
        }
      ];

      var query = {
        query: { sort: 'name', order: true }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should return the number of items set by the limit', function(done){
      var expected = [
        {
          id: 1,
          name: 'Test 1'
        },
        {
          id: 2,
          name: 'Bob'
        }
      ];

      var query = {
        query: { limit: 2 }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should skip over the number of items set by skip', function(done){
      var expected = [
        {
          id: 3,
          name: 'Alice'
        }
      ];

      var query = {
        query: { skip: 2 }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

  });
});
<commit_msg>fixing tests<commit_after>'use strict';

/* jshint undef:false, expr:true */

var chai = require('chai');
var expect = chai.expect;
var service = require('../lib/memory')();

describe('Memory Service', function () {
  beforeEach(function(done){
    service.create({
      id: 1,
      name: 'Test 1'
    }, function() {
      done();
    });
  });

  afterEach(function(done){
    service.remove(1, function(){
      done();
    });
  });

  describe('get', function () {

    it('should return an instance that exists', function (done){
      service.get(1, function(error, data) {
        expect(data.id).to.equal(1);
        expect(data.name).to.equal('Test 1');
        done();
      });
    });

    it('should return an error when requested instance doesn\'t exist', function (done){
      service.get(2, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });

  });

  describe('create', function () {

    it('should create a new instance', function (done) {
      service.create({
        id: 2,
        name: 'Test 2'
      }, function(error, data) {
        expect(data.id).to.equal(2);
        expect(data.name).to.equal('Test 2');

        service.remove(2, function(){
          done();
        });
      });
    });

    it('should return an error when it can\'t create', function (done) {
      service.create({
        id: 1,
        name: 'Test 2'
      }, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });
  });

  describe('update', function () {

    it('should update an existing instance', function (done) {
      service.update(1, {
        name: 'Test 1 Updated'
      }, {}, function(error, data) {
        expect(data.id).to.equal(1);
        expect(data.name).to.equal('Test 1 Updated');
        done();
      });
    });

    it('should return an error on db when instance to update doesn\'t exist', function (done) {
      service.update(3, {
        name: 'Test 2'
      }, {}, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });

  });

  describe('remove', function () {

    it('should delete an existing instance', function (done) {
      service.remove(1, function(error, data) {
        expect(data.id).to.equal(1);
        expect(data.name).to.equal('Test 1');
        done();
      });
    });

    it('should return an error on db when instance to delete doesn\'t exist', function (done) {
      service.remove(3, function(error, data) {
        expect(error).to.not.be.null;
        expect(data).to.be.undefined;
        done();
      });
    });

  });

  describe('find', function () {

    beforeEach(function(done){
      service.create({
        id: 2,
        name: 'Bob'
      }, function(){
        service.create({
          id: 3,
          name: 'Alice'
        }, function(){
          done();
        });
      });
    });

    afterEach(function(done){
      service.remove(2, function(){
        service.remove(3, function(){
          done();
        });
      });
    });

    it('should return all items', function(done){
      var expected = [
        {
          id: 1,
          name: 'Test 1'
        },
        {
          id: 2,
          name: 'Bob'
        },
        {
          id: 3,
          name: 'Alice'
        }
      ];

      service.find({ query: {} }, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should return all items sorted in ascending order by sort value', function(done){
      var expected = [
        {
          id: 3,
          name: 'Alice'
        },
        {
          id: 2,
          name: 'Bob'
        },
        {
          id: 1,
          name: 'Test 1'
        }
      ];

      var query = {
        query: { sort: 'name' }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should return all items sorted in descending order by sort value', function(done){
      var expected = [
        {
          id: 1,
          name: 'Test 1'
        },
        {
          id: 2,
          name: 'Bob'
        },
        {
          id: 3,
          name: 'Alice'
        }
      ];

      var query = {
        query: { sort: 'name', order: true }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should return the number of items set by the limit', function(done){
      var expected = [
        {
          id: 1,
          name: 'Test 1'
        },
        {
          id: 2,
          name: 'Bob'
        }
      ];

      var query = {
        query: { limit: 2 }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

    it('should skip over the number of items set by skip', function(done){
      var expected = [
        {
          id: 3,
          name: 'Alice'
        }
      ];

      var query = {
        query: { skip: 2 }
      };

      service.find(query, function(err, items){
        expect(err).to.be.null;
        expect(items).to.deep.equal(expected);
        done();
      });
    });

  });
});
<|endoftext|>


<commit_before>/* @flow */

import clone from 'lodash.clone'
import isEqual from 'lodash.isequal'
import pick from 'lodash.pick'
import path from 'path'

import logger from './logger'
import { sameDate } from './timestamp'

const log = logger({
  prefix: 'Metadata',
  date: true
})

export type MetadataRemoteInfo = {
  _id: string,
  _rev: string
}

export type MetadataSidesInfo = {
  remote?: ?number,
  local?: ?number
}

// The files/dirs metadata, as stored in PouchDB
export type Metadata = {
  _id: string,
  _rev: string,
  // TODO: v3: Rename to md5sum to match remote
  checksum?: string,
  class?: string,
  creationDate: string,
  // TODO: v3: Use the same local *type fields as the remote ones
  docType: string,
  executable?: boolean,
  lastModification: string,
  mime?: string,
  path: string,
  remote: MetadataRemoteInfo,
  size?: string,
  tags: string[],
  sides: MetadataSidesInfo
}

export let buildId: (doc: Metadata) => void = (_) => {}

switch (process.platform) {
  case 'linux': case 'freebsd': case 'sunos':
    buildId = buildIdUnix
    break
  case 'darwin':
    buildId = buildIdHFS
    break
  case 'win32':
    // FIXME: Temporary hack to run the CLI on Windows
    // TODO: Proper implementation of buildId on Windows
    buildId = buildIdUnix
    break
  default:
    log.error(`Sorry, ${process.platform} is not supported!`)
    process.exit(1)
}

// Build an _id from the path for a case sensitive file system (Linux, BSD)
function buildIdUnix (doc: Metadata) {
  doc._id = doc.path
}

// Build an _id from the path for OSX (HFS+ file system):
// - case preservative, but not case sensitive
// - unicode NFD normalization (sort of)
//
// See https://nodejs.org/en/docs/guides/working-with-different-filesystems/
// for why toUpperCase is better than toLowerCase
//
// Note: String.prototype.normalize is not available on node 0.10 and does
// nothing when node is compiled without intl option.
function buildIdHFS (doc: Metadata) {
  let id = doc.path
  if (id.normalize) { id = id.normalize('NFD') }
  doc._id = id.toUpperCase()
}

// Return true if the document has not a valid path
// (ie a path inside the mount point)
export function invalidPath (doc: Metadata) {
  if (!doc.path) { return true }
  doc.path = path.normalize(doc.path)
  doc.path = doc.path.replace(/^\//, '')
  let parts = doc.path.split(path.sep)
  return (doc.path === '.') ||
          (doc.path === '') ||
          (parts.indexOf('..') >= 0)
}

export function ensureValidPath (doc: Metadata) {
  if (invalidPath(doc)) {
    log.warn(`Invalid path: ${JSON.stringify(doc, null, 2)}`)
    throw new Error('Invalid path')
  }
}

// Return true if the checksum is invalid
// If the checksum is missing, it is not invalid, just missing,
// so it returns false.
// MD5 has 16 bytes.
// Base64 encoding must include padding.
export function invalidChecksum (doc: Metadata) {
  if (doc.checksum == null) return false

  const buffer = Buffer.from(doc.checksum, 'base64')

  return buffer.byteLength !== 16 ||
    buffer.toString('base64') !== doc.checksum
}

export function ensureValidChecksum (doc: Metadata) {
  if (invalidChecksum(doc)) {
    log.warn(`Invalid checksum: ${JSON.stringify(doc, null, 2)}`)
    throw new Error('Invalid checksum')
  }
}

// Extract the revision number, or 0 it not found
export function extractRevNumber (infos: Metadata) {
  try {
    let rev = infos._rev.split('-')[0]
    return Number(rev)
  } catch (error) {
    return 0
  }
}

// Return true if the remote file is up-to-date for this document
export function isUpToDate (doc: Metadata) {
  let currentRev = doc.sides.remote || 0
  let lastRev = extractRevNumber(doc)
  return currentRev === lastRev
}

// Return true if the metadata of the two folders are the same
// The creationDate of the two folders are not compared, because the local
// filesystem can't give us a relevant information for that.
// For lastModification, we accept up to 3s of differences because we can't
// rely on file systems to be precise to the millisecond.
export function sameFolder (one: Metadata, two: Metadata) {
  if (!sameDate(one.lastModification, two.lastModification)) { return false }
  let fields = ['_id', 'docType', 'remote', 'tags']
  one = pick(one, fields)
  two = pick(two, fields)
  const same = isEqual(one, two)
  if (!same) log.diff(one, two)
  return same
}

// Return true if the metadata of the two files are the same
// The creationDate of the two files are not compared, because the local
// filesystem can't give us a relevant information for that.
// For lastModification, we accept up to 3s of differences because we can't
// rely on file systems to be precise to the millisecond.
export function sameFile (one: Metadata, two: Metadata) {
  if (!sameDate(one.lastModification, two.lastModification)) { return false }
  let fields = ['_id', 'docType', 'checksum', 'remote',
    'tags', 'size', 'class', 'mime']
  one = {...pick(one, fields), executable: !!one.executable}
  two = {...pick(two, fields), executable: !!two.executable}
  const same = isEqual(one, two)
  if (!same) log.diff(one, two)
  return same
}

// Return true if the two files have the same binary content
export function sameBinary (one: Metadata, two: Metadata) {
  if ((one.docType !== 'file') || (two.docType !== 'file')) {
    return false
  } else if ((one.checksum != null) && (one.checksum === two.checksum)) {
    return true
  } else if ((one.remote != null) && (two.remote != null)) {
    let oneId = one.remote._id
    let twoId = two.remote._id
    return (oneId != null) && (oneId === twoId)
  } else {
    return false
  }
}

// Mark the next rev for this side
//
// To track which side has made which modification, a revision number is
// associated to each side. When a side make a modification, we extract the
// revision from the previous state, increment it by one to have the next
// revision and associate this number to the side that makes the
// modification.
export function markSide (side: string, doc: Metadata, prev: ?Metadata): Metadata {
  let rev = 0
  if (prev) { rev = extractRevNumber(prev) }
  if (doc.sides == null) {
    const was = prev && prev.sides
    doc.sides = clone(was || {})
  }
  doc.sides[side] = ++rev
  return doc
}
<commit_msg>metadata: Add toBeTrashed property<commit_after>/* @flow */

import clone from 'lodash.clone'
import isEqual from 'lodash.isequal'
import pick from 'lodash.pick'
import path from 'path'

import logger from './logger'
import { sameDate } from './timestamp'

const log = logger({
  prefix: 'Metadata',
  date: true
})

export type MetadataRemoteInfo = {
  _id: string,
  _rev: string
}

export type MetadataSidesInfo = {
  remote?: ?number,
  local?: ?number
}

// The files/dirs metadata, as stored in PouchDB
export type Metadata = {
  _id: string,
  _rev: string,
  // TODO: v3: Rename to md5sum to match remote
  checksum?: string,
  class?: string,
  creationDate: string,
  // TODO: v3: Use the same local *type fields as the remote ones
  docType: string,
  executable?: boolean,
  lastModification: string,
  mime?: string,
  path: string,
  remote: MetadataRemoteInfo,
  size?: string,
  tags: string[],
  sides: MetadataSidesInfo,
  toBeTrashed?: true
}

export let buildId: (doc: Metadata) => void = (_) => {}

switch (process.platform) {
  case 'linux': case 'freebsd': case 'sunos':
    buildId = buildIdUnix
    break
  case 'darwin':
    buildId = buildIdHFS
    break
  case 'win32':
    // FIXME: Temporary hack to run the CLI on Windows
    // TODO: Proper implementation of buildId on Windows
    buildId = buildIdUnix
    break
  default:
    log.error(`Sorry, ${process.platform} is not supported!`)
    process.exit(1)
}

// Build an _id from the path for a case sensitive file system (Linux, BSD)
function buildIdUnix (doc: Metadata) {
  doc._id = doc.path
}

// Build an _id from the path for OSX (HFS+ file system):
// - case preservative, but not case sensitive
// - unicode NFD normalization (sort of)
//
// See https://nodejs.org/en/docs/guides/working-with-different-filesystems/
// for why toUpperCase is better than toLowerCase
//
// Note: String.prototype.normalize is not available on node 0.10 and does
// nothing when node is compiled without intl option.
function buildIdHFS (doc: Metadata) {
  let id = doc.path
  if (id.normalize) { id = id.normalize('NFD') }
  doc._id = id.toUpperCase()
}

// Return true if the document has not a valid path
// (ie a path inside the mount point)
export function invalidPath (doc: Metadata) {
  if (!doc.path) { return true }
  doc.path = path.normalize(doc.path)
  doc.path = doc.path.replace(/^\//, '')
  let parts = doc.path.split(path.sep)
  return (doc.path === '.') ||
          (doc.path === '') ||
          (parts.indexOf('..') >= 0)
}

export function ensureValidPath (doc: Metadata) {
  if (invalidPath(doc)) {
    log.warn(`Invalid path: ${JSON.stringify(doc, null, 2)}`)
    throw new Error('Invalid path')
  }
}

// Return true if the checksum is invalid
// If the checksum is missing, it is not invalid, just missing,
// so it returns false.
// MD5 has 16 bytes.
// Base64 encoding must include padding.
export function invalidChecksum (doc: Metadata) {
  if (doc.checksum == null) return false

  const buffer = Buffer.from(doc.checksum, 'base64')

  return buffer.byteLength !== 16 ||
    buffer.toString('base64') !== doc.checksum
}

export function ensureValidChecksum (doc: Metadata) {
  if (invalidChecksum(doc)) {
    log.warn(`Invalid checksum: ${JSON.stringify(doc, null, 2)}`)
    throw new Error('Invalid checksum')
  }
}

// Extract the revision number, or 0 it not found
export function extractRevNumber (infos: Metadata) {
  try {
    let rev = infos._rev.split('-')[0]
    return Number(rev)
  } catch (error) {
    return 0
  }
}

// Return true if the remote file is up-to-date for this document
export function isUpToDate (doc: Metadata) {
  let currentRev = doc.sides.remote || 0
  let lastRev = extractRevNumber(doc)
  return currentRev === lastRev
}

// Return true if the metadata of the two folders are the same
// The creationDate of the two folders are not compared, because the local
// filesystem can't give us a relevant information for that.
// For lastModification, we accept up to 3s of differences because we can't
// rely on file systems to be precise to the millisecond.
export function sameFolder (one: Metadata, two: Metadata) {
  if (!sameDate(one.lastModification, two.lastModification)) { return false }
  let fields = ['_id', 'docType', 'remote', 'tags']
  one = pick(one, fields)
  two = pick(two, fields)
  const same = isEqual(one, two)
  if (!same) log.diff(one, two)
  return same
}

// Return true if the metadata of the two files are the same
// The creationDate of the two files are not compared, because the local
// filesystem can't give us a relevant information for that.
// For lastModification, we accept up to 3s of differences because we can't
// rely on file systems to be precise to the millisecond.
export function sameFile (one: Metadata, two: Metadata) {
  if (!sameDate(one.lastModification, two.lastModification)) { return false }
  let fields = ['_id', 'docType', 'checksum', 'remote',
    'tags', 'size', 'class', 'mime']
  one = {...pick(one, fields), executable: !!one.executable}
  two = {...pick(two, fields), executable: !!two.executable}
  const same = isEqual(one, two)
  if (!same) log.diff(one, two)
  return same
}

// Return true if the two files have the same binary content
export function sameBinary (one: Metadata, two: Metadata) {
  if ((one.docType !== 'file') || (two.docType !== 'file')) {
    return false
  } else if ((one.checksum != null) && (one.checksum === two.checksum)) {
    return true
  } else if ((one.remote != null) && (two.remote != null)) {
    let oneId = one.remote._id
    let twoId = two.remote._id
    return (oneId != null) && (oneId === twoId)
  } else {
    return false
  }
}

// Mark the next rev for this side
//
// To track which side has made which modification, a revision number is
// associated to each side. When a side make a modification, we extract the
// revision from the previous state, increment it by one to have the next
// revision and associate this number to the side that makes the
// modification.
export function markSide (side: string, doc: Metadata, prev: ?Metadata): Metadata {
  let rev = 0
  if (prev) { rev = extractRevNumber(prev) }
  if (doc.sides == null) {
    const was = prev && prev.sides
    doc.sides = clone(was || {})
  }
  doc.sides[side] = ++rev
  return doc
}
<|endoftext|>


<commit_before>'use strict';

class Stack {

  constructor() {
    const stack = [];
  }

  push(value) {
    this.stack.push(value);
  }

  pop() {
    if (stack.length === 0) {
      console.error('The stack is empty');
    }
    else return this.stack.remove(0);
  }

  peek() {
    if (this.stack.length === 0) {
      console.error('The stack is empty');
    }
    else return this.stack[0];
  }

  isEmpty() {
    return this.stack.length === 0;
  }

}

module.exports = Stack;
<commit_msg>!... instead of ===0<commit_after>'use strict';

class Stack {

  constructor() {
    const stack = [];
  }

  push(value) {
    this.stack.push(value);
  }

  pop() {
    if (!stack.length) {
      console.error('The stack is empty');
    }
    else return this.stack.remove(0);
  }

  peek() {
    if (!this.stack.length) {
      console.error('The stack is empty');
    }
    else return this.stack[0];
  }

  isEmpty() {
    return this.stack.length === 0;
  }

}

module.exports = Stack;
<|endoftext|>


<commit_before>    /**
 * Created by OscarEvertsson on 01/06/15.
 */
$(document).ready(function(){
    var KEYCODE_ESC = 27;

    //If someone presses escape closeModalPanel.
    $(document).on('keyup',function(e){
        if (e.keyCode === KEYCODE_ESC) {
            closeModalPanel();
        }
    });

    //Update
    window.showCalendarModalPanel = function(calendarEvent){
        $('#cover-screen-container').fadeIn(); //Fades in the background cover
        $('.calendar-modal-panel').fadeIn(); //Fades in the window
        $('#calendar-modal-panel-title').text(calendarEvent.title); //Sets the title of the event

        //Sets the location if there is one.
        if (typeof calendarEvent.location === "undefined") {
            $('#where-when-how-list').find('#where').text("Var? " + "...NollKIT har inte fyllt i något");
        } else {
            $('#where-when-how-list').find('#where').text("Var? " + calendarEvent.location);
        }

        //Sets the description if there is one.
        if (typeof calendarEvent.description === "undefined") {
            $('#where-when-how-list').find('#what').text("Vad? " + "...NollKIT har inte fyllt i något");
        } else {
            $('#where-when-how-list').find('#what').text("Vad? " + calendarEvent.description);
        }

        //Sets the time for the event.
        $('#where-when-how-list').find('#when').text(
            "När? " + calendarEvent.start.format("h:mm") + " - " + calendarEvent.end.format("h:mm"));

        //Sets the url
        $('#where-when-how-list').find('#event-url').attr('href',calendarEvent.url);
        changeModalPanelAccordingToSize();
    };

    //If for instance you want to change the model panel size to 40% width and 60% height call setCalendarModalPanelSize(40,60)
    setCalendarModalPanelSize = function(width,height){
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        //Changes the width and the height of the modal panel to the given percent.
        var widthInPercent = (windowWidth * width)/windowWidth;
        var heightInPercent = (windowHeight * height)/windowHeight;

        var howMuchFromLeft = (100 - widthInPercent)/2;
        var howMuchFromTop = (100 - heightInPercent)/2;

        //Sets the calculated values and ads the % to it
        $('.calendar-modal-panel').css({'width':widthInPercent + '%','height':heightInPercent + '%',
        'top':howMuchFromTop + '%','left':howMuchFromLeft + '%'});
    }

    //Closes the modal panel and removes the background dimmer.
    var closeModalPanel = function(){
        $('#cover-screen-container').fadeOut();
        $('.calendar-modal-panel').fadeOut();
    }

    //Close modal panel
    $('#calendar-close-modal-panel').on("click",function(){
        closeModalPanel();
    });

    var changeModalPanelAccordingToSize = function(){
        if ($(window).width() <= 660) {
            setCalendarModalPanelSize(95,70);
        } else if ($(window).width() <= 960) {
            setCalendarModalPanelSize(60,40);
        } else {
            setCalendarModalPanelSize(40,60);
        }
    }

    $(window).resize(function(){
        changeModalPanelAccordingToSize();
    });

    //On startup
    changeModalPanelAccordingToSize();

});<commit_msg>Fixed time format for the modal panel.<commit_after>    /**
 * Created by OscarEvertsson on 01/06/15.
 */
$(document).ready(function(){
    var KEYCODE_ESC = 27;

    //If someone presses escape closeModalPanel.
    $(document).on('keyup',function(e){
        if (e.keyCode === KEYCODE_ESC) {
            closeModalPanel();
        }
    });

    //Update
    window.showCalendarModalPanel = function(calendarEvent){
        $('#cover-screen-container').fadeIn(); //Fades in the background cover
        $('.calendar-modal-panel').fadeIn(); //Fades in the window
        $('#calendar-modal-panel-title').text(calendarEvent.title); //Sets the title of the event

        //Sets the location if there is one.
        if (typeof calendarEvent.location === "undefined") {
            $('#where-when-how-list').find('#where').text("Var? " + "...NollKIT har inte fyllt i något");
        } else {
            $('#where-when-how-list').find('#where').text("Var? " + calendarEvent.location);
        }

        //Sets the description if there is one.
        if (typeof calendarEvent.description === "undefined") {
            $('#where-when-how-list').find('#what').text("Vad? " + "...NollKIT har inte fyllt i något");
        } else {
            $('#where-when-how-list').find('#what').text("Vad? " + calendarEvent.description);
        }

        //Sets the time for the event.
        $('#where-when-how-list').find('#when').text(
            "När? " + calendarEvent.start.format("H:mm") + " - " + calendarEvent.end.format("Hit:mm"));

        //Sets the url
        $('#where-when-how-list').find('#event-url').attr('href',calendarEvent.url);
        changeModalPanelAccordingToSize();
    };

    //If for instance you want to change the model panel size to 40% width and 60% height call setCalendarModalPanelSize(40,60)
    setCalendarModalPanelSize = function(width,height){
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        //Changes the width and the height of the modal panel to the given percent.
        var widthInPercent = (windowWidth * width)/windowWidth;
        var heightInPercent = (windowHeight * height)/windowHeight;

        var howMuchFromLeft = (100 - widthInPercent)/2;
        var howMuchFromTop = (100 - heightInPercent)/2;

        //Sets the calculated values and ads the % to it
        $('.calendar-modal-panel').css({'width':widthInPercent + '%','height':heightInPercent + '%',
        'top':howMuchFromTop + '%','left':howMuchFromLeft + '%'});
    }

    //Closes the modal panel and removes the background dimmer.
    var closeModalPanel = function(){
        $('#cover-screen-container').fadeOut();
        $('.calendar-modal-panel').fadeOut();
    }

    //Close modal panel
    $('#calendar-close-modal-panel').on("click",function(){
        closeModalPanel();
    });

    var changeModalPanelAccordingToSize = function(){
        if ($(window).width() <= 660) {
            setCalendarModalPanelSize(95,70);
        } else if ($(window).width() <= 960) {
            setCalendarModalPanelSize(60,40);
        } else {
            setCalendarModalPanelSize(40,60);
        }
    }

    $(window).resize(function(){
        changeModalPanelAccordingToSize();
    });

    //On startup
    changeModalPanelAccordingToSize();

});<|endoftext|>


<commit_before>var dagre = require('dagre');
var SVG = require('svg.js');
require('svg.panzoom.js');

var KerasModelViewer;

(function (root, factory) {

	/* CommonJS */
  if (typeof exports == 'object') module.exports = factory()

  /* AMD module */
  else if (typeof define == 'function' && define.amd) define(factory)

  /* Global */
  else root.KerasModelViewer = factory()

}(this, function () {

  KerasModelViewer = function(json, el, options) {
    if(!json) {
        console.log('KerasModelViewer: No Model provided.');
    }

    this.json = json;

    this._options = {
      "rankdir": "LR", // "LR"  "UD"
      "nodesep": 20,
      "edgesep": 20,
      "ranksep": 40,
      "marginx": 0,
      "marginy": 0,
      dims: {
        w:300,
        h:100
      },
      "keras_ver": 1 // only option now;
		};

		// Overwrites options
		if (options) {
			for (var i in options) {
				this._options[i] = options[i];
			}
		}

		if (typeof el == "string") {
			this._el = document.getElementById(el);
		}
    this.layer_ndx = "model";
    this.graph = { layer: [] };
    this.merge_layers_ndx = [];

    if(this._options.keras_ver == 1) {
      var KerasModelDef = require('./defs/keras_def_v1.js');
    }
    else {
      console.log('Only Keras v.1 models are supported');
      return;
    }
    this.keras_args = KerasModelDef.keras_args;
  }

  KerasModelViewer.prototype.flatten_input = function(layer, arr1) {
    var input_arr = [];
    if (!arr1 || arr1 == [] || typeof arr1 != "Array") {
      if (this.layer_ndx == 0) return [];
      return [source_layers[this.layer_ndx-1].config.name, layer];
    }
    for (i in arr1){
      var rec = flatten_input(layer, arr1[i])
      if (rec == []) input_arr.push(rec)
    }
    return input_arr;
  }

  KerasModelViewer.prototype.flattenArrayOfArrays = function(a, r) {
    if(!r){ r = []}
    for(var i=0; i<a.length; i++){
        if(a[i].constructor == Array){
            this.flattenArrayOfArrays(a[i], r);
        }else{
            r.push(a[i]);
        }
    }
    return r;
  }

  KerasModelViewer.prototype.add_model = function() {
    let json = this.json;
    var name = json.config.name || json.class_name

    this.dgraf.nodes[name]={
      label: name + "\n" +json.class_name,
      color: this.keras_args[json.class_name].color,
      width: this._options.dims.w,
      height: this._options.dims.h
    }

    if (json.config.input_layers) {
      var links = this.flattenArrayOfArrays(json.config.input_layers)
      for (i in links) {
        if (typeof links[i] == "string") this.dgraf.edges.push([name, links[i]])
      }
    }
    else {
        if(json.config instanceof Array)
          this.dgraf.edges.push([name, json.config[0].config.name])
    }
  }

  KerasModelViewer.prototype.draw_diag = function() {
    let json = this.json;

    this.view.clear();
    this.dgraf = {
      svgd: this.view,
      nodes: {  },
      edges: []

    }

    if (this._options.rankdir == "LR" && this._options.dims.w > this._options.dims.h) this._options.dims={w: this._options.dims.h, h: this._options.dims.w}
    if (this._options.rankdir == "UD" && this._options.dims.w < this._options.dims.h) this._options.dims={w: this._options.dims.h, h: this._options.dims.w}

    this.add_model()

    source_layers = json.config.layers? json.config.layers : json.config
    source_layers.model = json

    var ls= source_layers,name

    for (i in ls){
      layer = ls[i]
      if(layer.keras_version) return;
      this.layer_ndx = i
      name = layer.config.name ? layer.config.name : layer.name

      this.dgraf.nodes[name]={
        label: name + "\n" +layer.class_name,
        color: this.keras_args[layer.class_name].color,
        width: this._options.dims.w,
        height: this._options.dims.h
      }
      if (layer.class_name == "Merge") {
        this.merge_layers_ndx.push(i)
      }

      if (layer.inbound_nodes && this.layer_ndx != 0) {
        var conns = this.flattenArrayOfArrays(layer.inbound_nodes)
        //console.log(conns)
        for (j in conns){
            //console.log('draw_diag edges', conns[j], name)
          if (conns[j] !== 0) this.dgraf.edges.push([conns[j], name])
        }

      } else {
        if (this.layer_ndx != 0 && this.layer_ndx != "model") {
           //console.log('draw_diag edges2', source_layers[layer_ndx - 1].config.name, name)
          this.dgraf.edges.push([source_layers[this.layer_ndx - 1].config.name, name])
        }
      }

    }
    this.layer_ndx = 0
  }

  KerasModelViewer.prototype.showGraph = function() {
    let self = this;
    let t = this.dgraf;

    t.g = new dagre.graphlib.Graph();
    t.g.setGraph({});
    t.g.setDefaultEdgeLabel(function() { return {}; });
    var g = t.g

    t.svgd.clear()
    t.marker = this.add_marker(t.svgd)

    var nodes = t.nodes

    var edges = t.edges

    g.setGraph(this._options)

    for(row of edges) {
      g.setEdge(row[0], row[1])
    }

    for(row in nodes) {
      g.setNode(row, nodes[row])
    }

    dagre.layout(g)
    var det = g.graph()
    t.svgd.size(det.width, det.height)

    g.edges().forEach(function(e) {
        //console.log("Edge " + e.v + " -> " + e.w + ": " + JSON.stringify(g.edge(e)));
        self.draw_edge(t.svgd, g.edge(e).points, t.marker)
    })

    var j=0
    for (i in t.nodes) {
      if (j == 0 ) {
        this.graph.layer.model = this.draw_node(t.svgd, t.nodes[i],j)
      } else {
        this.graph.layer[j-1] = this.draw_node(t.svgd, t.nodes[i],j)
      }

      j++
    }

    var d = t.svgd.bbox()
    var div = {w: this._el.clientWidth, h: this._el.clientHeight-5}

    var r = 1
    if (d.w/d.h > div.w/div.h){
      r = div.w/d.w
    } else {
      r = div.h/d.h
    }
    t.svgd.attr({transform: "matrix("+r+",0,0,"+r+",0,0)"})
  }

  KerasModelViewer.prototype.draw_node = function(svgd, node, j) {
    var r = 5
    if (j === 0) { j="model" , r = Math.min(node.width, node.height)/2} else { j-- }
    var group = svgd.group().attr({"data-index":j,"stroke-width": 0.5})
    var rect1 = group.rect(node.width, node.height).cx(node.x).cy(node.y).fill(node.color).attr({"fill-opacity": 0.2, rx:r, ry:r})

    var txt = group.text(node.label).x(node.x).y(node.y-20).font({anchor: 'middle'})

    if (this._options.rankdir == "LR") txt.rotate(-90)

    return group;
  }

  KerasModelViewer.prototype.draw_edge = function(svgd, points, marker) {
    var i, str="M " + points[0].x + ' ' + points[0].y + 'C '
    var len = points.length
    if(len == 2)
      str += points[0].x + ' ' + points[0].y + ' ' + points[1].x + ' ' + points[1].y + ' '
    else if(len == 3)
      str += points[1].x + ' ' + points[1].y + ' ' + points[1].x + ' ' + points[1].y + ' '
    else if(len == 4)
      str += points[1].x + ' ' + points[1].y + ' ' + points[2].x + ' ' + points[2].y + ' '
    else
      str += points[1].x + ' ' + points[1].y + ' ' + points[len-2].x + ' ' + points[len-2].y + ' '

    str += points[len-1].x + ' ' + points[len-1].y

    var edge = svgd.path(str).fill('none').stroke({width: 1}).attr({"stroke-linecap":"round", "stroke-linejoin":"round"})
    edge.marker('end', marker)
  }

  KerasModelViewer.prototype.add_marker = function(svgd) {
    var marker = svgd.marker(-19, 10, function(add) {
      add.path("M-19,0l10,5l-10,5l4,-5l-4,-5z").attr({"stroke-linecap":"round", "stroke-linejoin":"round"})
    })
    return marker
  }

  KerasModelViewer.prototype.show = function() {
    draw = SVG(this._el).size('100%', '100%').panZoom();

    this.view = draw.group().attr({id:"diagram"});

    this.draw_diag();
    this.showGraph();
  }

  KerasModelViewer.prototype.clear = function() {
    this.view.clear();
  }

  KerasModelViewer.prototype.model = function() {

  }

  return KerasModelViewer;
}));

exports = module.exports = KerasModelViewer;
<commit_msg>Add model() method for changing the JSON model.<commit_after>var dagre = require('dagre');
var SVG = require('svg.js');
require('svg.panzoom.js');

var KerasModelViewer;

(function (root, factory) {

	/* CommonJS */
  if (typeof exports == 'object') module.exports = factory()

  /* AMD module */
  else if (typeof define == 'function' && define.amd) define(factory)

  /* Global */
  else root.KerasModelViewer = factory()

}(this, function () {

  KerasModelViewer = function(json, el, options) {
    if(!json) {
        console.log('KerasModelViewer: No Model provided.');
    }

    this.json = json;

    this._options = {
      "rankdir": "LR", // "LR"  "UD"
      "nodesep": 20,
      "edgesep": 20,
      "ranksep": 40,
      "marginx": 0,
      "marginy": 0,
      dims: {
        w:300,
        h:100
      },
      "keras_ver": 1 // only option now;
		};

		// Overwrites options
		if (options) {
			for (var i in options) {
				this._options[i] = options[i];
			}
		}

		if (typeof el == "string") {
			this._el = document.getElementById(el);
		}
    this.layer_ndx = "model";
    this.graph = { layer: [] };
    this.merge_layers_ndx = [];

    if(this._options.keras_ver == 1) {
      var KerasModelDef = require('./defs/keras_def_v1.js');
    }
    else {
      console.log('Only Keras v.1 models are supported');
      return;
    }
    this.keras_args = KerasModelDef.keras_args;
  }

  KerasModelViewer.prototype.flatten_input = function(layer, arr1) {
    var input_arr = [];
    if (!arr1 || arr1 == [] || typeof arr1 != "Array") {
      if (this.layer_ndx == 0) return [];
      return [source_layers[this.layer_ndx-1].config.name, layer];
    }
    for (i in arr1){
      var rec = flatten_input(layer, arr1[i])
      if (rec == []) input_arr.push(rec)
    }
    return input_arr;
  }

  KerasModelViewer.prototype.flattenArrayOfArrays = function(a, r) {
    if(!r){ r = []}
    for(var i=0; i<a.length; i++){
        if(a[i].constructor == Array){
            this.flattenArrayOfArrays(a[i], r);
        }else{
            r.push(a[i]);
        }
    }
    return r;
  }

  KerasModelViewer.prototype.add_model = function() {
    let json = this.json;
    var name = json.config.name || json.class_name

    this.dgraf.nodes[name]={
      label: name + "\n" +json.class_name,
      color: this.keras_args[json.class_name].color,
      width: this._options.dims.w,
      height: this._options.dims.h
    }

    if (json.config.input_layers) {
      var links = this.flattenArrayOfArrays(json.config.input_layers)
      for (i in links) {
        if (typeof links[i] == "string") this.dgraf.edges.push([name, links[i]])
      }
    }
    else {
        if(json.config instanceof Array)
          this.dgraf.edges.push([name, json.config[0].config.name])
    }
  }

  KerasModelViewer.prototype.draw_diag = function() {
    let json = this.json;

    this.view.clear();
    this.dgraf = {
      svgd: this.view,
      nodes: {  },
      edges: []

    }

    if (this._options.rankdir == "LR" && this._options.dims.w > this._options.dims.h) this._options.dims={w: this._options.dims.h, h: this._options.dims.w}
    if (this._options.rankdir == "UD" && this._options.dims.w < this._options.dims.h) this._options.dims={w: this._options.dims.h, h: this._options.dims.w}

    this.add_model()

    source_layers = json.config.layers? json.config.layers : json.config
    source_layers.model = json

    var ls= source_layers,name

    for (i in ls){
      layer = ls[i]
      if(layer.keras_version) return;
      this.layer_ndx = i
      name = layer.config.name ? layer.config.name : layer.name

      this.dgraf.nodes[name]={
        label: name + "\n" +layer.class_name,
        color: this.keras_args[layer.class_name].color,
        width: this._options.dims.w,
        height: this._options.dims.h
      }
      if (layer.class_name == "Merge") {
        this.merge_layers_ndx.push(i)
      }

      if (layer.inbound_nodes && this.layer_ndx != 0) {
        var conns = this.flattenArrayOfArrays(layer.inbound_nodes)
        //console.log(conns)
        for (j in conns){
            //console.log('draw_diag edges', conns[j], name)
          if (conns[j] !== 0) this.dgraf.edges.push([conns[j], name])
        }

      } else {
        if (this.layer_ndx != 0 && this.layer_ndx != "model") {
           //console.log('draw_diag edges2', source_layers[layer_ndx - 1].config.name, name)
          this.dgraf.edges.push([source_layers[this.layer_ndx - 1].config.name, name])
        }
      }

    }
    this.layer_ndx = 0
  }

  KerasModelViewer.prototype.showGraph = function() {
    let self = this;
    let t = this.dgraf;

    t.g = new dagre.graphlib.Graph();
    t.g.setGraph({});
    t.g.setDefaultEdgeLabel(function() { return {}; });
    var g = t.g

    t.svgd.clear()
    t.marker = this.add_marker(t.svgd)

    var nodes = t.nodes

    var edges = t.edges

    g.setGraph(this._options)

    for(row of edges) {
      g.setEdge(row[0], row[1])
    }

    for(row in nodes) {
      g.setNode(row, nodes[row])
    }

    dagre.layout(g)
    var det = g.graph()
    t.svgd.size(det.width, det.height)

    g.edges().forEach(function(e) {
        //console.log("Edge " + e.v + " -> " + e.w + ": " + JSON.stringify(g.edge(e)));
        self.draw_edge(t.svgd, g.edge(e).points, t.marker)
    })

    var j=0
    for (i in t.nodes) {
      if (j == 0 ) {
        this.graph.layer.model = this.draw_node(t.svgd, t.nodes[i],j)
      } else {
        this.graph.layer[j-1] = this.draw_node(t.svgd, t.nodes[i],j)
      }

      j++
    }

    var d = t.svgd.bbox()
    var div = {w: this._el.clientWidth, h: this._el.clientHeight-5}

    var r = 1
    if (d.w/d.h > div.w/div.h){
      r = div.w/d.w
    } else {
      r = div.h/d.h
    }
    t.svgd.attr({transform: "matrix("+r+",0,0,"+r+",0,0)"})
  }

  KerasModelViewer.prototype.draw_node = function(svgd, node, j) {
    var r = 5
    if (j === 0) { j="model" , r = Math.min(node.width, node.height)/2} else { j-- }
    var group = svgd.group().attr({"data-index":j,"stroke-width": 0.5})
    var rect1 = group.rect(node.width, node.height).cx(node.x).cy(node.y).fill(node.color).attr({"fill-opacity": 0.2, rx:r, ry:r})

    var txt = group.text(node.label).x(node.x).y(node.y-20).font({anchor: 'middle'})

    if (this._options.rankdir == "LR") txt.rotate(-90)

    return group;
  }

  KerasModelViewer.prototype.draw_edge = function(svgd, points, marker) {
    var i, str="M " + points[0].x + ' ' + points[0].y + 'C '
    var len = points.length
    if(len == 2)
      str += points[0].x + ' ' + points[0].y + ' ' + points[1].x + ' ' + points[1].y + ' '
    else if(len == 3)
      str += points[1].x + ' ' + points[1].y + ' ' + points[1].x + ' ' + points[1].y + ' '
    else if(len == 4)
      str += points[1].x + ' ' + points[1].y + ' ' + points[2].x + ' ' + points[2].y + ' '
    else
      str += points[1].x + ' ' + points[1].y + ' ' + points[len-2].x + ' ' + points[len-2].y + ' '

    str += points[len-1].x + ' ' + points[len-1].y

    var edge = svgd.path(str).fill('none').stroke({width: 1}).attr({"stroke-linecap":"round", "stroke-linejoin":"round"})
    edge.marker('end', marker)
  }

  KerasModelViewer.prototype.add_marker = function(svgd) {
    var marker = svgd.marker(-19, 10, function(add) {
      add.path("M-19,0l10,5l-10,5l4,-5l-4,-5z").attr({"stroke-linecap":"round", "stroke-linejoin":"round"})
    })
    return marker
  }

  KerasModelViewer.prototype.show = function() {
    draw = SVG(this._el).size('100%', '100%').panZoom();

    this.view = draw.group().attr({id:"diagram"});

    this.draw_diag();
    this.showGraph();
  }

  KerasModelViewer.prototype.clear = function() {
    this.view.clear();
  }

  KerasModelViewer.prototype.model = function(newjson) {
    if(newjson)
      this.json = newjson;
    this.draw_diag();
    this.showGraph();
  }

  return KerasModelViewer;
}));

exports = module.exports = KerasModelViewer;
<|endoftext|>


<commit_before>var AppStore = require('../stores/AppStore');
var Generator = require('./Generator.react');
var Footer = require('./Footer.react');
var Header = require('./Header.react');

var App = React.createClass({
	// Get the data when the component is first created and save it to this.state
	getInitialState: function() {
		return AppStore.getData();
	},
	componentDidMount: function() {
		// Fade the website in
		this._fadeInApp();
		AppStore.addChangeListener(this._onChange);
		this._initAnalytics();
	},
	componentWillUnmount: function() {
		AppStore.removeChangeListener(this._onChange);
	},
	render: function() {
		// Render the basic layout and the Generator, found at js/components/Generator.react.js
		return (

<mxstbr/>

					<svg width="80" height="80" viewBox="0 0 250 250" className="github-corner">
					  <path className="github-corner__bg" d="M0 0l115 115h15l12 27 108 108V0z" />
					  <path className="octo-arm" d="M128 109c-15-9-9-19-9-19 3-7 2-11 2-11-1-7 3-2 3-2 4 5 2 11 2 11-3 10 5 15 9 16" />
					  <path className="octo-body" d="M115 115s4 2 5 0l14-14c3-2 6-3 8-3-8-11-15-24 2-41 5-5 10-7 16-7 1-2 3-7 12-11 0 0 5 3 7 16 4 2 8 5 12 9s7 8 9 12c14 3 17 7 17 7-4 8-9 11-11 11 0 6-2 11-7 16-16 16-30 10-41 2 0 3-1 7-5 11l-12 11c-1 1 1 5 1 5z"/>
					</svg>

					<Generator data={this.state} />

		);
	},
	// If the data changes, get the new data and rerender if something changed
	_onChange: function() {
	    this.setState(AppStore.getData());
	},
	_fadeInApp: function() {
		var elem = this.getDOMNode();
		var spinnerWrapper = document.querySelector('.spinner-wrapper');
		elem.style.opacity = 0;
		setTimeout(function() {
			elem.style.transition = "opacity 250ms";
			elem.style.opacity = 1;
			// And the loading spinner out
			spinnerWrapper.style.transition = "opacity 250ms";
			spinnerWrapper.style.opacity = 0;
			setTimeout(function() {
				spinnerWrapper.style.display = "none";
			}, 250);
		}, 0);
	},
	_initAnalytics: function() {
		window.owa_baseUrl = 'http://analytics.mxstbr.com/';
		window.owa_cmds = window.owa_cmds || [];
		window.owa_cmds.push(['setSiteId', '664af9a4b4b955434ee1980e56896ab7']);
		window.owa_cmds.push(['trackPageView']);
		window.owa_cmds.push(['trackClicks']);
		window.owa_cmds.push(['trackDomStream']);
		(function() {
	    var _owa = document.createElement('script'); _owa.type = 'text/javascript'; _owa.async = true;
	    window.owa_baseUrl = ('https:' == document.location.protocol ? window.owa_baseSecUrl || window.owa_baseUrl.replace(/http:/, 'https:') : window.owa_baseUrl );
	    _owa.src = window.owa_baseUrl + 'modules/base/js/owa.tracker-combined-min.js';
	    var _owa_s = document.getElementsByTagName('script')[0]; _owa_s.parentNode.insertBefore(_owa, _owa_s);
	  }());
	}
});

module.exports = App;
<commit_msg>Update App.react.js<commit_after>var AppStore = require('../stores/AppStore');
var Generator = require('./Generator.react');
var Footer = require('./Footer.react');
var Header = require('./Header.react');

var App = React.createClass({
	// Get the data when the component is first created and save it to this.state
	getInitialState: function() {
		return AppStore.getData();
	},
	componentDidMount: function() {
		// Fade the website in
		this._fadeInApp();
		AppStore.addChangeListener(this._onChange);
		this._initAnalytics();
	},
	componentWillUnmount: function() {
		AppStore.removeChangeListener(this._onChange);
	},
	render: function() {
		// Render the basic layout and the Generator, found at js/components/Generator.react.js
		return (

<mxstbr/>

					<svg width="80" height="80" viewBox="0 0 250 250" className="github-corner">
					  <path className="github-corner__bg" d="M0 0l115 115h15l12 27 108 108V0z" />
					  <path className="octo-arm" d="M128 109c-15-9-9-19-9-19 3-7 2-11 2-11-1-7 3-2 3-2 4 5 2 11 2 11-3 10 5 15 9 16" />
					  <path className="octo-body" d="M115 115s4 2 5 0l14-14c3-2 6-3 8-3-8-11-15-24 2-41 5-5 10-7 16-7 1-2 3-7 12-11 0 0 5 3 7 16 4 2 8 5 12 9s7 8 9 12c14 3 17 7 17 7-4 8-9 11-11 11 0 6-2 11-7 16-16 16-30 10-41 2 0 3-1 7-5 11l-12 11c-1 1 1 5 1 5z"/>
					</svg>

					<Generator data={this.state} />

		);
	},
	// If the data changes, get the new data and rerender if something changed
	_onChange: function() {
	    this.setState(AppStore.getData());
	},
	_fadeInApp: function() {
		var elem = this.getDOMNode();
		var spinnerWrapper = document.querySelector('.spinner-wrapper');
		elem.style.opacity = 0;
		setTimeout(function() {
			elem.style.transition = "opacity 250ms";
			elem.style.opacity = 1;
			// And the loading spinner out
			spinnerWrapper.style.transition = "opacity 250ms";
			spinnerWrapper.style.opacity = 0;
			setTimeout(function() {
				spinnerWrapper.style.display = "none";
			}, 250);
		}, 0);
	},
	_initAnalytics: function() {
	}
});

module.exports = App;
<|endoftext|>


<commit_before>(function ($) {

  window.WisemblyMixpanel = {

    version: '0.1.5',

    options: {
      identifier: '',
      script: '//cdn.mxpnl.com/libs/mixpanel-2.2.min.js',
      scriptTimeout: 5000,
      isEnabled: true,
      identity: null,
      onBoot: null,
      onStore: null,
      onFlush: null,
      onTrack: null,
      onTrackError: null,
      onScript: null,
      onScriptError: null
    },

    setOptions: function (options) {
      options = options || {};
      this.options = $.extend(this.options, options);
    },

    init: function () {
      var self = this;

      window.mixpanel = window.mixpanel || [];
      window.mixpanel.__SV = 1.2;

      if (!this.boot()) {
        this._loadScript().done(function () { self.boot(); })
      }
    },

    _get: function (property) {
      if (typeof this.options[property] === 'function')
        return this.options[property].call(this);
      return this.options[property];
    },

    _notify: function (eventName) {
      if (typeof this.options[eventName] === 'function')
        this.options[eventName].apply(this, [].slice.call(arguments, 1));
    },

    _loadScript: function () {
      var self = this;
      return $.ajax({ url: this._get('script'), dataType: 'script', timeout: this._get('scriptTimeout') })
        .done(function () { self._notify('onScript'); })
        .fail(function () { self._notify('onScriptError'); });
    },

    boot: function () {
      if (!this.isLoaded() || !this.isEnabled())
        return false;

      window.mixpanel.init(this._get('identifier'));
      this.initialized = true;

      this.track('identify', this._get('identity'), {}, true);
      this._notify('onBoot');
      return true;
    },

    isLoaded: function () {
      return window.mixpanel && typeof window.mixpanel.init === 'function';
    },

    isReady: function () {
      return this.initialized;
    },

    isEnabled: function () {
      return this._get('isEnabled');
    },

    track: function (type, data, metadata, priority) {
      if (!type)
        return false;
      this.store(type, data, metadata, priority);
      if (this.isReady() && this.isEnabled())
        this.flush();
      return true;
    },

    store: function (type, data, metadata, priority) {
      this._storedEvents = this._storedEvents || [];
      this._storedId = this._storedId || 0;
      // Build and store Deferred
      var _event = {
        id: ++this._storedId,
        dfd: $.Deferred(),
        type: type,
        data: data,
        metadata: metadata
      };

      if (priority !== true)
        this._storedEvents.push(_event);
      else
        this._storedEvents.unshift(_event);

      this._notify('onStore', _event);

      return _event;
    },

    flush: function () {
      var self = this;
      while (this._storedEvents && this._storedEvents.length) {
        (function (_event) {
          self._notify('onFlush', _event);
          self.mixpanelTrack(_event)
            .done(function () { self._notify('onTrack', _event); })
            .fail(function () { self._notify('onTrackError', _event); });
        })(this._storedEvents.shift());
      }
    },

    mixpanelTrack: function (_event) {
      if (!this.isReady() || !this.isEnabled())
        return _event.dfd.reject().promise();

      var fnCallback = function (status) {
        if (status === 1)
          _event.dfd.resolve();
        else
          _event.dfd.reject();
      };

      switch (_event.type) {
        case 'identify':
          window.mixpanel.identify(_event.data);
          window.mixpanel.register({ user_id: _event.data });
          _event.dfd.resolve();
          break;
        case 'track':
          window.mixpanel.track(_event.data, _event.metadata, fnCallback);
          break;
        case 'people.set':
          window.mixpanel.people.set(_event.data, fnCallback);
          break;
        case 'people.set_once':
          window.mixpanel.people.set_once(_event.data, fnCallback);
          break;
        case 'people.increment':
          var increment = _event.metadata ? _event.metadata.count : undefined;
          window.mixpanel.people.increment(_event.data, increment, fnCallback);
          break;
        case 'people.append':
          window.mixpanel.people.append(_event.data, fnCallback);
          break;
        case 'people.track_charge':
          window.mixpanel.people.track_charge(_event.data, fnCallback);
          break;
        default:
          _event.dfd.reject();
      }

      return _event.dfd.promise();
    }
  };

})(jQuery);
<commit_msg>Increment | Normalize vars<commit_after>(function ($) {

  window.WisemblyMixpanel = {

    version: '0.1.5',

    options: {
      identifier: '',
      script: '//cdn.mxpnl.com/libs/mixpanel-2.2.min.js',
      scriptTimeout: 5000,
      isEnabled: true,
      identity: null,
      onBoot: null,
      onStore: null,
      onFlush: null,
      onTrack: null,
      onTrackError: null,
      onScript: null,
      onScriptError: null
    },

    setOptions: function (options) {
      options = options || {};
      this.options = $.extend(this.options, options);
    },

    init: function () {
      var self = this;

      window.mixpanel = window.mixpanel || [];
      window.mixpanel.__SV = 1.2;

      if (!this.boot()) {
        this._loadScript().done(function () { self.boot(); })
      }
    },

    _get: function (property) {
      if (typeof this.options[property] === 'function')
        return this.options[property].call(this);
      return this.options[property];
    },

    _notify: function (eventName) {
      if (typeof this.options[eventName] === 'function')
        this.options[eventName].apply(this, [].slice.call(arguments, 1));
    },

    _loadScript: function () {
      var self = this;
      return $.ajax({ url: this._get('script'), dataType: 'script', timeout: this._get('scriptTimeout') })
        .done(function () { self._notify('onScript'); })
        .fail(function () { self._notify('onScriptError'); });
    },

    boot: function () {
      if (!this.isLoaded() || !this.isEnabled())
        return false;

      window.mixpanel.init(this._get('identifier'));
      this.initialized = true;

      this.track('identify', this._get('identity'), {}, true);
      this._notify('onBoot');
      return true;
    },

    isLoaded: function () {
      return window.mixpanel && typeof window.mixpanel.init === 'function';
    },

    isReady: function () {
      return this.initialized;
    },

    isEnabled: function () {
      return this._get('isEnabled');
    },

    track: function (type, data, metadata, priority) {
      if (!type)
        return false;
      this.store(type, data, metadata, priority);
      if (this.isReady() && this.isEnabled())
        this.flush();
      return true;
    },

    store: function (type, data, metadata, priority) {
      this._storedEvents = this._storedEvents || [];
      this._storedId = this._storedId || 0;
      // Build and store Deferred
      var _event = {
        id: ++this._storedId,
        dfd: $.Deferred(),
        type: type,
        data: data,
        metadata: metadata
      };

      if (priority !== true)
        this._storedEvents.push(_event);
      else
        this._storedEvents.unshift(_event);

      this._notify('onStore', _event);

      return _event;
    },

    flush: function () {
      var self = this;
      while (this._storedEvents && this._storedEvents.length) {
        (function (_event) {
          self._notify('onFlush', _event);
          self.mixpanelTrack(_event)
            .done(function () { self._notify('onTrack', _event); })
            .fail(function () { self._notify('onTrackError', _event); });
        })(this._storedEvents.shift());
      }
    },

    mixpanelTrack: function (_event) {
      if (!this.isReady() || !this.isEnabled())
        return _event.dfd.reject().promise();

      var fnCallback = function (status) {
        if (status === 1)
          _event.dfd.resolve();
        else
          _event.dfd.reject();
      };

      switch (_event.type) {
        case 'identify':
          window.mixpanel.identify(_event.data);
          window.mixpanel.register({ user_id: _event.data });
          _event.dfd.resolve();
          break;
        case 'track':
          window.mixpanel.track(_event.data, _event.metadata, fnCallback);
          break;
        case 'people.set':
          window.mixpanel.people.set(_event.data, fnCallback);
          break;
        case 'people.set_once':
          window.mixpanel.people.set_once(_event.data, fnCallback);
          break;
        case 'people.increment':
          var increment = _event.metadata ? _event.metadata.increment : undefined;
          window.mixpanel.people.increment(_event.data, increment, fnCallback);
          break;
        case 'people.append':
          window.mixpanel.people.append(_event.data, fnCallback);
          break;
        case 'people.track_charge':
          window.mixpanel.people.track_charge(_event.data, fnCallback);
          break;
        default:
          _event.dfd.reject();
      }

      return _event.dfd.promise();
    }
  };

})(jQuery);
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import ReactDOM from 'react-dom'

import {DatePicker, DatePickerInput} from './src'
import Styles from './dist/darkInput.css'
import DemoStyles from './index.css'

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: '2016-03-14',
            value1: '2016-03-12',
            value2: '2016-03',
            value3: '2016',
        };
    }

    render() {
        return

Date input(auto position in scroll container)

                    <DatePickerInput
                        value={this.state.value}
                        readOnly={true}
                        autoPosition={true}
                        container='#scrollContainer'
                        preferPo sition="topLeft"
                        closeOnSelect={true}
                        closeOnClickOutside={true}
                        displayFormat="yyyy/MM/dd"
                        returnFormat="yyyy-MM-dd"
                        onChange={(v)=>{this.setState({value: v})}}
                    />

Selected: {this.state.value}

Props

                        autoPosition= true

                        container= '#scrollContainer'

                        preferPosition= "topLeft"

                        closeOnSelect= true

                        closeOnClickOutside= true

                        displayFormat= "yyyy-MM-dd"

                        returnFormat= "yyyy/MM/dd"

Date input(auto position)

                    <DatePickerInput
                        value={this.state.value}
                        readOnly={true}
                        autoPosition={true}
                        preferPosition="bottomRight"
                        closeOnSelect={true}
                        closeOnClickOutside={true}
                        displayFormat="yyyy年M月d日"
                        returnFormat="yyyy-MM-dd"
                        onChange={(v)=>{this.setState({value: v})}}
                    />

Selected: {this.state.value}

Props

                        autoPosition= true

                        preferPosition= "bottomRight"

                        closeOnSelect= true

                        closeOnClickOutside= true

                        displayFormat= "yyyy-MM-dd"

                        returnFormat= "yyyy年M月d日"

Day picker

                    <DatePicker
                        mode="day"
                        min="2015-05-20"
                        max="2016-05-20"
                        value={this.state.value1}
                        returnFormat="yyyy-MM-dd"
                        onChange={(v)=>{this.setState({value1: v})}}
                    />

Selected: {this.state.value1}

Props

                        mode= "day"

                        min= "2015-05-20"

                        max= "2016-05-20"

                        returnFormat= "yyyy-MM-dd"

Month picker

                    <DatePicker
                        mode="month"
                        min="2015-05"
                        max="2016-05"
                        returnFormat="yyyy-MM"
                        value={this.state.value2}
                        onChange={(v)=>{this.setState({value2: v})}}
                    />

Selected: {this.state.value2}

Props

                        mode= "month"

                        min= "2015-05"

                        max= "2016-05"

                        returnFormat= "yyyy-MM"

Year picker

                    <DatePicker
                        mode="year"
                        min="2015"
                        max="2016"
                        returnFormat="yyyy"
                        value={this.state.value3}
                        onChange={(v)=>{this.setState({value3: v})}}
                    />

Selected: {this.state.value3}

Props

                        mode= "year"

                        min= "2015"

                        max= "2016"

                        returnFormat= "yyyy"

    }
}

ReactDOM.render(<Page />, document.getElementById('main'));
<commit_msg>fix demo<commit_after>import React, {PropTypes} from 'react'
import ReactDOM from 'react-dom'

import {DatePicker, DatePickerInput} from './src'
import Styles from './dist/darkInput.css'
import DemoStyles from './index.css'

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: '2016-03-14',
            value1: '2016-03-12',
            value2: '2016-03',
            value3: '2016',
        };
    }

    render() {
        return

Date input(auto position in scroll container)

                    <DatePickerInput
                        value={this.state.value}
                        readOnly={true}
                        autoPosition={true}
                        container='#scrollContainer'
                        preferPosition="topLeft"
                        closeOnSelect={true}
                        closeOnClickOutside={true}
                        displayFormat="yyyy/MM/dd"
                        returnFormat="yyyy-MM-dd"
                        onChange={(v)=>{this.setState({value: v})}}
                    />

Selected: {this.state.value}

Props

                        autoPosition= true

                        container= '#scrollContainer'

                        preferPosition= "topLeft"

                        closeOnSelect= true

                        closeOnClickOutside= true

                        displayFormat= "yyyy-MM-dd"

                        returnFormat= "yyyy/MM/dd"

Date input(auto position)

                    <DatePickerInput
                        value={this.state.value}
                        readOnly={true}
                        autoPosition={true}
                        preferPosition="bottomRight"
                        closeOnSelect={true}
                        closeOnClickOutside={true}
                        displayFormat="yyyy年M月d日"
                        returnFormat="yyyy-MM-dd"
                        onChange={(v)=>{this.setState({value: v})}}
                    />

Selected: {this.state.value}

Props

                        autoPosition= true

                        preferPosition= "bottomRight"

                        closeOnSelect= true

                        closeOnClickOutside= true

                        displayFormat= "yyyy-MM-dd"

                        returnFormat= "yyyy年M月d日"

Day picker

                    <DatePicker
                        mode="day"
                        min="2015-05-20"
                        max="2016-05-20"
                        value={this.state.value1}
                        returnFormat="yyyy-MM-dd"
                        onChange={(v)=>{this.setState({value1: v})}}
                    />

Selected: {this.state.value1}

Props

                        mode= "day"

                        min= "2015-05-20"

                        max= "2016-05-20"

                        returnFormat= "yyyy-MM-dd"

Month picker

                    <DatePicker
                        mode="month"
                        min="2015-05"
                        max="2016-05"
                        returnFormat="yyyy-MM"
                        value={this.state.value2}
                        onChange={(v)=>{this.setState({value2: v})}}
                    />

Selected: {this.state.value2}

Props

                        mode= "month"

                        min= "2015-05"

                        max= "2016-05"

                        returnFormat= "yyyy-MM"

Year picker

                    <DatePicker
                        mode="year"
                        min="2015"
                        max="2016"
                        returnFormat="yyyy"
                        value={this.state.value3}
                        onChange={(v)=>{this.setState({value3: v})}}
                    />

Selected: {this.state.value3}

Props

                        mode= "year"

                        min= "2015"

                        max= "2016"

                        returnFormat= "yyyy"

    }
}

ReactDOM.render(<Page />, document.getElementById('main'));
<|endoftext|>


<commit_before>// Copyright 2015-2019, University of Colorado Boulder

/**
 * Base type for ScreenViews that use a combo box to select a demo.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const ComboBox = require( 'SUN/ComboBox' );
  const ComboBoxItem = require( 'SUN/ComboBoxItem' );
  const inherit = require( 'PHET_CORE/inherit' );
  const merge = require( 'PHET_CORE/merge' );
  const Node = require( 'SCENERY/nodes/Node' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const Property = require( 'AXON/Property' );
  const ScreenView = require( 'JOIST/ScreenView' );
  const sun = require( 'SUN/sun' );
  const Tandem = require( 'TANDEM/Tandem' );
  const Text = require( 'SCENERY/nodes/Text' );
  const Vector2 = require( 'DOT/Vector2' );

  /**
   * @param {Object[]} demos - each demo has these properties:
   *   {string} label - label in the combo box
   *   {function(layoutBounds:Bounds2): Node} createNode - creates the Node for the demo
   *   {Node|null} node - the Node for the demo, created by DemosScreenView
   * @param {Object} [options]
   * @constructor
   */
  function DemosScreenView( demos, options ) {

    options = merge( {

      selectedDemoLabel: null, // {string|null} label field of the demo to be selected initially

      // options related to the ComboBox that selects the demo
      comboBoxCornerRadius: 4,
      comboBoxPosition: new Vector2( 20, 20 ), // {Vector2} position of ComboBox used to select a demo
      comboBoxItemFont: new PhetFont( 20 ), // {Font} font used for ComboBox items
      comboBoxItemXMargin: 12, // {number} x margin around ComboBox items
      comboBoxItemYMargin: 8, // {number} y margin around ComboBox items

      // {boolean} see https://github.com/phetsims/sun/issues/386
      // true = caches Nodes for all demos that have been selected
      // false = keeps only the Node for the selected demo in memory
      cacheDemos: false,

      tandem: Tandem.REQUIRED
    }, options );

    ScreenView.call( this, options );

    const layoutBounds = this.layoutBounds;

    // Sort the demos by label, so that they appear in the combo box in alphabetical order
    demos = _.sortBy( demos, function( demo ) {
      return demo.label;
    } );

    // All demos will be children of this node, to maintain rendering order with combo box list
    const demosParent = new Node();
    this.addChild( demosParent );

    // add each demo to the combo box
    const comboBoxItems = [];
    demos.forEach( function( demo ) {
      comboBoxItems.push( new ComboBoxItem( new Text( demo.label, { font: options.comboBoxItemFont } ), demo, {

        // demo.label is like ArrowNode or StopwatchNode, decorate it for use as a tandem.
        tandemName: 'demo' + demo.label + 'ComboBoxItem'
      } ) );
    } );

    // Parent for the combo box popup list
    const listParent = new Node();
    this.addChild( listParent );

    // Set the initial demo
    let selectedDemo = demos[ 0 ];
    if ( options.selectedDemoLabel ) {
      selectedDemo = _.find( demos, function( demo ) {
        return ( demo.label === options.selectedDemoLabel );
      } );
      if ( !selectedDemo ) {
        throw new Error( 'demo not found: ' + options.selectedDemoLabel );
      }
    }

    // Combo box for selecting which component to view
    const selectedDemoProperty = new Property( selectedDemo );
    const comboBox = new ComboBox( comboBoxItems, selectedDemoProperty, listParent, {
      buttonFill: 'rgb( 218, 236, 255 )',
      cornerRadius: options.comboBoxCornerRadius,
      xMargin: options.comboBoxItemXMargin,
      yMargin: options.comboBoxItemYMargin,
      top: options.comboBoxPosition.x,
      left: options.comboBoxPosition.y,
      tandem: options.tandem.createTandem( 'comboBox' )
    } );
    this.addChild( comboBox );

    // Make the selected demo visible
    selectedDemoProperty.link( function( demo, oldDemo ) {

      // clean up the previously selected demo
      if ( oldDemo ) {
        if ( options.cacheDemos ) {

          // make the old demo invisible
          oldDemo.node.visible = false;
        }
        else {

          // delete the old demo
          demosParent.removeChild( oldDemo.node );
          oldDemo.node.dispose();
          oldDemo.node = null;
        }
      }

      if ( demo.node ) {

        // If the selected demo has an associated node, make it visible.
        demo.node.visible = true;
      }
      else {

        // If the selected demo doesn't doesn't have an associated node, create it.
        demo.node = demo.createNode( layoutBounds, {
          tandem: options.tandem.createTandem( 'demo' + demo.label )
        } );
        demosParent.addChild( demo.node );
      }
    } );
  }

  sun.register( 'DemosScreenView', DemosScreenView );

  return inherit( ScreenView, DemosScreenView );
} );
<commit_msg>update copyright dates from daily grunt work<commit_after>// Copyright 2015-2020, University of Colorado Boulder

/**
 * Base type for ScreenViews that use a combo box to select a demo.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const ComboBox = require( 'SUN/ComboBox' );
  const ComboBoxItem = require( 'SUN/ComboBoxItem' );
  const inherit = require( 'PHET_CORE/inherit' );
  const merge = require( 'PHET_CORE/merge' );
  const Node = require( 'SCENERY/nodes/Node' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const Property = require( 'AXON/Property' );
  const ScreenView = require( 'JOIST/ScreenView' );
  const sun = require( 'SUN/sun' );
  const Tandem = require( 'TANDEM/Tandem' );
  const Text = require( 'SCENERY/nodes/Text' );
  const Vector2 = require( 'DOT/Vector2' );

  /**
   * @param {Object[]} demos - each demo has these properties:
   *   {string} label - label in the combo box
   *   {function(layoutBounds:Bounds2): Node} createNode - creates the Node for the demo
   *   {Node|null} node - the Node for the demo, created by DemosScreenView
   * @param {Object} [options]
   * @constructor
   */
  function DemosScreenView( demos, options ) {

    options = merge( {

      selectedDemoLabel: null, // {string|null} label field of the demo to be selected initially

      // options related to the ComboBox that selects the demo
      comboBoxCornerRadius: 4,
      comboBoxPosition: new Vector2( 20, 20 ), // {Vector2} position of ComboBox used to select a demo
      comboBoxItemFont: new PhetFont( 20 ), // {Font} font used for ComboBox items
      comboBoxItemXMargin: 12, // {number} x margin around ComboBox items
      comboBoxItemYMargin: 8, // {number} y margin around ComboBox items

      // {boolean} see https://github.com/phetsims/sun/issues/386
      // true = caches Nodes for all demos that have been selected
      // false = keeps only the Node for the selected demo in memory
      cacheDemos: false,

      tandem: Tandem.REQUIRED
    }, options );

    ScreenView.call( this, options );

    const layoutBounds = this.layoutBounds;

    // Sort the demos by label, so that they appear in the combo box in alphabetical order
    demos = _.sortBy( demos, function( demo ) {
      return demo.label;
    } );

    // All demos will be children of this node, to maintain rendering order with combo box list
    const demosParent = new Node();
    this.addChild( demosParent );

    // add each demo to the combo box
    const comboBoxItems = [];
    demos.forEach( function( demo ) {
      comboBoxItems.push( new ComboBoxItem( new Text( demo.label, { font: options.comboBoxItemFont } ), demo, {

        // demo.label is like ArrowNode or StopwatchNode, decorate it for use as a tandem.
        tandemName: 'demo' + demo.label + 'ComboBoxItem'
      } ) );
    } );

    // Parent for the combo box popup list
    const listParent = new Node();
    this.addChild( listParent );

    // Set the initial demo
    let selectedDemo = demos[ 0 ];
    if ( options.selectedDemoLabel ) {
      selectedDemo = _.find( demos, function( demo ) {
        return ( demo.label === options.selectedDemoLabel );
      } );
      if ( !selectedDemo ) {
        throw new Error( 'demo not found: ' + options.selectedDemoLabel );
      }
    }

    // Combo box for selecting which component to view
    const selectedDemoProperty = new Property( selectedDemo );
    const comboBox = new ComboBox( comboBoxItems, selectedDemoProperty, listParent, {
      buttonFill: 'rgb( 218, 236, 255 )',
      cornerRadius: options.comboBoxCornerRadius,
      xMargin: options.comboBoxItemXMargin,
      yMargin: options.comboBoxItemYMargin,
      top: options.comboBoxPosition.x,
      left: options.comboBoxPosition.y,
      tandem: options.tandem.createTandem( 'comboBox' )
    } );
    this.addChild( comboBox );

    // Make the selected demo visible
    selectedDemoProperty.link( function( demo, oldDemo ) {

      // clean up the previously selected demo
      if ( oldDemo ) {
        if ( options.cacheDemos ) {

          // make the old demo invisible
          oldDemo.node.visible = false;
        }
        else {

          // delete the old demo
          demosParent.removeChild( oldDemo.node );
          oldDemo.node.dispose();
          oldDemo.node = null;
        }
      }

      if ( demo.node ) {

        // If the selected demo has an associated node, make it visible.
        demo.node.visible = true;
      }
      else {

        // If the selected demo doesn't doesn't have an associated node, create it.
        demo.node = demo.createNode( layoutBounds, {
          tandem: options.tandem.createTandem( 'demo' + demo.label )
        } );
        demosParent.addChild( demo.node );
      }
    } );
  }

  sun.register( 'DemosScreenView', DemosScreenView );

  return inherit( ScreenView, DemosScreenView );
} );
<|endoftext|>


<commit_before>import { getInstallations } from 'testcafe-browser-tools'
import { execSync } from 'child_process'

import merge from './merge'
import generateCustomMode from './generate_custom_mode'

const getConfig = async (resolveConfig, options) => {
  if (options == null || options.constructor !== Object) {
    throw new Error('Invalid run-testcafe options')
  }

  const { functionalTestsDir, browser, customArgs, timeout } = options
  if (functionalTestsDir == null || functionalTestsDir.constructor !== String) {
    throw new Error('Options field "functionalTestsDir" must be string')
  }

  if (browser != null && browser.constructor !== String) {
    throw new Error('Options field "browser" should be string or null')
  }

  if (timeout != null && timeout.constructor !== Number) {
    throw new Error('Options field "timeout" should be number or null')
  }

  if (customArgs != null && !Array.isArray(customArgs)) {
    throw new Error('Options field "customArgs" must be array of strings')
  }

  const config = merge(resolveConfig, {
    apiHandlers: [
      {
        controller: 'resolve-runtime/lib/local/query-is-ready-handler.js',
        path: '/api/query-is-ready',
        method: 'GET'
      }
    ]
  })

  return config
}

const runAfterLaunch = async options => {
  let { functionalTestsDir, browser, customArgs, timeout } = options
  browser = browser != null ? browser : Object.keys(await getInstallations())[0]
  timeout = timeout != null ? timeout : 20000
  customArgs = customArgs != null ? customArgs : []

  try {
    return execSync(
      [
        `npx testcafe ${browser}`,
        `${functionalTestsDir}`,
        `--app-init-delay ${timeout}`,
        `--selector-timeout ${timeout}`,
        `--assertion-timeout ${timeout}`,
        `--page-load-timeout ${timeout}`,
        browser === 'remote' ? ' --qr-code' : '',
        ...customArgs
      ].join(' '),
      { stdio: 'inherit' }
    )
  } catch (e) {
    return ''
  }
}

const runTestcafeMode = async ({
  resolveConfig,
  adjustWebpackConfigs,
  functionalTestsDir,
  browser,
  customArgs,
  timeout
}) =>
  generateCustomMode(getConfig, 'query-is-ready', runAfterLaunch)(
    resolveConfig,
    {
      functionalTestsDir,
      browser,
      customArgs,
      timeout
    },
    adjustWebpackConfigs
  )

export default runTestcafeMode
<commit_msg>Fix #1325<commit_after>import { getInstallations } from 'testcafe-browser-tools'
import { execSync } from 'child_process'

import merge from './merge'
import generateCustomMode from './generate_custom_mode'

const getConfig = async (resolveConfig, options) => {
  if (options == null || options.constructor !== Object) {
    throw new Error('Invalid run-testcafe options')
  }

  const { functionalTestsDir, browser, customArgs, timeout } = options
  if (functionalTestsDir == null || functionalTestsDir.constructor !== String) {
    throw new Error('Options field "functionalTestsDir" must be string')
  }

  if (browser != null && browser.constructor !== String) {
    throw new Error('Options field "browser" should be string or null')
  }

  if (timeout != null && timeout.constructor !== Number) {
    throw new Error('Options field "timeout" should be number or null')
  }

  if (customArgs != null && !Array.isArray(customArgs)) {
    throw new Error('Options field "customArgs" must be array of strings')
  }

  const config = merge(resolveConfig, {
    apiHandlers: [
      {
        controller: 'resolve-runtime/lib/local/query-is-ready-handler.js',
        path: '/api/query-is-ready',
        method: 'GET'
      }
    ]
  })

  return config
}

const runAfterLaunch = async options => {
  let { functionalTestsDir, browser, customArgs, timeout } = options
  browser = browser != null ? browser : Object.keys(await getInstallations())[0]
  timeout = timeout != null ? timeout : 20000
  customArgs = customArgs != null ? customArgs : []

  try {
    return execSync(
      [
        `npx testcafe ${browser}`,
        `${functionalTestsDir}`,
        `--app-init-delay ${timeout}`,
        `--selector-timeout ${timeout}`,
        `--assertion-timeout ${timeout}`,
        `--page-load-timeout ${timeout}`,
        browser === 'remote' ? ' --qr-code' : '',
        ...customArgs
      ].join(' '),
      { stdio: 'inherit' }
    )
  } catch (e) {
    // eslint-disable-next-line no-throw-literal
    throw ''
  }
}

const runTestcafeMode = async ({
  resolveConfig,
  adjustWebpackConfigs,
  functionalTestsDir,
  browser,
  customArgs,
  timeout
}) =>
  generateCustomMode(getConfig, 'query-is-ready', runAfterLaunch)(
    resolveConfig,
    {
      functionalTestsDir,
      browser,
      customArgs,
      timeout
    },
    adjustWebpackConfigs
  )

export default runTestcafeMode
<|endoftext|>