<commit_before>'use strict'
const assert = require('assert')
const request = require('request')

const host1 = process.env.HOST1 || 'localhost:3000'
const host2 = process.env.HOST2 || 'localhost:3001'
const hostApi = process.env.HOST_API || 'localhost:3030'

describe('Console Log', () => {
  before(() => {
    console.log('host1', host1)
    console.log('host2', host2)
    console.log('hostApi', hostApi)
  })

  it('gets the title of page1', () => {
    const title = browser.url('http://' + host1 + '/page1.html').getTitle()
    assert.equal(title, 'HOST1')
  })

  it('gets the title of page2', () => {
    const title = browser.url('http://' + host2 + '/page2.html').getTitle()
    assert.equal(title, 'HOST2')
  })

  it('send beacon', () => {
    browser.url('http://' + host1 + '/beacon.html?' + hostApi)

    browser.call(() => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          request.get({url:'http://' + hostApi + '/last_request', timeout: 1000}, (err, res) => {
            const data = JSON.parse(res.body)
            assert.equal(data.method, 'GET')
            resolve()
          })
        }, 800)
      })
    })
  })

  it('has no SEVERE error', () => {
    browser.call(function() {
      // wait 500msec to load js
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, 500)
      })
    })
    try {
      // Because `log/types` is not webdriver specification, the exception is occured on cloud
      const errors = browser.log('browser').value
      for (var i = 0; i < errors.length; i++) {
        var err = errors[i]
        assert (err.level !== 'SEVERE', err.message)
      }
    } catch(err) { }
  })
})
<commit_msg>add type check<commit_after>'use strict'
const assert = require('assert')
const request = require('request')

const host1 = process.env.HOST1 || 'localhost:3000'
const host2 = process.env.HOST2 || 'localhost:3001'
const hostApi = process.env.HOST_API || 'localhost:3030'

describe('Console Log', () => {
  before(() => {
    console.log('host1', host1)
    console.log('host2', host2)
    console.log('hostApi', hostApi)
  })

  it('gets the title of page1', () => {
    const title = browser.url('http://' + host1 + '/page1.html').getTitle()
    assert.equal(title, 'HOST1')
  })

  it('gets the title of page2', () => {
    const title = browser.url('http://' + host2 + '/page2.html').getTitle()
    assert.equal(title, 'HOST2')
  })

  it('send beacon', () => {
    browser.url('http://' + host1 + '/beacon.html?' + hostApi)

    browser.call(() => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          request.get({url:'http://' + hostApi + '/last_request', timeout: 1000}, (err, res) => {
            var data = res.body
            console.log('data type', typeof data)
            if (typeof data === 'string') {
              assert.doesNotThrow(()=>{
                data = JSON.parse(res.body)
              })
            }
            assert.equal(data.method, 'GET')
            resolve()
          })
        }, 800)
      })
    })
  })

  it('has no SEVERE error', () => {
    browser.call(function() {
      // wait 500msec to load js
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, 500)
      })
    })
    try {
      // Because `log/types` is not webdriver specification, the exception is occured on cloud
      const errors = browser.log('browser').value
      for (var i = 0; i < errors.length; i++) {
        var err = errors[i]
        assert (err.level !== 'SEVERE', err.message)
      }
    } catch(err) { }
  })
})
<|endoftext|>


<commit_before>if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
var B = require('../').Buffer
var test = require('tape')

test('new buffer from array', function (t) {
  t.equal(
    new B([1, 2, 3]).toString(),
    '\u0001\u0002\u0003'
  )
  t.end()
})

test('new buffer from array w/ negatives', function (t) {
  t.equal(
    new B([-1, -2, -3]).toString('hex'),
    'fffefd'
  )
  t.end()
})

test('new buffer from array with mixed signed input', function (t) {
  t.equal(
    new B([-255, 255, -128, 128, 512, -512, 511, -511]).toString('hex'),
    '01ff80800000ff01'
  )
  t.end()
})

test('new buffer from string', function (t) {
  t.equal(
    new B('hey', 'utf8').toString(),
    'hey'
  )
  t.end()
})

test('new buffer from buffer', function (t) {
  var b1 = new B('asdf')
  var b2 = new B(b1)
  t.equal(b1.toString('hex'), b2.toString('hex'))
  t.end()
})

test('new buffer from Uint8Array', function (t) {
  if (typeof Uint8Array !== 'undefined') {
    var b1 = new Uint8Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Uint16Array', function (t) {
  if (typeof Uint16Array !== 'undefined') {
    var b1 = new Uint16Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Uint32Array', function (t) {
  if (typeof Uint32Array !== 'undefined') {
    var b1 = new Uint32Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Int16Array', function (t) {
  if (typeof Int16Array !== 'undefined') {
    var b1 = new Int16Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Int32Array', function (t) {
  if (typeof Int32Array !== 'undefined') {
    var b1 = new Int32Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Float32Array', function (t) {
  if (typeof Float32Array !== 'undefined') {
    var b1 = new Float32Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Float64Array', function (t) {
  if (typeof Float64Array !== 'undefined') {
    var b1 = new Float64Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from buffer.toJSON() output', function (t) {
  if (typeof JSON === 'undefined') {
    // ie6, ie7 lack support
    t.end()
    return
  }
  var buf = new B('test')
  var json = JSON.stringify(buf)
  var obj = JSON.parse(json)
  var copy = new B(obj)
  t.ok(buf.equals(copy))
  t.end()
})
<commit_msg>test: add arraybuffer tests<commit_after>if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
var B = require('../').Buffer
var test = require('tape')

test('new buffer from array', function (t) {
  t.equal(
    new B([1, 2, 3]).toString(),
    '\u0001\u0002\u0003'
  )
  t.end()
})

test('new buffer from array w/ negatives', function (t) {
  t.equal(
    new B([-1, -2, -3]).toString('hex'),
    'fffefd'
  )
  t.end()
})

test('new buffer from array with mixed signed input', function (t) {
  t.equal(
    new B([-255, 255, -128, 128, 512, -512, 511, -511]).toString('hex'),
    '01ff80800000ff01'
  )
  t.end()
})

test('new buffer from string', function (t) {
  t.equal(
    new B('hey', 'utf8').toString(),
    'hey'
  )
  t.end()
})

test('new buffer from buffer', function (t) {
  var b1 = new B('asdf')
  var b2 = new B(b1)
  t.equal(b1.toString('hex'), b2.toString('hex'))
  t.end()
})

test('new buffer from ArrayBuffer', function (t) {
  if (typeof ArrayBuffer !== 'undefined') {
    var arraybuffer = new Uint8Array([0, 1, 2, 3]).buffer
    var b = new B(arraybuffer)
    t.equal(b.length, 4)
    t.equal(b[0], 0)
    t.equal(b[1], 1)
    t.equal(b[2], 2)
    t.equal(b[3], 3)
    t.equal(b[4], undefined)
  }
  t.end()
})

test('new buffer from ArrayBuffer, shares memory', function (t) {
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    var u = new Uint8Array([0, 1, 2, 3])
    var arraybuffer = u.buffer
    var b = new B(arraybuffer)
    t.equal(b.length, 4)
    t.equal(b[0], 0)
    t.equal(b[1], 1)
    t.equal(b[2], 2)
    t.equal(b[3], 3)
    t.equal(b[4], undefined)

    // changing the Uint8Array (and thus the ArrayBuffer), changes the Buffer
    u[0] = 10
    t.equal(b[0], 10)
    u[1] = 11
    t.equal(b[1], 11)
    u[2] = 12
    t.equal(b[2], 12)
    u[3] = 13
    t.equal(b[3], 13)
  }
  t.end()
})

test('new buffer from Uint8Array', function (t) {
  if (typeof Uint8Array !== 'undefined') {
    var b1 = new Uint8Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Uint16Array', function (t) {
  if (typeof Uint16Array !== 'undefined') {
    var b1 = new Uint16Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Uint32Array', function (t) {
  if (typeof Uint32Array !== 'undefined') {
    var b1 = new Uint32Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Int16Array', function (t) {
  if (typeof Int16Array !== 'undefined') {
    var b1 = new Int16Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Int32Array', function (t) {
  if (typeof Int32Array !== 'undefined') {
    var b1 = new Int32Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Float32Array', function (t) {
  if (typeof Float32Array !== 'undefined') {
    var b1 = new Float32Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from Float64Array', function (t) {
  if (typeof Float64Array !== 'undefined') {
    var b1 = new Float64Array([0, 1, 2, 3])
    var b2 = new B(b1)
    t.equal(b1.length, b2.length)
    t.equal(b1[0], 0)
    t.equal(b1[1], 1)
    t.equal(b1[2], 2)
    t.equal(b1[3], 3)
    t.equal(b1[4], undefined)
  }
  t.end()
})

test('new buffer from buffer.toJSON() output', function (t) {
  if (typeof JSON === 'undefined') {
    // ie6, ie7 lack support
    t.end()
    return
  }
  var buf = new B('test')
  var json = JSON.stringify(buf)
  var obj = JSON.parse(json)
  var copy = new B(obj)
  t.ok(buf.equals(copy))
  t.end()
})
<|endoftext|>


<commit_before>"use strict";

cconst util = require("util");
util.inspect.defaultOptions.colors = true;
// Debug wird mit NODE_DEBUG="controller" im Environment eingeschaltet
const debug = util.debuglog("controller1");

class Controller1 extends require("../lib/controller.js") {
  constructor(param) {
    super(param);
    this.errprob = 0.0001;
    this.collector = [];

    setInterval(() => {
      //    const erg = this.checkRunning(0,2E8);
      const erg = this.checkRunning(5);

      debug("longest %d", erg.length);
      //  this.parallel += erg.length;

    }, 1000).unref();

  }
  errHandler(pos, err) {
    debug("error", err, pos);

    if (this.errcollector.size > 30) {
      return true;
    } else {
      return false;
    }
  }
  objHandler(pos, obj) { //add timing
    //debug("hier da",pos,obj);

    this.collector[pos.input.id] = obj;

  }
  endHandler() {
    if (this.errcollector.size > 30) { //throw with error
      debug("finished with error %d", this.errcollector.size);
      this.emit("ende", [...this.errcollector]);
    } else { // return the array of results
      debug("finished with gen");
      this.emit("ende", null, this.collector);
    }

  }

  *
  dataGenerator(res) {

    try {
      const iter1 = this.makeIteratorFun(res, null, this.fun);

      let first = yield* this.startAll(res, () => iter1.next(), 30000);

      debug("warte auf ende");
      const l = yield* this.waiterFinished(3000, true);
      debug("ende hier %d", l.length);

      return first.concat(l);
    } catch (err) {
      debug("error generator", err);
    }

  }

}
module.exports = Controller1;
<commit_msg>debug<commit_after>"use strict";

const util = require("util");
util.inspect.defaultOptions.colors = true;
// Debug wird mit NODE_DEBUG="controller" im Environment eingeschaltet
const debug = util.debuglog("controller1");

class Controller1 extends require("../lib/controller.js") {
  constructor(param) {
    super(param);
    this.errprob = 0.0001;
    this.collector = [];

    setInterval(() => {
      //    const erg = this.checkRunning(0,2E8);
      const erg = this.checkRunning(5);

      debug("longest %d", erg.length);
      //  this.parallel += erg.length;

    }, 1000).unref();

  }
  errHandler(pos, err) {
    debug("error", err, pos);

    if (this.errcollector.size > 30) {
      return true;
    } else {
      return false;
    }
  }
  objHandler(pos, obj) { //add timing
    //debug("hier da",pos,obj);

    this.collector[pos.input.id] = obj;

  }
  endHandler() {
    if (this.errcollector.size > 30) { //throw with error
      debug("finished with error %d", this.errcollector.size);
      this.emit("ende", [...this.errcollector]);
    } else { // return the array of results
      debug("finished with gen");
      this.emit("ende", null, this.collector);
    }

  }

  *
  dataGenerator(res) {

    try {
      const iter1 = this.makeIteratorFun(res, null, this.fun);

      let first = yield* this.startAll(res, () => iter1.next(), 30000);

      debug("warte auf ende");
      const l = yield* this.waiterFinished(3000, true);
      debug("ende hier %d", l.length);

      return first.concat(l);
    } catch (err) {
      debug("error generator", err);
    }

  }

}
module.exports = Controller1;
<|endoftext|>


<commit_before>'use strict';

var assert = require('proclaim');
var cookie = require('../lib').constructor.cookie;

describe('cookie', function() {
  beforeEach(function() {
    // Just to make sure that
    // URIError is never thrown here.
    document.cookie = 'bad=%';
  });

  afterEach(function() {
    // reset to defaults
    cookie.options({});
    document.cookie.split(';').forEach(function(entry) {
      cookie.remove(entry.split('=')[0]);
    });
  });

  describe('#get', function() {
    it('should not not get an empty cookie', function() {
      assert(cookie.get('abc') === null);
    });

    it('should get an existing cookie', function() {
      cookie.set('cookie-get', { a: 'b' });
      assert.deepEqual(cookie.get('cookie-get'), { a: 'b' });
    });

    it('should not throw an error on a malformed cookie', function() {
      document.cookie = 'cookie-bad=y';
      assert(cookie.get('cookie-bad') === null);
    });
  });

  describe('#set', function() {
    it('should set a cookie', function() {
      cookie.set('cookie-set', { a: 'b' });
      assert.deepEqual(cookie.get('cookie-set'), { a: 'b' });
    });
  });

  describe('#remove', function() {
    it('should remove a cookie', function() {
      cookie.set('cookie-remove', { a: 'b' });
      assert.deepEqual(cookie.get('cookie-remove'), { a: 'b' });
      cookie.remove('cookie-remove');
      assert(cookie.get('cookie-remove') === null);
    });
  });

  describe('#options', function() {
    it('should save options', function() {
      cookie.options({ path: '/xyz' });
      assert(cookie.options().path === '/xyz');
      assert(cookie.options().maxage === 31536000000);
    });

    it('should set the domain correctly', function() {
      cookie.options({ domain: '' });
      assert(cookie.options().domain === '');
    });

    it('should fallback to `domain=null` when it cant set the test cookie', function() {
      cookie.options({ domain: 'baz.com' });
      assert(cookie.options().domain === null);
      assert(cookie.get('ajs:test') === null);
    });

    // TODO: unskip once we don't use `window`, instead mock it :/
    it.skip('should set domain localhost to `""`', function() {
      cookie.options({});
      assert(cookie.options().domain === '');
    });
  });
});
<commit_msg>A comment doesn't hurt<commit_after>'use strict';

var assert = require('proclaim');
var cookie = require('../lib').constructor.cookie;

describe('cookie', function() {
  beforeEach(function() {
    // Just to make sure that
    // URIError is never thrown here.
    document.cookie = 'bad=%';
  });

  afterEach(function() {
    // reset to defaults
    cookie.options({});
    // remove all cookies
    document.cookie.split(';').forEach(function(entry) {
      cookie.remove(entry.split('=')[0]);
    });
  });

  describe('#get', function() {
    it('should not not get an empty cookie', function() {
      assert(cookie.get('abc') === null);
    });

    it('should get an existing cookie', function() {
      cookie.set('cookie-get', { a: 'b' });
      assert.deepEqual(cookie.get('cookie-get'), { a: 'b' });
    });

    it('should not throw an error on a malformed cookie', function() {
      document.cookie = 'cookie-bad=y';
      assert(cookie.get('cookie-bad') === null);
    });
  });

  describe('#set', function() {
    it('should set a cookie', function() {
      cookie.set('cookie-set', { a: 'b' });
      assert.deepEqual(cookie.get('cookie-set'), { a: 'b' });
    });
  });

  describe('#remove', function() {
    it('should remove a cookie', function() {
      cookie.set('cookie-remove', { a: 'b' });
      assert.deepEqual(cookie.get('cookie-remove'), { a: 'b' });
      cookie.remove('cookie-remove');
      assert(cookie.get('cookie-remove') === null);
    });
  });

  describe('#options', function() {
    it('should save options', function() {
      cookie.options({ path: '/xyz' });
      assert(cookie.options().path === '/xyz');
      assert(cookie.options().maxage === 31536000000);
    });

    it('should set the domain correctly', function() {
      cookie.options({ domain: '' });
      assert(cookie.options().domain === '');
    });

    it('should fallback to `domain=null` when it cant set the test cookie', function() {
      cookie.options({ domain: 'baz.com' });
      assert(cookie.options().domain === null);
      assert(cookie.get('ajs:test') === null);
    });

    // TODO: unskip once we don't use `window`, instead mock it :/
    it.skip('should set domain localhost to `""`', function() {
      cookie.options({});
      assert(cookie.options().domain === '');
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

Sidebar.Geometry.BoxGeometry = function ( editor, object ) {

	var signals = editor.signals;

	var container = new UI.Row();

	var geometry = object.geometry;
	var parameters = geometry.parameters;

	// width

	var widthRow = new UI.Row();
	var width = new UI.Number( parameters.width ).onChange( update );

	widthRow.add( new UI.Text( 'Width' ).setWidth( '90px' ) );
	widthRow.add( width );

	container.add( widthRow );

	// height

	var heightRow = new UI.Row();
	var height = new UI.Number( parameters.height ).onChange( update );

	heightRow.add( new UI.Text( 'Height' ).setWidth( '90px' ) );
	heightRow.add( height );

	container.add( heightRow );

	// depth

	var depthRow = new UI.Row();
	var depth = new UI.Number( parameters.depth ).onChange( update );

	depthRow.add( new UI.Text( 'Depth' ).setWidth( '90px' ) );
	depthRow.add( depth );

	container.add( depthRow );

	// widthSegments

	var widthSegmentsRow = new UI.Row();
	var widthSegments = new UI.Integer( parameters.widthSegments ).setRange( 1, Infinity ).onChange( update );

	widthSegmentsRow.add( new UI.Text( 'Width segments' ).setWidth( '90px' ) );
	widthSegmentsRow.add( widthSegments );

	container.add( widthSegmentsRow );

	// heightSegments

	var heightSegmentsRow = new UI.Row();
	var heightSegments = new UI.Integer( parameters.heightSegments ).setRange( 1, Infinity ).onChange( update );

	heightSegmentsRow.add( new UI.Text( 'Height segments' ).setWidth( '90px' ) );
	heightSegmentsRow.add( heightSegments );

	container.add( heightSegmentsRow );

	// depthSegments

	var depthSegmentsRow = new UI.Row();
	var depthSegments = new UI.Integer( parameters.depthSegments ).setRange( 1, Infinity ).onChange( update );

	depthSegmentsRow.add( new UI.Text( 'Height segments' ).setWidth( '90px' ) );
	depthSegmentsRow.add( depthSegments );

	container.add( depthSegmentsRow );

	//

	function update() {

		editor.execute( new SetGeometryCommand( object, new THREE[ geometry.type ](
			width.getValue(),
			height.getValue(),
			depth.getValue(),
			widthSegments.getValue(),
			heightSegments.getValue(),
			depthSegments.getValue()
		) ) );

	}

	return container;

};

Sidebar.Geometry.BoxBufferGeometry = Sidebar.Geometry.BoxGeometry;
<commit_msg>Editor: Correct Typo in Sidebar.Geometry.BoxGeometry<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

Sidebar.Geometry.BoxGeometry = function ( editor, object ) {

	var signals = editor.signals;

	var container = new UI.Row();

	var geometry = object.geometry;
	var parameters = geometry.parameters;

	// width

	var widthRow = new UI.Row();
	var width = new UI.Number( parameters.width ).onChange( update );

	widthRow.add( new UI.Text( 'Width' ).setWidth( '90px' ) );
	widthRow.add( width );

	container.add( widthRow );

	// height

	var heightRow = new UI.Row();
	var height = new UI.Number( parameters.height ).onChange( update );

	heightRow.add( new UI.Text( 'Height' ).setWidth( '90px' ) );
	heightRow.add( height );

	container.add( heightRow );

	// depth

	var depthRow = new UI.Row();
	var depth = new UI.Number( parameters.depth ).onChange( update );

	depthRow.add( new UI.Text( 'Depth' ).setWidth( '90px' ) );
	depthRow.add( depth );

	container.add( depthRow );

	// widthSegments

	var widthSegmentsRow = new UI.Row();
	var widthSegments = new UI.Integer( parameters.widthSegments ).setRange( 1, Infinity ).onChange( update );

	widthSegmentsRow.add( new UI.Text( 'Width segments' ).setWidth( '90px' ) );
	widthSegmentsRow.add( widthSegments );

	container.add( widthSegmentsRow );

	// heightSegments

	var heightSegmentsRow = new UI.Row();
	var heightSegments = new UI.Integer( parameters.heightSegments ).setRange( 1, Infinity ).onChange( update );

	heightSegmentsRow.add( new UI.Text( 'Height segments' ).setWidth( '90px' ) );
	heightSegmentsRow.add( heightSegments );

	container.add( heightSegmentsRow );

	// depthSegments

	var depthSegmentsRow = new UI.Row();
	var depthSegments = new UI.Integer( parameters.depthSegments ).setRange( 1, Infinity ).onChange( update );

	depthSegmentsRow.add( new UI.Text( 'Depth segments' ).setWidth( '90px' ) );
	depthSegmentsRow.add( depthSegments );

	container.add( depthSegmentsRow );

	//

	function update() {

		editor.execute( new SetGeometryCommand( object, new THREE[ geometry.type ](
			width.getValue(),
			height.getValue(),
			depth.getValue(),
			widthSegments.getValue(),
			heightSegments.getValue(),
			depthSegments.getValue()
		) ) );

	}

	return container;

};

Sidebar.Geometry.BoxBufferGeometry = Sidebar.Geometry.BoxGeometry;
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const JsonML = require('jsonml.js/lib/utils');
const Prism = require('node-prismjs');
const pkgPath = path.join(process.cwd(), 'package.json');
const pkgName = require(pkgPath).name;

const nunjucks = require('nunjucks');
nunjucks.configure({ autoescape: false });

const ts = require('typescript');

const babel = require('babel-core');
const babelrc = {
  presets: ['es2015', 'react'].map(m =>
     require.resolve(`babel-preset-${m}`)
  ),
};

const tmpl = fs.readFileSync(path.join(__dirname, 'template.html')).toString();

function isStyleTag(node) {
  return node && JsonML.getTagName(node) === 'style';
}

function getCode(node) {
  return JsonML.getChildren(
    JsonML.getChildren(node)[0]
  )[0];
}

function getChineseIntroStart(contentChildren) {
  return contentChildren.findIndex(node =>
     JsonML.getTagName(node) === 'h2' &&
      JsonML.getChildren(node)[0] === 'zh-CN'
  );
}

function getEnglishIntroStart(contentChildren) {
  return contentChildren.findIndex(node =>
     JsonML.getTagName(node) === 'h2' &&
      JsonML.getChildren(node)[0] === 'en-US'
  );
}

function getCodeIndex(contentChildren) {
  return contentChildren.findIndex(node =>
     JsonML.getTagName(node) === 'pre' &&
      JsonML.getAttributes(node).lang === 'jsx'
  );
}

function getSourceCodeObject(filename, contentChildren, codeIndex) {
  if (codeIndex > -1) {
    return {
      isES6: true,
      code: getCode(contentChildren[codeIndex]),
    };
  }

  return {
    isTS: true,
    code: fs.readFileSync(path.join(process.cwd(), fileName.replace(/\.md$/i, '.tsx'))).toString(),
  };
}

const componentsPath = path.join(process.cwd(), 'components');
function getPreview(sourceCode) {
  const preview = [
    'pre', { lang: '__react' },
  ];
  preview.push([
    'code',
    sourceCode.replace(`${pkgName}/lib`, componentsPath),
  ]);
  return preview;
}

function getStyleNode(contentChildren) {
  return contentChildren.filter(node =>
     isStyleTag(node) ||
      (JsonML.getTagName(node) === 'pre' && JsonML.getAttributes(node).lang === 'css')
  )[0];
}

module.exports = (markdownData, isBuild) => {
  const meta = markdownData.meta;
  meta.id = meta.filename.replace(/\.md$/, '').replace(/\//g, '-');
  // Should throw debugging demo while publish.
  if (isBuild && meta.debug) {
    return { meta: {} };
  }

  // Update content of demo.
  const contentChildren = JsonML.getChildren(markdownData.content);
  const chineseIntroStart = getChineseIntroStart(contentChildren);
  const englishIntroStart = getEnglishIntroStart(contentChildren);
  const codeIndex = getCodeIndex(contentChildren);
  const introEnd = codeIndex === -1 ? contentChildren.length : codeIndex;
  if (chineseIntroStart > -1 /* equal to englishIntroStart > -1 */) {
    markdownData.content = {
      'zh-CN': contentChildren.slice(chineseIntroStart + 1, englishIntroStart),
      'en-US': contentChildren.slice(englishIntroStart + 1, introEnd),
    };
  } else {
    markdownData.content = contentChildren.slice(0, introEnd);
  }

  const sourceCodeObject = getSourceCodeObject(meta.filename, contentChildren, codeIndex);
  if (sourceCodeObject.isES6) {
    markdownData.highlightedCode = contentChildren[codeIndex].slice(0, 2);
    markdownData.preview = getPreview(sourceCodeObject.code);
  } else {
    const es6Code = ts.transpileModule(sourceCodeObject.code, {
      compilerOptions: {
        jsx: 'preserve',
        target: 'es6'
      },
    });
    markdownData.highlightedCode = {
      es6: Prism.highlight(es6Code, Prism.languages.jsx),
      ts: Prism.highlight(sourceCodeObject.code, Prism.languages.typescript),
    };
    markdownData.preview = getPreview(es6Code);
  }

  // Add style node to markdown data.
  const styleNode = getStyleNode(contentChildren);
  if (isStyleTag(styleNode)) {
    markdownData.style = JsonML.getChildren(styleNode)[0];
  } else if (styleNode) {
    const styleTag = contentChildren.filter(isStyleTag)[0];
    markdownData.style = getCode(styleNode) + (styleTag ? JsonML.getChildren(styleTag)[0] : '');
    markdownData.highlightedStyle = JsonML.getAttributes(styleNode).highlighted;
  }

  if (meta.iframe) {
    const html = nunjucks.renderString(tmpl, {
      id: meta.id,
      style: markdownData.style,
      script: babel.transform(getCode(markdownData.preview), babelrc).code,
    });
    const fileName = `demo-${Math.random()}.html`;
    fs.writeFile(path.join(process.cwd(), '_site', fileName), html);
    markdownData.src = path.join('/', fileName);
  }

  return markdownData;
};
<commit_msg>fix: should work..<commit_after>const fs = require('fs');
const path = require('path');
const JsonML = require('jsonml.js/lib/utils');
const Prism = require('node-prismjs');
const pkgPath = path.join(process.cwd(), 'package.json');
const pkgName = require(pkgPath).name;

const nunjucks = require('nunjucks');
nunjucks.configure({ autoescape: false });

const ts = require('typescript');

const babel = require('babel-core');
const babelrc = {
  presets: ['es2015', 'react'].map(m =>
     require.resolve(`babel-preset-${m}`)
  ),
};

const tmpl = fs.readFileSync(path.join(__dirname, 'template.html')).toString();

function isStyleTag(node) {
  return node && JsonML.getTagName(node) === 'style';
}

function getCode(node) {
  return JsonML.getChildren(
    JsonML.getChildren(node)[0]
  )[0];
}

function getChineseIntroStart(contentChildren) {
  return contentChildren.findIndex(node =>
     JsonML.getTagName(node) === 'h2' &&
      JsonML.getChildren(node)[0] === 'zh-CN'
  );
}

function getEnglishIntroStart(contentChildren) {
  return contentChildren.findIndex(node =>
     JsonML.getTagName(node) === 'h2' &&
      JsonML.getChildren(node)[0] === 'en-US'
  );
}

function getCodeIndex(contentChildren) {
  return contentChildren.findIndex(node =>
     JsonML.getTagName(node) === 'pre' &&
      JsonML.getAttributes(node).lang === 'jsx'
  );
}

function getSourceCodeObject(filename, contentChildren, codeIndex) {
  if (codeIndex > -1) {
    return {
      isES6: true,
      code: getCode(contentChildren[codeIndex]),
    };
  }

  return {
    isTS: true,
    code: fs.readFileSync(path.join(process.cwd(), filename.replace(/\.md$/i, '.tsx'))).toString(),
  };
}

const componentsPath = path.join(process.cwd(), 'components');
function getPreview(sourceCode) {
  const preview = [
    'pre', { lang: '__react' },
  ];
  preview.push([
    'code',
    sourceCode.replace(`${pkgName}/lib`, componentsPath),
  ]);
  return preview;
}

function getStyleNode(contentChildren) {
  return contentChildren.filter(node =>
     isStyleTag(node) ||
      (JsonML.getTagName(node) === 'pre' && JsonML.getAttributes(node).lang === 'css')
  )[0];
}

module.exports = (markdownData, isBuild) => {
  const meta = markdownData.meta;
  meta.id = meta.filename.replace(/\.md$/, '').replace(/\//g, '-');
  // Should throw debugging demo while publish.
  if (isBuild && meta.debug) {
    return { meta: {} };
  }

  // Update content of demo.
  const contentChildren = JsonML.getChildren(markdownData.content);
  const chineseIntroStart = getChineseIntroStart(contentChildren);
  const englishIntroStart = getEnglishIntroStart(contentChildren);
  const codeIndex = getCodeIndex(contentChildren);
  const introEnd = codeIndex === -1 ? contentChildren.length : codeIndex;
  if (chineseIntroStart > -1 /* equal to englishIntroStart > -1 */) {
    markdownData.content = {
      'zh-CN': contentChildren.slice(chineseIntroStart + 1, englishIntroStart),
      'en-US': contentChildren.slice(englishIntroStart + 1, introEnd),
    };
  } else {
    markdownData.content = contentChildren.slice(0, introEnd);
  }

  const sourceCodeObject = getSourceCodeObject(meta.filename, contentChildren, codeIndex);
  if (sourceCodeObject.isES6) {
    markdownData.highlightedCode = contentChildren[codeIndex].slice(0, 2);
    markdownData.preview = getPreview(sourceCodeObject.code);
  } else {
    const es6Code = ts.transpileModule(sourceCodeObject.code, {
      compilerOptions: {
        jsx: 'preserve',
        target: 'es6'
      },
    }).outputText;;
    markdownData.highlightedCode = {
      es6: Prism.highlight(es6Code, Prism.languages.jsx),
      ts: Prism.highlight(sourceCodeObject.code, Prism.languages.typescript),
    };
    markdownData.preview = getPreview(es6Code);
  }

  // Add style node to markdown data.
  const styleNode = getStyleNode(contentChildren);
  if (isStyleTag(styleNode)) {
    markdownData.style = JsonML.getChildren(styleNode)[0];
  } else if (styleNode) {
    const styleTag = contentChildren.filter(isStyleTag)[0];
    markdownData.style = getCode(styleNode) + (styleTag ? JsonML.getChildren(styleTag)[0] : '');
    markdownData.highlightedStyle = JsonML.getAttributes(styleNode).highlighted;
  }

  if (meta.iframe) {
    const html = nunjucks.renderString(tmpl, {
      id: meta.id,
      style: markdownData.style,
      script: babel.transform(getCode(markdownData.preview), babelrc).code,
    });
    const fileName = `demo-${Math.random()}.html`;
    fs.writeFile(path.join(process.cwd(), '_site', fileName), html);
    markdownData.src = path.join('/', fileName);
  }

  return markdownData;
};
<|endoftext|>


<commit_before>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    http = require('http-browser'),
    $q = require('q-promise'),
    cssHack = require('../tools/css-hack');

function checkout (options) {

  options = options || {};
  var baseUrl = ( options.host === 'location' ? location.origin : options.host ) || 'https://aplazame.com/static/checkout/';

  if( !/\/$/.test(baseUrl) ) {
    baseUrl += '/';
  }

  var iframeSrc = baseUrl + 'iframe.html?' + new Date().getTime(),
      errorLoading = false,
      tmpOverlay = document.createElement('div'),
      cssOverlay = cssHack('overlay'),
      cssBlur = cssHack('blur'),
      cssLogo = cssHack('logo'),
      cssModal = cssHack('modal');

  tmpOverlay.className = 'aplazame-overlay aplazame-overlay-show';

  cssOverlay.hack(true);
  cssLogo.hack(true);
  cssBlur.hack(true);

  setTimeout(function () {
    if( !errorLoading ) {
      _.addClass(document.body, 'aplazame-blur');
    }
  }, 0);

  tmpOverlay.innerHTML = '

' +
  require('./loading-svg') + '

Cargando pasarela de pago...

';

  document.body.appendChild(tmpOverlay);

  var loadingText = tmpOverlay.querySelector('.aplazame-overlay-loading-text');

  setTimeout(function () {
    if( !errorLoading ) {
      tmpOverlay.querySelector('.logo-aplazame').className += ' animate';
    }
  }, 200);

  options.api = _.copy(api);

  return http( iframeSrc ).then(function (response) {
      var iframeHtml = response.data.replace(//, '<base href="' + baseUrl + '" />'),
          iframe = _.getIFrame({
            top: 0,
            left: 0,
            width: '100%',
            height: '0',
            background: 'transparent'
          }),
          httpCheckout = function () {
            var started = Date.now();
            return http.apply(this, arguments).then(function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-success',
                started: started,
                elapsed: Date.now() - started,
                response: http.plainResponse(response)
              }, '*');
              return response;
            }, function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-error',
                started: started,
                elapsed: Date.now() - started,
                response: http.plainResponse(response)
              }, '*');
              throw response;
            });
          };

      iframe.className = 'aplazame-modal';

      document.body.appendChild(iframe);
      iframe.src = iframeSrc;

      if( !options.merchant ) {
        throw new Error('missing merchant parameters');
      }

      if( 'sandbox' in options.merchant ) {
        api.sandbox = options.merchant.sandbox;
      }

      if( !options.merchant.public_api_key ) {
        if( api.publicKey ) {
          options.merchant.public_api_key = api.publicKey;
        } else {
          throw new Error('missing public key');
        }
      }

      options.origin = {
        href: location.href,
        host: location.host,
        protocol: location.protocol,
        origin: location.origin
      };

      _.onMessage('checkout', function (e, message) {

        switch( message.event ) {
          case 'merchant':
            iframe.style.display = null;
            e.source.postMessage({
              checkout: options
            }, '*');
            break;
          case 'show-iframe':
            _.removeClass(iframe, 'hide');
            cssModal.hack(true);
            cssOverlay.hack(false);
            document.body.removeChild(tmpOverlay);
            break;
          case 'loading-text':
            loadingText.textContent = message.text;
            break;
          case 'drop-blur':
            _.removeClass(document.body, 'aplazame-blur');
            _.addClass(document.body, 'aplazame-unblur');
            setTimeout(function () {
              document.head.removeChild(cssBlur);
            }, 600);
            break;
          case 'confirm':
          case 'success':
            _.log('aplazame.checkout:confirm', message);

            httpCheckout( options.merchant.confirmation_url, {
              method: 'post',
              contentType: 'application/json',
              data: message.data,
              params: _.extend(message.params || {}, {
                order_id: message.data.checkout_token,
                checkout_token: message.data.checkout_token
              })
            }).then(function (response) {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'success',
                response: http.plainResponse(response)
              }, '*');
            }, function () {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'error',
                response: http.plainResponse(response)
              }, '*');
            });
            // confirmation_url
            break;
          case 'close':
            if( iframe ) {
              document.body.removeChild(iframe);
              cssModal.hack(false);
              iframe = null;

              switch( message.result ) {
                case 'dismiss':
                  location.replace(options.merchant.checkout_url || '/');
                  break;
                case 'success':
                  location.replace(options.merchant.success_url);
                  break;
                case 'cancel':
                  location.replace(options.merchant.cancel_url);
                  break;
              }
            }
            break;
        }

      });

    }).catch(function (reason) {
      // throw new Error('can not connect to ' + baseUrl);
      errorLoading = true;

      console.error('Aplazame ' + reason);

      _.removeClass(tmpOverlay.querySelector('.logo-aplazame'), 'animate');
      loadingText.innerHTML = '
Error cargando pasarela de pago

soporte@aplazame.com
';
      loadingText.style.lineHeight = '1.5';

      (options.onError || _.noop)(reason);
    });

}

module.exports = checkout;
<commit_msg>added support for merchant.onSuccess, merchant.onCancel and merchant.onDismiss<commit_after>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    http = require('http-browser'),
    $q = require('q-promise'),
    cssHack = require('../tools/css-hack');

function checkout (options) {

  options = options || {};
  var baseUrl = ( options.host === 'location' ? location.origin : options.host ) || 'https://aplazame.com/static/checkout/';

  if( !/\/$/.test(baseUrl) ) {
    baseUrl += '/';
  }

  var iframeSrc = baseUrl + 'iframe.html?' + new Date().getTime(),
      errorLoading = false,
      tmpOverlay = document.createElement('div'),
      cssOverlay = cssHack('overlay'),
      cssBlur = cssHack('blur'),
      cssLogo = cssHack('logo'),
      cssModal = cssHack('modal');

  tmpOverlay.className = 'aplazame-overlay aplazame-overlay-show';

  cssOverlay.hack(true);
  cssLogo.hack(true);
  cssBlur.hack(true);

  setTimeout(function () {
    if( !errorLoading ) {
      _.addClass(document.body, 'aplazame-blur');
    }
  }, 0);

  tmpOverlay.innerHTML = '

' +
  require('./loading-svg') + '

Cargando pasarela de pago...

';

  document.body.appendChild(tmpOverlay);

  var loadingText = tmpOverlay.querySelector('.aplazame-overlay-loading-text');

  setTimeout(function () {
    if( !errorLoading ) {
      tmpOverlay.querySelector('.logo-aplazame').className += ' animate';
    }
  }, 200);

  options.api = _.copy(api);

  return http( iframeSrc ).then(function (response) {
      var iframeHtml = response.data.replace(//, '<base href="' + baseUrl + '" />'),
          iframe = _.getIFrame({
            top: 0,
            left: 0,
            width: '100%',
            height: '0',
            background: 'transparent'
          }),
          httpCheckout = function () {
            var started = Date.now();
            return http.apply(this, arguments).then(function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-success',
                started: started,
                elapsed: Date.now() - started,
                response: http.plainResponse(response)
              }, '*');
              return response;
            }, function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-error',
                started: started,
                elapsed: Date.now() - started,
                response: http.plainResponse(response)
              }, '*');
              throw response;
            });
          };

      iframe.className = 'aplazame-modal';

      document.body.appendChild(iframe);
      iframe.src = iframeSrc;

      if( !options.merchant ) {
        throw new Error('missing merchant parameters');
      }

      if( 'sandbox' in options.merchant ) {
        api.sandbox = options.merchant.sandbox;
      }

      if( !options.merchant.public_api_key ) {
        if( api.publicKey ) {
          options.merchant.public_api_key = api.publicKey;
        } else {
          throw new Error('missing public key');
        }
      }

      options.origin = {
        href: location.href,
        host: location.host,
        protocol: location.protocol,
        origin: location.origin
      };

      _.onMessage('checkout', function (e, message) {

        switch( message.event ) {
          case 'merchant':
            iframe.style.display = null;
            e.source.postMessage({
              checkout: options
            }, '*');
            break;
          case 'show-iframe':
            _.removeClass(iframe, 'hide');
            cssModal.hack(true);
            cssOverlay.hack(false);
            document.body.removeChild(tmpOverlay);
            break;
          case 'loading-text':
            loadingText.textContent = message.text;
            break;
          case 'drop-blur':
            _.removeClass(document.body, 'aplazame-blur');
            _.addClass(document.body, 'aplazame-unblur');
            setTimeout(function () {
              document.head.removeChild(cssBlur);
            }, 600);
            break;
          case 'confirm':
          case 'success':
            _.log('aplazame.checkout:confirm', message);

            httpCheckout( options.merchant.confirmation_url, {
              method: 'post',
              contentType: 'application/json',
              data: message.data,
              params: _.extend(message.params || {}, {
                order_id: message.data.checkout_token,
                checkout_token: message.data.checkout_token
              })
            }).then(function (response) {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'success',
                response: http.plainResponse(response)
              }, '*');
            }, function () {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'error',
                response: http.plainResponse(response)
              }, '*');
            });
            // confirmation_url
            break;
          case 'close':
            if( iframe ) {
              document.body.removeChild(iframe);
              cssModal.hack(false);
              iframe = null;

              switch( message.result ) {
                case 'dismiss':
                  if( typeof options.merchant.onDismiss === 'function' ) {
                    options.merchant.onDismiss();
                  } else {
                    location.replace(options.merchant.checkout_url || '/');
                  }
                  break;
                case 'success':
                  if( typeof options.merchant.onSuccess === 'function' ) {
                    options.merchant.onSuccess();
                  } else if( !options.merchant.success_url ) {
                    throw new Error('success_url missing');
                  } else {
                    location.replace(options.merchant.success_url);
                  }
                  break;
                case 'cancel':
                  if( typeof options.merchant.onCancel === 'function' ) {
                    options.merchant.onCancel();
                  } else if( !options.merchant.cancel_url ) {
                    throw new Error('cancel_url missing');
                  } else {
                    location.replace(options.merchant.cancel_url);
                  }
                  break;
              }
            }
            break;
        }

      });

    }).catch(function (reason) {
      // throw new Error('can not connect to ' + baseUrl);
      errorLoading = true;

      console.error('Aplazame ' + reason);

      _.removeClass(tmpOverlay.querySelector('.logo-aplazame'), 'animate');
      loadingText.innerHTML = '
Error cargando pasarela de pago

soporte@aplazame.com
';
      loadingText.style.lineHeight = '1.5';

      (options.onError || _.noop)(reason);
    });

}

module.exports = checkout;
<|endoftext|>


<commit_before>/** @jsx React.DOM */

var React = require('react'),
	Field = require('../field'),
	pikaday = require('pikaday'),
	moment = require('moment');

module.exports = Field.create({

	supports: {
		focusTarget: 'dateInput'
	},

	// default formats
	inputFormat: 'YYYY-MM-DD',
	noEditFormat: 'Do MMM YYYY',

	getInitialState: function() {
		return {
			value: this.props.value ? moment(this.props.value).format(this.inputFormat) : ''
		};
	},

	componentDidMount: function() {
		var _this = this;

		// just return if noedit is enabled
		if (this.props.noedit) {
			return;
		}

		// add date picker
		this.picker = new Pikaday({
			field: this.refs.dateInput.getDOMNode(),
			onSelect: function(date) {
				format: this.inputFormat,
				_this.setDate(_this.picker.toString());
			}
		});

	},
	componentWillUnmount: function() {
		// clean up
		this.picker.destroy();
	},

	// TODO: Move isValid() so we can share with server-side code
	isValid: function(value) {
		return moment(value, this.inputFormat).isValid();
	},

	// TODO: Move format() so we can share with server-side code
	format: function(dateValue, format) {
		format = format || this.inputFormat;
		return dateValue ? moment(this.props.dateValue).format(format) : '';
	},

	setDate: function(dateValue) {
		this.setState({	value: dateValue	});
		this.props.onChange({
			path: this.props.path,
			value: this.isValid(dateValue) ? moment(dateValue, this.inputFormat).toISOString() : null
		});
	},

	setToday: function() {
		this.setDate(moment().format(this.inputFormat));
	},

	valueChanged: function(event) {
		this.setDate(event.target.value);
	},

	renderUI: function() {

		var input, fieldClassName = 'field-ui', noeditFormat, value;

		if (this.props.noedit) {
			input = (

{this.format(this.props.value, this.props.formatString || this.noEditFormat)}

			);
		} else {
			input = (

					<input type="text" name={this.props.path} ref="dateInput" value={this.state.value} onChange={this.valueChanged} autoComplete="off" className="form-control" />
					Today

			);
		}

		return (

				{this.props.label}
				{input}

		);
	}

});
<commit_msg>removed unused vars<commit_after>/** @jsx React.DOM */

var React = require('react'),
	Field = require('../field'),
	pikaday = require('pikaday'),
	moment = require('moment');

module.exports = Field.create({

	supports: {
		focusTarget: 'dateInput'
	},

	// default formats
	inputFormat: 'YYYY-MM-DD',
	noEditFormat: 'Do MMM YYYY',

	getInitialState: function() {
		return {
			value: this.props.value ? moment(this.props.value).format(this.inputFormat) : ''
		};
	},

	componentDidMount: function() {
		var _this = this;

		// just return if noedit is enabled
		if (this.props.noedit) {
			return;
		}

		// add date picker
		this.picker = new Pikaday({
			field: this.refs.dateInput.getDOMNode(),
			onSelect: function(date) {
				format: this.inputFormat,
				_this.setDate(_this.picker.toString());
			}
		});

	},
	componentWillUnmount: function() {
		// clean up
		this.picker.destroy();
	},

	// TODO: Move isValid() so we can share with server-side code
	isValid: function(value) {
		return moment(value, this.inputFormat).isValid();
	},

	// TODO: Move format() so we can share with server-side code
	format: function(dateValue, format) {
		format = format || this.inputFormat;
		return dateValue ? moment(this.props.dateValue).format(format) : '';
	},

	setDate: function(dateValue) {
		this.setState({	value: dateValue	});
		this.props.onChange({
			path: this.props.path,
			value: this.isValid(dateValue) ? moment(dateValue, this.inputFormat).toISOString() : null
		});
	},

	setToday: function() {
		this.setDate(moment().format(this.inputFormat));
	},

	valueChanged: function(event) {
		this.setDate(event.target.value);
	},

	renderUI: function() {

		var input, fieldClassName = 'field-ui';

		if (this.props.noedit) {
			input = (

{this.format(this.props.value, this.props.formatString || this.noEditFormat)}

			);
		} else {
			input = (

					<input type="text" name={this.props.path} ref="dateInput" value={this.state.value} onChange={this.valueChanged} autoComplete="off" className="form-control" />
					Today

			);
		}

		return (

				{this.props.label}
				{input}

		);
	}

});
<|endoftext|>


<commit_before>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 */
'use strict';

var React = require('react-native');
var {
  Image,
  ListView,
  TouchableHighlight,
  StyleSheet,
  RecyclerViewBackedScrollView,
  Text,
  View,
} = React;

var UIExplorerPage = require('./UIExplorerPage');

var ListViewSimpleExample = React.createClass({
  statics: {
    title: '<ListView> - Simple',
    description: 'Performant, scrollable list of data.'
  },

  getInitialState: function() {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows(this._genRows({})),
    };
  },

  _pressData: ({}: {[key: number]: boolean}),

  componentWillMount: function() {
    this._pressData = {};
  },

  render: function() {
    return (
      <UIExplorerPage
        title={this.props.navigator ? null : '<ListView> - Simple'}
        noSpacer={true}
        noScroll={true}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          renderScrollComponent={props => <RecyclerViewBackedScrollView {...props} />}
        />
      </UIExplorerPage>
    );
  },

  _renderRow: function(rowData: string, sectionID: number, rowID: number) {
    var rowHash = Math.abs(hashCode(rowData));
    var imgSource = THUMB_URLS[rowHash % THUMB_URLS.length];
    return (
      <TouchableHighlight onPress={() => this._pressRow(rowID)}>
        <View>
          <View style={styles.row}>
            <Image style={styles.thumb} source={imgSource} />
            <Text style={styles.text}>
              {rowData + ' - ' + LOREM_IPSUM.substr(0, rowHash % 301 + 10)}
            </Text>
          </View>
          <View style={styles.separator} />
        </View>
      </TouchableHighlight>
    );
  },

  _genRows: function(pressData: {[key: number]: boolean}): Array<string> {
    var dataBlob = [];
    for (var ii = 0; ii < 100; ii++) {
      var pressedText = pressData[ii] ? ' (pressed)' : '';
      dataBlob.push('Row ' + ii + pressedText);
    }
    return dataBlob;
  },

  _pressRow: function(rowID: number) {
    this._pressData[rowID] = !this._pressData[rowID];
    this.setState({dataSource: this.state.dataSource.cloneWithRows(
      this._genRows(this._pressData)
    )});
  },
});

var THUMB_URLS = [
  require('./Thumbnails/like.png'),
  require('./Thumbnails/dislike.png'),
  require('./Thumbnails/call.png'),
  require('./Thumbnails/fist.png'),
  require('./Thumbnails/bandaged.png'),
  require('./Thumbnails/flowers.png'),
  require('./Thumbnails/heart.png'),
  require('./Thumbnails/liking.png'),
  require('./Thumbnails/party.png'),
  require('./Thumbnails/poke.png'),
  require('./Thumbnails/superlike.png'),
  require('./Thumbnails/victory.png'),
  ];
var LOREM_IPSUM = 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.';

/* eslint no-bitwise: 0 */
var hashCode = function(str) {
  var hash = 15;
  for (var ii = str.length - 1; ii >= 0; ii--) {
    hash = ((hash << 5) - hash) + str.charCodeAt(ii);
  }
  return hash;
};

var styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 10,
    backgroundColor: '#F6F6F6',
  },
  separator: {
    height: 1,
    backgroundColor: '#CCCCCC',
  },
  thumb: {
    width: 64,
    height: 64,
  },
  text: {
    flex: 1,
  },
});

module.exports = ListViewSimpleExample;
<commit_msg>Use renderSeparator in List View Example<commit_after>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 */
'use strict';

var React = require('react-native');
var {
  Image,
  ListView,
  TouchableHighlight,
  StyleSheet,
  RecyclerViewBackedScrollView,
  Text,
  View,
} = React;

var UIExplorerPage = require('./UIExplorerPage');

var ListViewSimpleExample = React.createClass({
  statics: {
    title: '<ListView> - Simple',
    description: 'Performant, scrollable list of data.'
  },

  getInitialState: function() {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows(this._genRows({})),
    };
  },

  _pressData: ({}: {[key: number]: boolean}),

  componentWillMount: function() {
    this._pressData = {};
  },

  render: function() {
    return (
      <UIExplorerPage
        title={this.props.navigator ? null : '<ListView> - Simple'}
        noSpacer={true}
        noScroll={true}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          renderScrollComponent={props => <RecyclerViewBackedScrollView {...props} />}
          renderSeparator={(sectionID, rowID) => <View key={`${sectionID}-${rowID}`} style={styles.separator} />}
        />
      </UIExplorerPage>
    );
  },

  _renderRow: function(rowData: string, sectionID: number, rowID: number) {
    var rowHash = Math.abs(hashCode(rowData));
    var imgSource = THUMB_URLS[rowHash % THUMB_URLS.length];
    return (
      <TouchableHighlight onPress={() => this._pressRow(rowID)}>
        <View>
          <View style={styles.row}>
            <Image style={styles.thumb} source={imgSource} />
            <Text style={styles.text}>
              {rowData + ' - ' + LOREM_IPSUM.substr(0, rowHash % 301 + 10)}
            </Text>
          </View>
        </View>
      </TouchableHighlight>
    );
  },

  _genRows: function(pressData: {[key: number]: boolean}): Array<string> {
    var dataBlob = [];
    for (var ii = 0; ii < 100; ii++) {
      var pressedText = pressData[ii] ? ' (pressed)' : '';
      dataBlob.push('Row ' + ii + pressedText);
    }
    return dataBlob;
  },

  _pressRow: function(rowID: number) {
    this._pressData[rowID] = !this._pressData[rowID];
    this.setState({dataSource: this.state.dataSource.cloneWithRows(
      this._genRows(this._pressData)
    )});
  },
});

var THUMB_URLS = [
  require('./Thumbnails/like.png'),
  require('./Thumbnails/dislike.png'),
  require('./Thumbnails/call.png'),
  require('./Thumbnails/fist.png'),
  require('./Thumbnails/bandaged.png'),
  require('./Thumbnails/flowers.png'),
  require('./Thumbnails/heart.png'),
  require('./Thumbnails/liking.png'),
  require('./Thumbnails/party.png'),
  require('./Thumbnails/poke.png'),
  require('./Thumbnails/superlike.png'),
  require('./Thumbnails/victory.png'),
  ];
var LOREM_IPSUM = 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.';

/* eslint no-bitwise: 0 */
var hashCode = function(str) {
  var hash = 15;
  for (var ii = str.length - 1; ii >= 0; ii--) {
    hash = ((hash << 5) - hash) + str.charCodeAt(ii);
  }
  return hash;
};

var styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 10,
    backgroundColor: '#F6F6F6',
  },
  separator: {
    height: 1,
    backgroundColor: '#CCCCCC',
  },
  thumb: {
    width: 64,
    height: 64,
  },
  text: {
    flex: 1,
  },
});

module.exports = ListViewSimpleExample;
<|endoftext|>


<commit_before>class ProfileStats {
    constructor(content) {
        this.region = content.Region;
        this.season = content.Season;
        this.match = content.Match;
        this.stats = this._structureStats(content.Stats);
    }

    getItem(name) {
        if (!name || typeof name === 'string') return;
        return this.stats.find(s => s.name === name);
    }

    _structureStats(Stats) {
        const stats = [];
        for (const stat of Object.keys(Stats)) {
            const key = Stats[stat];
            const statObj = {
                fullName: key.label,
                name: key.field,
                category: key.category,
                valueInt: key.ValueInt,
                valueDec: key.ValueDec,
                value: key.value,
                rank: key.rank,
                percentile: key.percentile,
                displayValue: key.displayValue
            };
            stats.push(statObj);
        }
        return stats;
    }
}

module.exports = ProfileStats;<commit_msg>Forgot !, major errors caused<commit_after>class ProfileStats {
    constructor(content) {
        this.region = content.Region;
        this.season = content.Season;
        this.match = content.Match;
        this.stats = this._structureStats(content.Stats);
    }

    getItem(name) {
        if (!name || !typeof name === 'string') return;
        return this.stats.find(s => s.name === name);
    }

    _structureStats(Stats) {
        const stats = [];
        for (const stat of Object.keys(Stats)) {
            const key = Stats[stat];
            const statObj = {
                fullName: key.label,
                name: key.field,
                category: key.category,
                valueInt: key.ValueInt,
                valueDec: key.ValueDec,
                value: key.value,
                rank: key.rank,
                percentile: key.percentile,
                displayValue: key.displayValue
            };
            stats.push(statObj);
        }
        return stats;
    }
}

module.exports = ProfileStats;<|endoftext|>


<commit_before>'use strict'

var test = require('tap').test
var path = require('path')
var writeStream = require('flush-write-stream')
var fork = require('child_process').fork
var spawn = require('child_process').spawn
var fixturesPath = path.join(__dirname, 'fixtures', 'events')

test('no event loop logs successfully', function (t) {
  t.plan(1)
  var output = ''
  var child = fork(path.join(fixturesPath, 'no-event-loop.js'), {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.on('close', function () {
    t.notEqual(output.match(/"msg":"h"/), null)
  })
})

test('handles no file descriptor in extreme mode', function (t) {
  t.plan(2)
  var output = ''
  var errorOutput = ''
  var child = fork(path.join(fixturesPath, 'no-fd.js'), {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.stderr.pipe(writeStream(function (s, enc, cb) {
    errorOutput += s
    cb()
  }))

  child.on('close', function () {
    t.is(output, '')
    t.notEqual(errorOutput.match(/stream must have/g), null)
  })
})

test('terminates when uncaughtException is fired with onTerminate registered', function (t) {
  t.plan(3)
  var output = ''
  var errorOutput = ''
  var child = spawn(process.argv0, [path.join(fixturesPath, 'uncaughtException.js')], {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.stderr.pipe(writeStream(function (s, enc, cb) {
    errorOutput += s
    cb()
  }))

  child.on('close', function () {
    t.notEqual(output.match(/"msg":"h"/), null)
    t.notEqual(output.match(/terminated/g), null)
    t.notEqual(errorOutput.match(/this is not caught/g), null)
  })
})

test('terminates when uncaughtException is fired without onTerminate registered', function (t) {
  t.plan(2)
  var output = ''
  var child = spawn(process.argv0, [path.join(fixturesPath, 'uncaughtException-noTerminate.js')], {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.on('exit', function (code) {
    t.is(code, 0)
  })

  child.on('close', function () {
    t.notEqual(output.match(/"msg":"h"/), null)
  })
})
<commit_msg>Fix events tests for Node v4/5<commit_after>'use strict'

var test = require('tap').test
var path = require('path')
var writeStream = require('flush-write-stream')
var fork = require('child_process').fork
var spawn = require('child_process').spawn
var fixturesPath = path.join(__dirname, 'fixtures', 'events')

test('no event loop logs successfully', function (t) {
  t.plan(1)
  var output = ''
  var child = fork(path.join(fixturesPath, 'no-event-loop.js'), {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.on('close', function () {
    t.notEqual(output.match(/"msg":"h"/), null)
  })
})

test('handles no file descriptor in extreme mode', function (t) {
  t.plan(2)
  var output = ''
  var errorOutput = ''
  var child = fork(path.join(fixturesPath, 'no-fd.js'), {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.stderr.pipe(writeStream(function (s, enc, cb) {
    errorOutput += s
    cb()
  }))

  child.on('close', function () {
    t.is(output, '')
    t.notEqual(errorOutput.match(/stream must have/g), null)
  })
})

test('terminates when uncaughtException is fired with onTerminate registered', function (t) {
  t.plan(3)
  var output = ''
  var errorOutput = ''
  var child = spawn(process.argv[0], [path.join(fixturesPath, 'uncaughtException.js')], {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.stderr.pipe(writeStream(function (s, enc, cb) {
    errorOutput += s
    cb()
  }))

  child.on('close', function () {
    t.notEqual(output.match(/"msg":"h"/), null)
    t.notEqual(output.match(/terminated/g), null)
    t.notEqual(errorOutput.match(/this is not caught/g), null)
  })
})

test('terminates when uncaughtException is fired without onTerminate registered', function (t) {
  t.plan(2)
  var output = ''
  var child = spawn(process.argv[0], [path.join(fixturesPath, 'uncaughtException-noTerminate.js')], {silent: true})

  child.stdout.pipe(writeStream(function (s, enc, cb) {
    output += s
    cb()
  }))

  child.on('exit', function (code) {
    t.is(code, 0)
  })

  child.on('close', function () {
    t.notEqual(output.match(/"msg":"h"/), null)
  })
})
<|endoftext|>


<commit_before>import utils from "./utils";

// Dependencies
var R        = require("ramda");
var BPromise = require("bluebird");
var path     = require("path");
var fs       = BPromise.promisifyAll(require("fs"));
var stripJsonComments = require("strip-json-comments");

// Log
var chalk = require('chalk');

export class Asana2Pivotal {
  constructor(options) {
    options = R.merge({
      from  : 'debug.json',
      to    : 'normalized.json',
      config: 'map.json'
    }, options);

    if (options.verbose) {
      utils.verbose = options.verbose;
    }

    options.from   = path.resolve(process.cwd(), options.from);
    options.to     = path.resolve(process.cwd(), options.to);
    options.config = path.resolve(process.cwd(), options.config);

    this.map     = this.readMapFile(options.config);
    this.options = options;
  }

  readMapFile(filepath) {
    filepath = filepath || this.options.map;
    var content;

    try {
      content = stripJsonComments(fs.readFileSync(filepath).toString());
      content = JSON.parse(content);
    } catch (e) {
      throw e;
    }
    return content;
  }

  run() {
    return BPromise.coroutine(function* () {
      var workspace, json, stories;

      json = yield this.readFile();
      json = this.replaceUsers(json);

      workspace = JSON.parse(json);

      if (R.is(Object, workspace) && !R.isEmpty(workspace.tasks)) {
        var old_length = workspace.tasks.length;
        utils.log("  Normalize", chalk.green(workspace.tasks.length), "tasks");
        workspace.tasks = R.filter((task) => !R.isNil(task), workspace.tasks);
        utils.log("  Remove", chalk.green(old_length - workspace.tasks.length), "empty tasks");
        stories = workspace.tasks.map(this.taskToStorie.bind(this));
      }

      utils.log("  " + chalk.green(stories.length), chalk.blue("normalized stories"));
      var normalized_json = JSON.stringify(stories, null, 2);
      this.saveFile(normalized_json);

      return stories;
    }.bind(this))();
  }

  readFile(filepath) {
    filepath = filepath || this.options.from;
    return fs.readFileAsync(filepath)
      .then(function (data) {
        utils.log("Successful read file " + chalk.green(filepath));
        return data.toString();
      })
      .catch(BPromise.OperationalError, function (e) {
        console.error("unable to read file, because: ", e.message);
      });
  }

  saveFile(json) {
    var filepath = this.options.to;
    fs.writeFileAsync(filepath, json)
      .then(function() {
        utils.log("Successful saved file " + chalk.green(filepath));
      });
  }

  replaceUsers(json) {
    var asana_ids = Object.keys(this.map.users);

    for (var i = 0; asana_ids.length > i; i++) {
      var user_id = asana_ids[i];
      var user    = this.map.users[user_id];

      // Mention Replaces
      var url   = 'https://app.asana.com/0/' + user.mention_id + '/' + user.mention_id;
      var regex = new RegExp(url, "gm");
      json = json.replace(regex, '@' + user.username);

      // UserID replace
      regex = new RegExp(user_id, "gm");
      json  = json.replace(regex, user.pivotal_id);
    }

    return json;
  }

  projectMap(task) {
    var projectMaped = R.clone(this.map.defaults.projects);

    console.log('task:', task);
    if (!R.isEmpty(task.projects) && !R.isEmpty(task.projects[0])) {
      projectMaped = R.clone(this.map.projects[task.projects[0].id]) || projectMaped;
    }

    // Replaces the state based in section
    var membership = R.find(R.prop('section'))(task.memberships);
    var section    = (membership && membership.section.name);
    if (!R.isNil(section) && this.map.sections.hasOwnProperty(section)) {
      var sectionMaped = R.clone(this.map.sections[section]);
      if (!R.isNil(sectionMaped)) {
        if (sectionMaped.hasOwnProperty("state")) {
          projectMaped.state = sectionMaped.state;
        }
        if (sectionMaped.hasOwnProperty("labels") && R.isArrayLike(sectionMaped.labels)) {
          projectMaped.labels = projectMaped.labels.concat(sectionMaped.labels);
        }
      }
    }

    return projectMaped;
  }

  taskToStorie(task) {
    var projectMaped = this.projectMap(task);
    var comments     = this.comments(task);
    var assignee     = (task.assignee) ? [task.assignee] : [];
    var labels       = projectMaped.labels.concat(task.tags);

    var [subtasks, owners, subtasks_comments] = this.subtasksToTasks(task.subtasks);

    labels = R.map((label) => {
      if (R.is(Object, label) && label.hasOwnProperty('name')) {
        label = label.name;
      } else if (!R.is(String, label)) {
        label = null;
      }
      return label;
    }, labels);

    // array of object to array of ids
    var owner_ids = R.map((owner) => owner.id, assignee.concat(owners));

    // Clean duplicated and limit to three owners.
    owner_ids = R.slice(0, 3)(R.uniq(owner_ids));
    labels = R.uniq(labels);

    // clean nil or empty
    labels = R.filter(((label) => !R.isNil(label) && !R.isEmpty(label)), labels);

    // Clean invalid person_id in comments
    var user_keys   = Object.keys(this.map.users);
    var user_values = Object.values(this.map.users);
    var removeInvalidPerson_ids = (comment) => {
      if (comment.person_id) {
        var result = R.contains(comment.person_id)(user_keys);
        if (!result) {
          var filterPersonId = R.propEq('pivotal_id', (comment.person_id || '').toString());
          var pivotal_user   = R.find(filterPersonId)(user_values);

          if (!pivotal_user) {
            delete(comment.person_id);
          }
        }
      }
      return comment;
    };
    comments = R.map(removeInvalidPerson_ids, comments.concat(subtasks_comments));

    var story = {
      name         : task.name,
      labels       : labels,
      description  : task.notes,
      project_id   : projectMaped.pivotal_id,
      current_state: projectMaped.state,
      tasks        : subtasks,
      owner_ids    : owner_ids,
      comments     : comments
    };

    if (!R.isNil(task.due_on)) {
      story.deadline   = (new Date(task.due_on)).toISOString();
      story.story_type = "release";
    }

    return story;
  }

  subtasksToTasks(tasks) {
    var assignees     = [];
    var descriptions  = [];
    var normalize = function(subtask) {
      if (!R.isEmpty(subtask.notes)) {
        descriptions.push({
          text: '`[' + subtask.name + ']:`' + subtask.notes
        });
      }

      if (subtask.assignee) { assignees.push(subtask.assignee); }

      return {
        description: subtask.name,
        complete   : !!subtask.completed
      };
    };
    var subtasks = R.map(normalize, tasks);
    return [subtasks, assignees, descriptions];
  }

  comments(task) {
    // stories (comments)
    var normalize = function(storie) {
      return {
        text: storie.text,
        person_id: storie.created_by.id
      };
    };
    var stories = R.map(normalize, (task.stories || []));

    // attachments
    var attachments = R.map(((attach) => {
      return {
        name: attach.name,
        url : attach.download_url
      };
    }), (task.attachments || []));
    attachments = (!R.isEmpty(attachments)) ? [{ file_attachments: attachments }] : [];

    return attachments.concat(stories);
  }
}
<commit_msg>[Normalize] Adding attribute `estimate` to stories with `current_state` equal `finished`;<commit_after>import utils from "./utils";

// Dependencies
var R        = require("ramda");
var BPromise = require("bluebird");
var path     = require("path");
var fs       = BPromise.promisifyAll(require("fs"));
var stripJsonComments = require("strip-json-comments");

// Log
var chalk = require('chalk');

export class Asana2Pivotal {
  constructor(options) {
    options = R.merge({
      from  : 'debug.json',
      to    : 'normalized.json',
      config: 'map.json'
    }, options);

    if (options.verbose) {
      utils.verbose = options.verbose;
    }

    options.from   = path.resolve(process.cwd(), options.from);
    options.to     = path.resolve(process.cwd(), options.to);
    options.config = path.resolve(process.cwd(), options.config);

    this.map     = this.readMapFile(options.config);
    this.options = options;
  }

  readMapFile(filepath) {
    filepath = filepath || this.options.map;
    var content;

    try {
      content = stripJsonComments(fs.readFileSync(filepath).toString());
      content = JSON.parse(content);
    } catch (e) {
      throw e;
    }
    return content;
  }

  run() {
    return BPromise.coroutine(function* () {
      var workspace, json, stories;

      json = yield this.readFile();
      json = this.replaceUsers(json);

      workspace = JSON.parse(json);

      if (R.is(Object, workspace) && !R.isEmpty(workspace.tasks)) {
        var old_length = workspace.tasks.length;
        utils.log("  Normalize", chalk.green(workspace.tasks.length), "tasks");
        workspace.tasks = R.filter((task) => !R.isNil(task), workspace.tasks);
        utils.log("  Remove", chalk.green(old_length - workspace.tasks.length), "empty tasks");
        stories = workspace.tasks.map(this.taskToStorie.bind(this));
      }

      utils.log("  " + chalk.green(stories.length), chalk.blue("normalized stories"));
      var normalized_json = JSON.stringify(stories, null, 2);
      this.saveFile(normalized_json);

      return stories;
    }.bind(this))();
  }

  readFile(filepath) {
    filepath = filepath || this.options.from;
    return fs.readFileAsync(filepath)
      .then(function (data) {
        utils.log("Successful read file " + chalk.green(filepath));
        return data.toString();
      })
      .catch(BPromise.OperationalError, function (e) {
        console.error("unable to read file, because: ", e.message);
      });
  }

  saveFile(json) {
    var filepath = this.options.to;
    fs.writeFileAsync(filepath, json)
      .then(function() {
        utils.log("Successful saved file " + chalk.green(filepath));
      });
  }

  replaceUsers(json) {
    var asana_ids = Object.keys(this.map.users);

    for (var i = 0; asana_ids.length > i; i++) {
      var user_id = asana_ids[i];
      var user    = this.map.users[user_id];

      // Mention Replaces
      var url   = 'https://app.asana.com/0/' + user.mention_id + '/' + user.mention_id;
      var regex = new RegExp(url, "gm");
      json = json.replace(regex, '@' + user.username);

      // UserID replace
      regex = new RegExp(user_id, "gm");
      json  = json.replace(regex, user.pivotal_id);
    }

    return json;
  }

  projectMap(task) {
    var projectMaped = R.clone(this.map.defaults.projects);

    console.log('task:', task);
    if (!R.isEmpty(task.projects) && !R.isEmpty(task.projects[0])) {
      projectMaped = R.clone(this.map.projects[task.projects[0].id]) || projectMaped;
    }

    // Replaces the state based in section
    var membership = R.find(R.prop('section'))(task.memberships);
    var section    = (membership && membership.section.name);
    if (!R.isNil(section) && this.map.sections.hasOwnProperty(section)) {
      var sectionMaped = R.clone(this.map.sections[section]);
      if (!R.isNil(sectionMaped)) {
        if (sectionMaped.hasOwnProperty("state")) {
          projectMaped.state = sectionMaped.state;
        }
        if (sectionMaped.hasOwnProperty("labels") && R.isArrayLike(sectionMaped.labels)) {
          projectMaped.labels = projectMaped.labels.concat(sectionMaped.labels);
        }
      }
    }

    return projectMaped;
  }

  taskToStorie(task) {
    var projectMaped = this.projectMap(task);
    var comments     = this.comments(task);
    var assignee     = (task.assignee) ? [task.assignee] : [];
    var labels       = projectMaped.labels.concat(task.tags);

    var [subtasks, owners, subtasks_comments] = this.subtasksToTasks(task.subtasks);

    labels = R.map((label) => {
      if (R.is(Object, label) && label.hasOwnProperty('name')) {
        label = label.name;
      } else if (!R.is(String, label)) {
        label = null;
      }
      return label;
    }, labels);

    // array of object to array of ids
    var owner_ids = R.map((owner) => owner.id, assignee.concat(owners));

    // Clean duplicated and limit to three owners.
    owner_ids = R.slice(0, 3)(R.uniq(owner_ids));
    labels = R.uniq(labels);

    // clean nil or empty
    labels = R.filter(((label) => !R.isNil(label) && !R.isEmpty(label)), labels);

    // Clean invalid person_id in comments
    var user_keys   = Object.keys(this.map.users);
    var user_values = Object.values(this.map.users);
    var removeInvalidPerson_ids = (comment) => {
      if (comment.person_id) {
        var result = R.contains(comment.person_id)(user_keys);
        if (!result) {
          var filterPersonId = R.propEq('pivotal_id', (comment.person_id || '').toString());
          var pivotal_user   = R.find(filterPersonId)(user_values);

          if (!pivotal_user) {
            delete(comment.person_id);
          }
        }
      }
      return comment;
    };
    comments = R.map(removeInvalidPerson_ids, comments.concat(subtasks_comments));

    var story = {
      name         : task.name,
      labels       : labels,
      description  : task.notes,
      project_id   : projectMaped.pivotal_id,
      current_state: projectMaped.state,
      tasks        : subtasks,
      owner_ids    : owner_ids,
      comments     : comments
    };

    if (!R.isNil(task.due_on)) {
      story.deadline   = (new Date(task.due_on)).toISOString();
      story.story_type = "release";
    }
    if (story.current_state && story.current_state == "finished") {
      story.estimate = 1;
    }

    return story;
  }

  subtasksToTasks(tasks) {
    var assignees     = [];
    var descriptions  = [];
    var normalize = function(subtask) {
      if (!R.isEmpty(subtask.notes)) {
        descriptions.push({
          text: '`[' + subtask.name + ']:`' + subtask.notes
        });
      }

      if (subtask.assignee) { assignees.push(subtask.assignee); }

      return {
        description: subtask.name,
        complete   : !!subtask.completed
      };
    };
    var subtasks = R.map(normalize, tasks);
    return [subtasks, assignees, descriptions];
  }

  comments(task) {
    // stories (comments)
    var normalize = function(storie) {
      return {
        text: storie.text,
        person_id: storie.created_by.id
      };
    };
    var stories = R.map(normalize, (task.stories || []));

    // attachments
    var attachments = R.map(((attach) => {
      return {
        name: attach.name,
        url : attach.download_url
      };
    }), (task.attachments || []));
    attachments = (!R.isEmpty(attachments)) ? [{ file_attachments: attachments }] : [];

    return attachments.concat(stories);
  }
}
<|endoftext|>


<commit_before>/** @jsx React.DOM */

var React = require('react'),
	Field = require('../field'),
	pikaday = require('pikaday'),
	moment = require('moment');

module.exports = Field.create({

	supports: {
		focusTarget: 'dateInput'
	},

	// default formats
	inputFormat: 'YYYY-MM-DD',
	noEditFormat: 'Do MMM YYYY',

	getInitialState: function() {
		return {
			value: this.props.value ? moment(this.props.value).format(this.inputFormat) : ''
		};
	},

	componentDidMount: function() {
		var _this = this;

		// just return if noedit is enabled
		if (this.props.noedit) {
			return;
		}

		// add date picker
		this.picker = new Pikaday({
			field: this.refs.dateInput.getDOMNode(),
			onSelect: function(date) {
				format: this.inputFormat,
				_this.setDate(_this.picker.toString());
			}
		});

	},
	componentWillUnmount: function() {
		// clean up
		this.picker.destroy();
	},

	// TODO: Move isValid() so we can share with server-side code
	isValid: function(value) {
		return moment(value, this.inputFormat).isValid();
	},

	// TODO: Move format() so we can share with server-side code
	format: function(dateValue, format) {
		format = format || this.inputFormat;
		return dateValue ? moment(this.props.dateValue).format(format) : '';
	},

	setDate: function(dateValue) {
		this.setState({	value: dateValue	});
		this.props.onChange({
			path: this.props.path,
			value: this.isValid(dateValue) ? moment(dateValue, this.inputFormat).toISOString() : null
		});
	},

	setToday: function() {
		this.setDate(moment().format(this.inputFormat));
	},

	valueChanged: function(event) {
		this.setDate(event.target.value);
	},

	renderUI: function() {

		var input, fieldClassName = 'field-ui';

		if (this.props.noedit) {
			input = (

{this.format(this.props.value, this.props.formatString || this.noEditFormat)}

			);
		} else {
			input = (

					<input type="text" name={this.props.path} ref="dateInput" value={this.state.value} onChange={this.valueChanged} autoComplete="off" className="form-control" />
					Today

			);
		}

		return (

				{this.props.label}
				{input}

		);
	}

});
<commit_msg>more code formatting fixes<commit_after>/** @jsx React.DOM */

var React = require('react'),
	Field = require('../field'),
	pikaday = require('pikaday'),
	moment = require('moment');

module.exports = Field.create({

	supports: {
		focusTarget: 'dateInput'
	},

	// default formats
	inputFormat: 'YYYY-MM-DD',
	noEditFormat: 'Do MMM YYYY',

	getInitialState: function() {
		return {
			value: this.props.value ? moment(this.props.value).format(this.inputFormat) : ''
		};
	},

	componentDidMount: function() {
		var _this = this;

		// just return if noedit is enabled
		if (this.props.noedit) {
			return;
		}

		// add date picker
		this.picker = new Pikaday({
			field: this.refs.dateInput.getDOMNode(),
			onSelect: function(date) {
				format: this.inputFormat,
				_this.setDate(_this.picker.toString());
			}
		});

	},
	componentWillUnmount: function() {
		// clean up
		this.picker.destroy();
	},

	// TODO: Move isValid() so we can share with server-side code
	isValid: function(value) {
		return moment(value, this.inputFormat).isValid();
	},

	// TODO: Move format() so we can share with server-side code
	format: function(dateValue, format) {
		format = format || this.inputFormat;
		return dateValue ? moment(this.props.dateValue).format(format) : '';
	},

	setDate: function(dateValue) {
		this.setState({ value: dateValue });
		this.props.onChange({
			path: this.props.path,
			value: this.isValid(dateValue) ? moment(dateValue, this.inputFormat).toISOString() : null
		});
	},

	setToday: function() {
		this.setDate(moment().format(this.inputFormat));
	},

	valueChanged: function(event) {
		this.setDate(event.target.value);
	},

	renderUI: function() {

		var input, fieldClassName = 'field-ui';

		if (this.props.noedit) {
			input = (

{this.format(this.props.value, this.props.formatString || this.noEditFormat)}

			);
		} else {
			input = (

					<input type="text" name={this.props.path} ref="dateInput" value={this.state.value} onChange={this.valueChanged} autoComplete="off" className="form-control" />
					Today

			);
		}

		return (

				{this.props.label}
				{input}

		);
	}

});
<|endoftext|>


<commit_before>var gRex = require('../index.js'),
  T = gRex.T,
  Contains = gRex.Contains,
  Vertex = gRex.Vertex,
  Edge = gRex.Edge;

var gRex;

before(function(done) {
  gRex.connect()
    .then(function(result) {
      gRex = result;
      done();
    })
    .fail(function(error) {
      console.error(error);
    });
});

describe('Gremlin steps', function() {
  describe('Transform-based steps', function() {
    it('should chain .V()', function() {
      var query = gRex.gremlin().g.V();
      query.gremlin.script.should.equal('g.V()');
    });

    it('should chain .V(key, value)', function() {
      var query = gRex.gremlin().g.V('name', 'marko');
      query.gremlin.script.should.equal("g.V('name','marko')");
    });

    it('should chain .E()', function() {
      var query = gRex.gremlin().g.E();
      query.gremlin.script.should.equal("g.E()");
    });

    it("should chain .v() with a numerical id", function() {
      var query = gRex.gremlin().g.v(1);
      query.gremlin.script.should.equal("g.v(1)");
    });

    it("should chain .v() with multiple numerical ids", function() {
      var query = gRex.gremlin().g.v(1, 4);
      query.gremlin.script.should.equal("g.v(1,4)");
    });

    it("should chain .id()", function() {
      var query = gRex.gremlin().g.V().id();
      query.gremlin.script.should.equal('g.V().id()');
    });

    it('should chain .transform() with a closure', function() {
      var query = gRex.gremlin().g.E().has('weight', T.gt, '0.5f').outV().transform('{[it.id,it.age]}');
      query.gremlin.script.should.equal("g.E().has('weight',T.gt,0.5f).outV().transform(){[it.id,it.age]}");
    });

    it('should chain .select()', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select();
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select()");
    });

    it('should chain .select([])', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select(["y"]);
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select([\"y\"])");
    });

    it('should chain .select([]) & 1 closure', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select(["y"],"{it.name}");
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select([\"y\"]){it.name}");
    });

    it('should chain .select() & 2 closures', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select("{it.id}{it.name}");
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select(){it.id}{it.name}");
    });

    it("should chain .orderMap()", function() {
      var query = gRex.gremlin().g.V().both().groupCount().cap().orderMap(T.decr);
      query.gremlin.script.should.equal("g.V().both().groupCount().cap().orderMap(T.decr)");
    });
  });

  describe('Filter-based steps', function() {
    it('should chain .index() as []', function() {
      var query = gRex.gremlin().g.V().index(0).property('name');
      query.gremlin.script.should.equal("g.V()[0].property('name')");
    });

    it('should chain .range() as [..]', function() {
      var query = gRex.gremlin().g.V().range('0..<2').property('name');
      query.gremlin.script.should.equal("g.V()[0..<2].property('name')");
    });

    it('should chain .and() with 2 conditions', function() {
      var gremlin = gRex.gremlin();
      var query = gremlin.g.V().and(gremlin._().both("knows"), gremlin._().both("created"));
      console.log(query.gremlin.script);
      query.gremlin.script.should.equal("g.V().and(_().both('knows'),_().both('created'))");
    });

    it('should chain .or() with 2 conditions', function() {
      var gremlin = gRex.gremlin();
      var query = gremlin.g.v(1).outE().or(gremlin._().has('id', T.eq, 9), gremlin._().has('weight', T.lt, '0.6f'));
      query.gremlin.script.should.equal("g.v(1).outE().or(_().has('id',T.eq,9),_().has('weight',T.lt,0.6f))");
    });

    it('should chain .retain([])', function() {
      var gremlin = gRex.gremlin();

      var query = gremlin.g.V().retain([gremlin.g.v(1), gremlin.g.v(2), gremlin.g.v(3)]);

      query.gremlin.script.should.equal("g.V().retain([g.v(1),g.v(2),g.v(3),])");
    });

    it('should chain .except()', function() {
      var query = gRex.gremlin().g.V().has('age',T.lt,30).as('x').out('created').in('created').except('x');
      query.gremlin.script.should.equal("g.V().has('age',T.lt,30).as('x').out('created').in('created').except('x')");
    });
  });

  describe('SideEffect-based steps', function() {
    it("should chain .gather()", function() {
      var query = gRex.gremlin().g.v(1).out().gather("{it.size()}");
      query.gremlin.script.should.equal("g.v(1).out().gather(){it.size()}");
    });
  });

  describe('Branch-based steps', function() {
    it("should chain .ifThenElse()", function() {
      var query = gRex.gremlin().g.v(1).out().ifThenElse("{it.name=='josh'}{it.age}{it.name}");
      query.gremlin.script.should.equal("g.v(1).out().ifThenElse(){it.name=='josh'}{it.age}{it.name}");
    });

    it("should chain .copySplit()", function() {
      var gremlin = gRex.gremlin();
      var query = gremlin.g.v(1).out('knows').copySplit(gremlin._().out('created').property('name'), gremlin._().property('age')).fairMerge();
      query.gremlin.script.should.equal("g.v(1).out('knows').copySplit(_().out('created').property('name'),_().property('age')).fairMerge()");
    });
  });
});

describe('Graph methods', function() {
  describe('indexing', function() {
    it("should support g.createIndex()", function() {
      var query = gRex.gremlin().g.createIndex("my-index", 'Vertex.class');
      query.gremlin.script.should.equal("g.createIndex('my-index',Vertex.class)");
    });

    it("should support g.idx().put()", function() {
      var gremlin = gRex.gremlin();
      var query = gRex.gremlin().g.idx("my-index").put("name", "marko", gremlin.g.v(1));
      query.gremlin.script.should.equal("g.idx('my-index').put('name','marko',g.v(1))");
    });

    it("should support g.idx(name, {})", function() {
      var query = gRex.gremlin().g.idx("my-index", {'name':'marko'});
      query.gremlin.script.should.equal("g.idx('my-index')[[name:'marko']]");
    });

    it("should support g.dropIndex()", function() {
      var query = gRex.gremlin().g.dropIndex("my-index");
      query.gremlin.script.should.equal("g.dropIndex('my-index')");
    });
  });

  describe('Elements', function() {
    it("should chain .keys()", function() {
      var query = gRex.gremlin().g.v(1).keys();
      query.gremlin.script.should.equal("g.v(1).keys()");
    });

    it("should chain .values()", function() {
      var query = gRex.gremlin().g.v(1).values();
      query.gremlin.script.should.equal("g.v(1).values()");
    });
  });
});

describe('Misc', function() {
  describe('float', function() {
    it("should handle float values", function() {
      var query = gRex.gremlin().g.v(1).outE().has("weight", T.gte, "0.5f");
      query.gremlin.script.should.equal("g.v(1).outE().has('weight',T.gte,0.5f)");
    });
  });
});
<commit_msg>Remove a console.log() in test<commit_after>var gRex = require('../index.js'),
  T = gRex.T,
  Contains = gRex.Contains,
  Vertex = gRex.Vertex,
  Edge = gRex.Edge;

var gRex;

before(function(done) {
  gRex.connect()
    .then(function(result) {
      gRex = result;
      done();
    })
    .fail(function(error) {
      console.error(error);
    });
});

describe('Gremlin steps', function() {
  describe('Transform-based steps', function() {
    it('should chain .V()', function() {
      var query = gRex.gremlin().g.V();
      query.gremlin.script.should.equal('g.V()');
    });

    it('should chain .V(key, value)', function() {
      var query = gRex.gremlin().g.V('name', 'marko');
      query.gremlin.script.should.equal("g.V('name','marko')");
    });

    it('should chain .E()', function() {
      var query = gRex.gremlin().g.E();
      query.gremlin.script.should.equal("g.E()");
    });

    it("should chain .v() with a numerical id", function() {
      var query = gRex.gremlin().g.v(1);
      query.gremlin.script.should.equal("g.v(1)");
    });

    it("should chain .v() with multiple numerical ids", function() {
      var query = gRex.gremlin().g.v(1, 4);
      query.gremlin.script.should.equal("g.v(1,4)");
    });

    it("should chain .id()", function() {
      var query = gRex.gremlin().g.V().id();
      query.gremlin.script.should.equal('g.V().id()');
    });

    it('should chain .transform() with a closure', function() {
      var query = gRex.gremlin().g.E().has('weight', T.gt, '0.5f').outV().transform('{[it.id,it.age]}');
      query.gremlin.script.should.equal("g.E().has('weight',T.gt,0.5f).outV().transform(){[it.id,it.age]}");
    });

    it('should chain .select()', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select();
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select()");
    });

    it('should chain .select([])', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select(["y"]);
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select([\"y\"])");
    });

    it('should chain .select([]) & 1 closure', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select(["y"],"{it.name}");
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select([\"y\"]){it.name}");
    });

    it('should chain .select() & 2 closures', function() {
      var query = gRex.gremlin().g.v(1).as('x').out('knows').as('y').select("{it.id}{it.name}");
      query.gremlin.script.should.equal("g.v(1).as('x').out('knows').as('y').select(){it.id}{it.name}");
    });

    it("should chain .orderMap()", function() {
      var query = gRex.gremlin().g.V().both().groupCount().cap().orderMap(T.decr);
      query.gremlin.script.should.equal("g.V().both().groupCount().cap().orderMap(T.decr)");
    });
  });

  describe('Filter-based steps', function() {
    it('should chain .index() as []', function() {
      var query = gRex.gremlin().g.V().index(0).property('name');
      query.gremlin.script.should.equal("g.V()[0].property('name')");
    });

    it('should chain .range() as [..]', function() {
      var query = gRex.gremlin().g.V().range('0..<2').property('name');
      query.gremlin.script.should.equal("g.V()[0..<2].property('name')");
    });

    it('should chain .and() with 2 conditions', function() {
      var gremlin = gRex.gremlin();
      var query = gremlin.g.V().and(gremlin._().both("knows"), gremlin._().both("created"));
      query.gremlin.script.should.equal("g.V().and(_().both('knows'),_().both('created'))");
    });

    it('should chain .or() with 2 conditions', function() {
      var gremlin = gRex.gremlin();
      var query = gremlin.g.v(1).outE().or(gremlin._().has('id', T.eq, 9), gremlin._().has('weight', T.lt, '0.6f'));
      query.gremlin.script.should.equal("g.v(1).outE().or(_().has('id',T.eq,9),_().has('weight',T.lt,0.6f))");
    });

    it('should chain .retain([])', function() {
      var gremlin = gRex.gremlin();

      var query = gremlin.g.V().retain([gremlin.g.v(1), gremlin.g.v(2), gremlin.g.v(3)]);

      query.gremlin.script.should.equal("g.V().retain([g.v(1),g.v(2),g.v(3),])");
    });

    it('should chain .except()', function() {
      var query = gRex.gremlin().g.V().has('age',T.lt,30).as('x').out('created').in('created').except('x');
      query.gremlin.script.should.equal("g.V().has('age',T.lt,30).as('x').out('created').in('created').except('x')");
    });
  });

  describe('SideEffect-based steps', function() {
    it("should chain .gather()", function() {
      var query = gRex.gremlin().g.v(1).out().gather("{it.size()}");
      query.gremlin.script.should.equal("g.v(1).out().gather(){it.size()}");
    });
  });

  describe('Branch-based steps', function() {
    it("should chain .ifThenElse()", function() {
      var query = gRex.gremlin().g.v(1).out().ifThenElse("{it.name=='josh'}{it.age}{it.name}");
      query.gremlin.script.should.equal("g.v(1).out().ifThenElse(){it.name=='josh'}{it.age}{it.name}");
    });

    it("should chain .copySplit()", function() {
      var gremlin = gRex.gremlin();
      var query = gremlin.g.v(1).out('knows').copySplit(gremlin._().out('created').property('name'), gremlin._().property('age')).fairMerge();
      query.gremlin.script.should.equal("g.v(1).out('knows').copySplit(_().out('created').property('name'),_().property('age')).fairMerge()");
    });
  });
});

describe('Graph methods', function() {
  describe('indexing', function() {
    it("should support g.createIndex()", function() {
      var query = gRex.gremlin().g.createIndex("my-index", 'Vertex.class');
      query.gremlin.script.should.equal("g.createIndex('my-index',Vertex.class)");
    });

    it("should support g.idx().put()", function() {
      var gremlin = gRex.gremlin();
      var query = gRex.gremlin().g.idx("my-index").put("name", "marko", gremlin.g.v(1));
      query.gremlin.script.should.equal("g.idx('my-index').put('name','marko',g.v(1))");
    });

    it("should support g.idx(name, {})", function() {
      var query = gRex.gremlin().g.idx("my-index", {'name':'marko'});
      query.gremlin.script.should.equal("g.idx('my-index')[[name:'marko']]");
    });

    it("should support g.dropIndex()", function() {
      var query = gRex.gremlin().g.dropIndex("my-index");
      query.gremlin.script.should.equal("g.dropIndex('my-index')");
    });
  });

  describe('Elements', function() {
    it("should chain .keys()", function() {
      var query = gRex.gremlin().g.v(1).keys();
      query.gremlin.script.should.equal("g.v(1).keys()");
    });

    it("should chain .values()", function() {
      var query = gRex.gremlin().g.v(1).values();
      query.gremlin.script.should.equal("g.v(1).values()");
    });
  });
});

describe('Misc', function() {
  describe('float', function() {
    it("should handle float values", function() {
      var query = gRex.gremlin().g.v(1).outE().has("weight", T.gte, "0.5f");
      query.gremlin.script.should.equal("g.v(1).outE().has('weight',T.gte,0.5f)");
    });
  });
});
<|endoftext|>