<commit_before>import React from "react";

import {
  Appear, BlockQuote, Cite, CodePane, Deck, Fill,
  Heading, Image, Layout, Link, ListItem, List, Markdown, Quote, Slide, Spectacle,
  TableHeaderItem, TableItem, TableRow, Table, Text
} from "../src";

import preloader from "../src/utils/preloader";

import createTheme from "../src/themes/default";

import Interactive from "../assets/interactive";

import InteractiveRemove from "../assets/interactiveRemove";

import Rd3Interactive from "../assets/rd3Interactive";

require("normalize.css");
require("../src/themes/default/index.css");

const images = {
  template: require("../assets/template.png"),
};

preloader(images);

const theme = createTheme({
  primary: "#46AAE8"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["zoom", "slide"]} transitionDuration={500}>

          <Slide transition={["zoom"]} bgColor="primary">
            <Heading size={1} fit caps lineHeight={1} textColor="black">
              React D3 Library
            </Heading>
            <Heading size={1} fit caps>
              A codesmith Presentation
            </Heading>
            <Heading size={1} fit caps textColor="black">
              where you can use d3 in react
            </Heading>
            <Link href="https://github.com/FormidableLabs/spectacle">
              <Text bold caps textColor="tertiary">it's super sweet</Text>
            </Link>
            <Text textSize="1.5em" margin="20px 0px 0px" bold>by andrew burke, danny lee, and dave loyst!</Text>
          </Slide>

          <Slide transition={["slide"]} bgColor="rgb(34, 34, 34)" notes="You can even put notes on your slide. How awesome is that?">
            <Image src="https://s3.amazonaws.com/media-p.slid.es/uploads/473947/images/2571254/How-to-integrate-React-D3-The-right-way-adeveloperdiary.com-4.jpg" margin="0px auto 40px" height="293px"/>
            <Heading size={2} caps fit textColor="primary" textFont="primary">
              Wait what?
            </Heading>
          </Slide>

          <Slide transition={["slide"]} bgImage="primary">
            <Heading size={1} caps fit textColor="white">
              The Problem
            </Heading>
            <Appear fid="1">
              <Heading size={.75} caps fit textColor="black">
                D3 interacts with the actual DOM
              </Heading>
            </Appear>
            <Appear fid="2">
              <Heading size={.75} caps fit textColor="black">
                React interacts with the virtual DOM
              </Heading>
            </Appear>
          </Slide>

          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              D3 will attach itself to the actual DOM
            </Heading>
            <Interactive/>
          </Slide>

          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="black">
              Which ruins React's Life Cycle
            </Heading>
            <InteractiveRemove/>
          </Slide>

          <Slide transition={["slide"]} bgImage="primary">
            <Heading size={1} caps fit textColor="white">
              The Solution
            </Heading>
            <Appear fid="1">
              <Heading size={.75} caps fit textColor="black">
                Reroute D3 to React's Virtual DOM
              </Heading>
            </Appear>
            <Appear fid="2">
              <Heading size={.75} caps fit textColor="black">
                Maintain D3's core features
              </Heading>
            </Appear>
          </Slide>

          <Slide transition={["slide"]} bgColor="primary">
            <Rd3Interactive/>
          </Slide>

          <Slide transition={["slide", "spin"]} bgColor="secondary" textColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Benefits
            </Heading>
            <List>
              <Appear><ListItem>Simple to use yet highly flexible</ListItem></Appear>
              <Appear><ListItem>Visualizations are part of React Lifecycle</ListItem></Appear>
              <Appear><ListItem>Support for entire spectrum of users</ListItem></Appear>
            </List>
          </Slide>

          <Slide transition={["slide", "spin"]} bgColor="secondary" textColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              MVP Features
            </Heading>
            <List>
              <Appear><ListItem>Converts D3 into React Components</ListItem></Appear>
              <Appear><ListItem>Create simple charts in one line of code</ListItem></Appear>
              <Appear><ListItem>Maintain React's lifecycle and D3 syntax</ListItem></Appear>
            </List>
          </Slide>

          <Slide transition={["slide", "spin"]} bgColor="secondary" textColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Coming soon
            </Heading>
            <List>
              <Appear><ListItem>Full D3 functionality such as transitions, animations, canvas tags</ListItem></Appear>
              <Appear><ListItem>Support for Redux/Flux and Immutable.js</ListItem></Appear>
              <Appear><ListItem>Expanded template library</ListItem></Appear>
            </List>
          </Slide>

          <Slide transition={["fade"]} bgColor="tertiary">
            <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
              Made with love in Codesmith by
            </Heading>
            <Image width="25%" src="http://cdn.shopify.com/s/files/1/0080/8372/products/tattly_bekka_palmer_classic_red_heart_web_design_01_grande.jpg?v=1444763442"/>
            <Heading size={.75} caps fit textColor="black">
              Andrew, Daniel, and Dave
            </Heading>
          </Slide>

        </Deck>
      </Spectacle>
    );
  }
}
<commit_msg>added new slides for presentation<commit_after>import React from "react";

import {
  Appear, BlockQuote, Cite, CodePane, Deck, Fill,
  Heading, Image, Layout, Link, ListItem, List, Markdown, Quote, Slide, Spectacle,
  TableHeaderItem, TableItem, TableRow, Table, Text
} from "../src";

import preloader from "../src/utils/preloader";

import createTheme from "../src/themes/default";

import Interactive from "../assets/interactive";

import InteractiveRemove from "../assets/interactiveRemove";

import Rd3Interactive from "../assets/rd3Interactive";

require("normalize.css");
require("../src/themes/default/index.css");

const images = {
  template: require("../assets/template.png"),
};

preloader(images);

const theme = createTheme({
  primary: "#46AAE8"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["zoom", "slide"]} transitionDuration={500}>

          <Slide transition={["zoom"]} bgColor="primary">
            <Heading size={1} fit caps lineHeight={1} textColor="black">
              React D3 Library
            </Heading>
            <Heading size={1} fit caps>
              A codesmith Presentation
            </Heading>
            <Heading size={1} fit caps textColor="black">
              where you can use d3 in react
            </Heading>
            <Link href="https://github.com/FormidableLabs/spectacle">
              <Text bold caps textColor="tertiary">it's super sweet</Text>
            </Link>
            <Text textSize="1.5em" margin="20px 0px 0px" bold>by andrew burke, danny lee, and dave loyst!</Text>
          </Slide>

          <Slide transition={["slide"]} bgColor="rgb(34, 34, 34)" notes="You can even put notes on your slide. How awesome is that?">
            <Image src="https://s3.amazonaws.com/media-p.slid.es/uploads/473947/images/2571254/How-to-integrate-React-D3-The-right-way-adeveloperdiary.com-4.jpg" margin="0px auto 40px" height="293px"/>
            <Heading size={2} caps fit textColor="primary" textFont="primary">
              Wait what?
            </Heading>
          </Slide>

          <Slide transition={["slide"]} bgImage="primary">
            <Heading size={1} caps fit textColor="white">
              The Problem
            </Heading>
              <Heading size={.75} caps fit textColor="black">
                Noise
              </Heading>
          </Slide>

          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Our Problem Demo
            </Heading>
            <Interactive/>
          </Slide>

          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="black">
              Other Solutions
            </Heading>
            <InteractiveRemove/>
          </Slide>

          <Slide transition={["slide"]} bgImage="primary">
            <Heading size={1} caps fit textColor="white">
              The Solution
            </Heading>
              <Heading size={.75} caps fit textColor="black">
                Gif
              </Heading>
          </Slide>

          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="white">
              Solution Demo
            </Heading>
            <Rd3Interactive/>
          </Slide>

          <Slide transition={["slide", "spin"]} bgColor="secondary" textColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Features
            </Heading>
            <List>
              <ListItem>Features</ListItem>
              <ListItem>Features</ListItem>
              <ListItem>Features</ListItem>
              <ListItem>Features</ListItem>
            </List>
          </Slide>

          <Slide transition={["slide", "spin"]} bgColor="secondary" textColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Challenges
            </Heading>
            <List>
              <ListItem>Features</ListItem>
              <ListItem>Features</ListItem>
              <ListItem>Features</ListItem>
              <ListItem>Features</ListItem>
            </List>
          </Slide>

          <Slide transition={["fade"]} bgColor="tertiary">
            <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
              Made with love in Codesmith by
            </Heading>
            <Image width="25%" src="http://cdn.shopify.com/s/files/1/0080/8372/products/tattly_bekka_palmer_classic_red_heart_web_design_01_grande.jpg?v=1444763442"/>
            <Heading size={.75} caps fit textColor="black">
              Andrew, Daniel, and Dave
            </Heading>
          </Slide>

        </Deck>
      </Spectacle>
    );
  }
}
<|endoftext|>


<commit_before>var Butter_tests = [{
  name: "Core",
  path: "./index.html",
  type: "Core"
}, {
  name: "Event Manager",
  path: "eventmanager/index.html",
  type: "Event"
}, {
  name: "Cornfield",
  path: "cornfield/index.html",
  type: "Cornfield"
}, {
  name: "Plugin Manager",
  path: "pluginmanager/index.html",
  type: "Plugin"
}

];
<commit_msg>Cornfield tests need to be ran from the node server<commit_after>var Butter_tests = [{
  name: "Core",
  path: "./index.html",
  type: "Core"
}, {
  name: "Event Manager",
  path: "eventmanager/index.html",
  type: "Event"
}, {
  name: "Cornfield",
  path: "http://localhost:8888/test/cornfield/index.html",
  type: "Cornfield"
}, {
  name: "Plugin Manager",
  path: "pluginmanager/index.html",
  type: "Plugin"
}

];
<|endoftext|>


<commit_before>/**
 * .reel Unit Test
 */
window.onload= ( function run(){

  yepnope( {
    load: [
      'http://code.jquery.com/jquery-'+(location.params.jq || '1.6.4')+'.min.js',
      '../jquery.reel-min.js',
      '../example/inc/jquery.disabletextselect-min.js',
      '../example/inc/jquery.mousewheel-min.js',

      'qunit/qunit.js',
      'qunit/quny.js',

      'unit/selector.js',
      'unit/parameters.js',
      'unit/events.js',
      'unit/computation.js',
      'unit/animation.js',
      'unit/rendering.js',
      'unit/data.js',
      'unit/api.js',
      'unit/interaction.js',
      'unit/sprite.js',
      'unit/issues.js'
    ],
    complete: function(){

      QUnit.load();

      QUnit.done = function(failures, total, config) {
        if (failures){
          $('body').addClass('failure');
        }

        /*
         * Results of the just finished testrun are automatically submitted
         * and collected on the Reel webserver as a kind of distributed
         * testing effort. Thanks for being a part of it!
         *
         * Data collected:
         * - timestamp
         * - counts (total number of tests, fails, passes)
         * - failures themselves
         * - versions (version of jQuery and Reel)
         * - the results summary line with duration
         * - user agent string (your browser name and its version(s))
         */
        var
          //server= 'http://au:4567',
          server= 'http://jquery.vostrel.cz',
          timestamp= +new Date(),
          report= {
            timestamp:  timestamp,
            filter:     config.filters,
            count: {
              total:    total,
              pass:     total - failures,
              fail:     failures
            },
            fails:      dump($('#qunit-tests li.fail')),
            version: {
              jquery:   $().jquery,
              reel:     $.reel.version
            },
            results:    $('#qunit-testresult').html(),
            agent:      $('#qunit-userAgent').html()
          }

        $('<a/>', { name: 'receipt' }).appendTo('#qunit-testresult');
        formatted(report, 'Carbon copy of the receipt, which has been sent out to central Reel test server. Thank you!').appendTo( $('<ul/>').appendTo('#qunit-testresult') );
        $.post(server+'/collect/reel/testrun/results', report);

        function formatted( bit, label ){
          var $result= $('<li/>')
          if( typeof bit == 'object' ){
            if( typeof bit.length != 'number' || bit.length > 0 ){ // Object/Array
              $result.text( label+':' );
              var $list= $('<ul/>').appendTo( $result )
              $.each( bit, function( label, value ){
                $list.append( formatted(value, label) );
              } );
            }
          }else{ // Value
            $result.html( label+': '+bit );
          }
          return $result
        }

        function dump($collection){
          var collection = [];
          $collection.each(function(){
            collection.push($(this).html())
          })
          return collection;
        }
      }

      $('#against-jquery-versions')
      .val( location.params.jq || '1.6.4' )
      .change( function(){
        var url= ''
        if( location.params.jq === undefined ){
          if( location.search === '' ){
            url= location.href.replace( /\?$/, '' ) + '?jq='+$(this).val()
          }else{
            url= location.href + '&jq=' + $(this).val()
          }
        }else{
          url= location.href.replace( 'jq=' + location.params.jq, 'jq=' + $(this).val() );
        }
        location.href= url;
      } )

    }
  } );

} );
<commit_msg>That didn't work either. Reverting to the former and moving the selector tests further in the stack.<commit_after>/**
 * .reel Unit Test
 */
( function run(){

  yepnope( {
    load: [
      'http://code.jquery.com/jquery-'+(location.params.jq || '1.6.4')+'.min.js',
      '../jquery.reel-min.js',
      '../example/inc/jquery.disabletextselect-min.js',
      '../example/inc/jquery.mousewheel-min.js',

      'qunit/qunit.js',
      'qunit/quny.js',

      'unit/parameters.js',
      'unit/events.js',
      'unit/computation.js',
      'unit/animation.js',
      'unit/selector.js',
      'unit/rendering.js',
      'unit/data.js',
      'unit/api.js',
      'unit/interaction.js',
      'unit/sprite.js',
      'unit/issues.js'
    ],
    complete: function(){

      QUnit.load();

      QUnit.done = function(failures, total, config) {
        if (failures){
          $('body').addClass('failure');
        }

        /*
         * Results of the just finished testrun are automatically submitted
         * and collected on the Reel webserver as a kind of distributed
         * testing effort. Thanks for being a part of it!
         *
         * Data collected:
         * - timestamp
         * - counts (total number of tests, fails, passes)
         * - failures themselves
         * - versions (version of jQuery and Reel)
         * - the results summary line with duration
         * - user agent string (your browser name and its version(s))
         */
        var
          //server= 'http://au:4567',
          server= 'http://jquery.vostrel.cz',
          timestamp= +new Date(),
          report= {
            timestamp:  timestamp,
            filter:     config.filters,
            count: {
              total:    total,
              pass:     total - failures,
              fail:     failures
            },
            fails:      dump($('#qunit-tests li.fail')),
            version: {
              jquery:   $().jquery,
              reel:     $.reel.version
            },
            results:    $('#qunit-testresult').html(),
            agent:      $('#qunit-userAgent').html()
          }

        $('<a/>', { name: 'receipt' }).appendTo('#qunit-testresult');
        formatted(report, 'Carbon copy of the receipt, which has been sent out to central Reel test server. Thank you!').appendTo( $('<ul/>').appendTo('#qunit-testresult') );
        $.post(server+'/collect/reel/testrun/results', report);

        function formatted( bit, label ){
          var $result= $('<li/>')
          if( typeof bit == 'object' ){
            if( typeof bit.length != 'number' || bit.length > 0 ){ // Object/Array
              $result.text( label+':' );
              var $list= $('<ul/>').appendTo( $result )
              $.each( bit, function( label, value ){
                $list.append( formatted(value, label) );
              } );
            }
          }else{ // Value
            $result.html( label+': '+bit );
          }
          return $result
        }

        function dump($collection){
          var collection = [];
          $collection.each(function(){
            collection.push($(this).html())
          })
          return collection;
        }
      }

      $('#against-jquery-versions')
      .val( location.params.jq || '1.6.4' )
      .change( function(){
        var url= ''
        if( location.params.jq === undefined ){
          if( location.search === '' ){
            url= location.href.replace( /\?$/, '' ) + '?jq='+$(this).val()
          }else{
            url= location.href + '&jq=' + $(this).val()
          }
        }else{
          url= location.href.replace( 'jq=' + location.params.jq, 'jq=' + $(this).val() );
        }
        location.href= url;
      } )

    }
  } );

} )();
<|endoftext|>


<commit_before>var assert =  require("chai").assert;
var cmds = require("../commands/commands");

describe("Command", function() {
	describe("#get()", function() {
		it("should return null if command doesn't exist", function() {
			assert.equal(null, cmds.get("test"));
		});
		it("should not return a command if command exists", function() {
			assert.typeOf(cmds.get("ping"), Command);
		});
	});
});
<commit_msg>Updated unit tests<commit_after>var assert =  require("chai").assert;
var cmds = require("../commands/commands");

function Command(cmd, descr, action, hidden = false) {
	this.cmd = cmd;
	this.description = descr;
	this.action = action;
	this.hidden = hidden;
	//commands[cmd]=this;
}

describe("Command", function() {
	describe("#get()", function() {
		it("should return null if command doesn't exist", function() {
			assert.equal(null, cmds.get("test"));
		});
		it("should return a command if command exists", function() {
			assert.typeOf(cmds.get("ping"), Command);
		});
	});
});
<|endoftext|>


<commit_before>/* global QUnit:false, module:false, test:false, asyncTest:false, expect:false */
/* global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false */
/* global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false */

define(function testWrapper (require) {
	var $ = require('jquery');
	var QUnit = require('qunit');

	QUnit.start(); // starting qunit, or phantom js will have a problem

	// Needed for saucelab testing
	var log = [];

	QUnit.done(function qUnitDone (testResults) {
		var tests = [];
		for (var i = 0, len = log.length; i < len; i++) {
			var details = log[i];
			tests.push({
				name: details.name,
				result: details.result,
				expected: details.expected,
				actual: details.actual,
				source: details.source
			});
		}
		testResults.tests = tests;

		window.global_test_results = testResults;

		// hide passed tests, helps with VM testing screencasts
		if (!$('#qunit-filter-pass').is(':checked')) {
			$('#qunit-filter-pass').click();
		}
	});
	QUnit.testStart(function testStart (testDetails) {
		QUnit.log = function qUnitLog (details) {
			if (!details.result) {
				details.name = testDetails.name;
				log.push(details);
			}
		};
	});

	require('moment');
	require('./test/checkbox-test');
	// require('./test/combobox-test');
	// require('./test/datepicker-moment-test');
	// require('./test/infinite-scroll-test');
	// require('./test/loader-test');
	// require('./test/pillbox-test');
	// require('./test/placard-test');
	// require('./test/radio-test');
	// require('./test/repeater-test');
	// require('./test/repeater-list-test');
	// require('./test/repeater-thumbnail-test');
	// require('./test/scheduler-test');
	// require('./test/search-test');
	// require('./test/selectlist-test');
	// require('./test/spinbox-test');
	// require('./test/picker-test');
	// require('./test/tree-test');
	// require('./test/wizard-test');
});
<commit_msg>(GH1972) puts back non-checkbox unit tests<commit_after>/* global QUnit:false, module:false, test:false, asyncTest:false, expect:false */
/* global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false */
/* global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false */

define(function testWrapper (require) {
	var $ = require('jquery');
	var QUnit = require('qunit');

	QUnit.start(); // starting qunit, or phantom js will have a problem

	// Needed for saucelab testing
	var log = [];

	QUnit.done(function qUnitDone (testResults) {
		var tests = [];
		for (var i = 0, len = log.length; i < len; i++) {
			var details = log[i];
			tests.push({
				name: details.name,
				result: details.result,
				expected: details.expected,
				actual: details.actual,
				source: details.source
			});
		}
		testResults.tests = tests;

		window.global_test_results = testResults;

		// hide passed tests, helps with VM testing screencasts
		if (!$('#qunit-filter-pass').is(':checked')) {
			$('#qunit-filter-pass').click();
		}
	});
	QUnit.testStart(function testStart (testDetails) {
		QUnit.log = function qUnitLog (details) {
			if (!details.result) {
				details.name = testDetails.name;
				log.push(details);
			}
		};
	});

	require('moment');
	require('./test/checkbox-test');
	require('./test/combobox-test');
	require('./test/datepicker-moment-test');
	require('./test/infinite-scroll-test');
	require('./test/loader-test');
	require('./test/pillbox-test');
	require('./test/placard-test');
	require('./test/radio-test');
	require('./test/repeater-test');
	require('./test/repeater-list-test');
	require('./test/repeater-thumbnail-test');
	require('./test/scheduler-test');
	require('./test/search-test');
	require('./test/selectlist-test');
	require('./test/spinbox-test');
	require('./test/picker-test');
	require('./test/tree-test');
	require('./test/wizard-test');
	require('./test/utilities-test');
});
<|endoftext|>


<commit_before>import * as Kefir from "kefir"
import * as R     from "ramda"
import * as L     from "partial.lenses"

import Atom, {Molecule, holding} from "../src/kefir.atom"

function show(x) {
  switch (typeof x) {
    case "string":
    case "object":
      return JSON.stringify(x)
    default:
      return `${x}`
  }
}

Kefir.Observable.prototype.orAsync = function (y) {
  return this.merge(Kefir.later(0, y))
}

const testEq = (expr, expect) => it(`${expr} => ${show(expect)}`, done => {
  const actual = eval(`(Atom, Kefir, L, R, Molecule, holding) => ${expr}`)(
                        Atom, Kefir, L, R, Molecule, holding)
  const check = actual => {
    if (!R.equals(actual, expect))
      throw new Error(`Expected: ${show(expect)}, actual: ${show(actual)}`)
    done()
  }
  if (actual instanceof Kefir.Observable)
    actual.take(1).onValue(check)
  else
    check(actual)
})

describe("Atom", () => {
  testEq('{const xy = Atom({x: {y: 1}}); return xy.orAsync("test bug")}', {x: {y: 1}})
  testEq('{const xy = Atom({x: {y: 1}}); xy.set({x: {y: 2}}) ; return xy.get()}', {x: {y: 2}})
  testEq('{const xy = Atom({x: 1, y: 2}); xy.lens("x").remove(); return xy}', {y: 2})
  testEq('{const xy = Atom({x: {y: 1}}), y = xy.lens("x"); return y.get()}', {y: 1})
  testEq('{const xy = Atom({x: {y: 1}}), y = xy.lens("x"); y.set({y: 3}); return y}', {y: 3})
  testEq('{const xy = Atom({x: {y: 2}}), y = xy.lens("x"), z = y.lens("y"); return z}', 2)
  testEq('{const xy = Atom({x: {y: 3}}), z = xy.lens("x", "y"); z.set(2); return z}', 2)
  testEq('{const xy = Atom({x: {y: 3}}), z = xy.view("x", "y"); return z.get()}', 3)
})

describe("holding", () => {
  testEq('{const a = Atom({x: 1}), b = a.lens("x"); let n = 0; const inc = () => ++n; a.onValue(inc); b.onValue(inc); holding(() => {a.set({x: 2}); b.set(1)}); return n}', 2)
  testEq('{const a = Atom({x: 1}), b = a.lens("x"); let n = 0; const inc = () => ++n; a.onValue(inc); b.onValue(inc); holding(() => {a.set({x: 2}); b.set(3)}); return n}', 4)
  testEq('{const a = Atom({x: 1}), b = a.lens("x"); return holding(() => {a.set({x: 2}); return b.get()})}', 2)
})

describe("Molecule", () => {
  testEq('{const x = new Molecule([{x: Atom(1)}, {y: 2}, Atom(3)]); return x}', [{x: 1}, {y: 2}, 3])
  testEq('{const x = Atom(1), y = Atom(2), xy = new Molecule({x, z: ["z"], y: [y]}); xy.lens(L.props("x", "y")).set({x: 3, y: [4]}); return Kefir.combine([x, y, xy])}', [3, 4, {x: 3, z: ["z"], y: [4]}])
})

describe("variable", () => {
  testEq('{const x = Atom(); return x.get()}', undefined)
  testEq('{const x = Atom(); return x.orAsync(1)}', 1)
  testEq('{const x = Atom(), y = x.lens("lol"); return y.get()}', undefined)
  testEq('{const x = Atom(), y = x.lens("lol"); return y.orAsync(1)}', 1)
  testEq('{const x = Atom(), y = new Molecule({x}); return y.get()}', {x: undefined})
  testEq('{const x = Atom(), y = new Molecule({x}); return x.orAsync(1)}', 1)
  testEq('{const x = Atom(), y = x.lens("y"); let r = "initial"; y.onValue(y => r = y); return r}', "initial")
  testEq('{const x = Atom(), y = x.lens("y"); let r = "initial"; y.onValue(y => r = y); x.set({y: 1}); return r}', 1)
  testEq('{const x = Atom(), y = x.lens("y"); let r = "initial"; y.onValue(y => r = y); holding(() => x.set({y: 1})); return r}', 1)
})
<commit_msg>Test that changes are propagated after holding in program order<commit_after>import * as Kefir from "kefir"
import * as R     from "ramda"
import * as L     from "partial.lenses"

import Atom, {Molecule, holding} from "../src/kefir.atom"

function show(x) {
  switch (typeof x) {
    case "string":
    case "object":
      return JSON.stringify(x)
    default:
      return `${x}`
  }
}

Kefir.Observable.prototype.orAsync = function (y) {
  return this.merge(Kefir.later(0, y))
}

const testEq = (expr, expect) => it(`${expr} => ${show(expect)}`, done => {
  const actual = eval(`(Atom, Kefir, L, R, Molecule, holding) => ${expr}`)(
                        Atom, Kefir, L, R, Molecule, holding)
  const check = actual => {
    if (!R.equals(actual, expect))
      throw new Error(`Expected: ${show(expect)}, actual: ${show(actual)}`)
    done()
  }
  if (actual instanceof Kefir.Observable)
    actual.take(1).onValue(check)
  else
    check(actual)
})

describe("Atom", () => {
  testEq('{const xy = Atom({x: {y: 1}}); return xy.orAsync("test bug")}', {x: {y: 1}})
  testEq('{const xy = Atom({x: {y: 1}}); xy.set({x: {y: 2}}) ; return xy.get()}', {x: {y: 2}})
  testEq('{const xy = Atom({x: 1, y: 2}); xy.lens("x").remove(); return xy}', {y: 2})
  testEq('{const xy = Atom({x: {y: 1}}), y = xy.lens("x"); return y.get()}', {y: 1})
  testEq('{const xy = Atom({x: {y: 1}}), y = xy.lens("x"); y.set({y: 3}); return y}', {y: 3})
  testEq('{const xy = Atom({x: {y: 2}}), y = xy.lens("x"), z = y.lens("y"); return z}', 2)
  testEq('{const xy = Atom({x: {y: 3}}), z = xy.lens("x", "y"); z.set(2); return z}', 2)
  testEq('{const xy = Atom({x: {y: 3}}), z = xy.view("x", "y"); return z.get()}', 3)
})

describe("holding", () => {
  testEq('{const a = Atom({x: 1}), b = a.lens("x"); let n = 0; const inc = () => ++n; a.onValue(inc); b.onValue(inc); holding(() => {a.set({x: 2}); b.set(1)}); return n}', 2)
  testEq('{const a = Atom({x: 1}), b = a.lens("x"); let n = 0; const inc = () => ++n; a.onValue(inc); b.onValue(inc); holding(() => {a.set({x: 2}); b.set(3)}); return n}', 4)
  testEq('{const a = Atom({x: 1}), b = a.lens("x"); return holding(() => {a.set({x: 2}); return b.get()})}', 2)
  testEq('{const a = Atom("a1"), b = Atom("b1"); let r = ""; a.merge(b).onValue(x => r = r + x); holding(() => {a.set("a2"); b.set("b2")}); return r}', "a1b1a2b2")
})

describe("Molecule", () => {
  testEq('{const x = new Molecule([{x: Atom(1)}, {y: 2}, Atom(3)]); return x}', [{x: 1}, {y: 2}, 3])
  testEq('{const x = Atom(1), y = Atom(2), xy = new Molecule({x, z: ["z"], y: [y]}); xy.lens(L.props("x", "y")).set({x: 3, y: [4]}); return Kefir.combine([x, y, xy])}', [3, 4, {x: 3, z: ["z"], y: [4]}])
})

describe("variable", () => {
  testEq('{const x = Atom(); return x.get()}', undefined)
  testEq('{const x = Atom(); return x.orAsync(1)}', 1)
  testEq('{const x = Atom(), y = x.lens("lol"); return y.get()}', undefined)
  testEq('{const x = Atom(), y = x.lens("lol"); return y.orAsync(1)}', 1)
  testEq('{const x = Atom(), y = new Molecule({x}); return y.get()}', {x: undefined})
  testEq('{const x = Atom(), y = new Molecule({x}); return x.orAsync(1)}', 1)
  testEq('{const x = Atom(), y = x.lens("y"); let r = "initial"; y.onValue(y => r = y); return r}', "initial")
  testEq('{const x = Atom(), y = x.lens("y"); let r = "initial"; y.onValue(y => r = y); x.set({y: 1}); return r}', 1)
  testEq('{const x = Atom(), y = x.lens("y"); let r = "initial"; y.onValue(y => r = y); holding(() => x.set({y: 1})); return r}', 1)
})
<|endoftext|>


<commit_before>require(['config'], function () {
  // load expect, mocha and sinon stuff
  require([
    'jquery',
    'expect',
    'mocha',
    'sinon'
  ], function (jquery, expect, mocha, sinon) {
    // setup mocha
    mocha.checkLeaks();
    mocha.setup('bdd');
    mocha.reporter('html');

    // load then Parsley modules for UT
    require([
      'src/parsley',
      'parsley/form',
      'parsley/field',
      'parsley/ui',
      'parsley/utils',
      'parsley/validator',
      'i18n/fr'
    ], function (Parsley, ParsleyForm, ParsleyField, ParsleyUI, ParsleyUtils, ParsleyValidator) {

      // load full parsley.js + UT
      require([
        'features/utils',
        'features/parsley',
        'features/pubsub',
        'features/abstract',
        'features/field',
        'features/multiple',
        'features/form',
        'features/validator',
        'features/ui'
      ], function (utils, parsleyBase, pubsub, abstract, field, multiple, form, validator, ui) {
        describe('ParsleyStandard', function () {
          // Use a pristine ParsleyExtend for the standard suite:
          var previousExtend;
          before(function () {
            previousExtend = window.ParsleyExtend;
            window.ParsleyExtend = {};
          });
          after(function () {
            window.ParsleyExtend = previousExtend;
          });
          utils(ParsleyUtils);
          parsleyBase(Parsley);
          pubsub();
          abstract(Parsley);
          field(ParsleyField, Parsley);
          multiple(Parsley);
          form(ParsleyForm, Parsley);
          validator(ParsleyValidator);
          ui(ParsleyUI);
        });

        // tested by it('should handle remote validator option') in `features/remote`
        window.ParsleyExtend = {
          asyncValidators: {
            custom: {
              fn: function (xhr) {
                return xhr.status === 404;
              }
            }
          }
        };

        require([
          'features/remote',
          'features/abstract',
          'features/field',
          'features/form'
        ], function (remote, abstract, field, form) {
          describe('Parsley+Remote', function () {
            // beforeEach(function () {
            //   window.ParsleyConfig = $.extend(true, {}, window.ParsleyConfig, { excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden], input[disabled]' });
            // });
            remote(ParsleyExtend);
            abstract(Parsley);
            field(ParsleyField, Parsley);
            form(ParsleyForm, Parsley);
          });

          require([
            'features/extra'
          ], function (extra) {
            extra(ParsleyValidator);

            // run mocha
            if (window.mochaPhantomJS)
              mochaPhantomJS.run();
            else
              mocha.run();
          });
        });
      });
    });
  });
});
<commit_msg>expect and sinon are not returned from load. Rename so we can use globals<commit_after>require(['config'], function () {
  // load expect, mocha and sinon stuff
  require([
    'jquery',
    'expect',
    'mocha',
    'sinon'
  ], function (jquery, _expect, mocha, _sinon) {
    // setup mocha
    mocha.checkLeaks();
    mocha.setup('bdd');
    mocha.reporter('html');

    // load then Parsley modules for UT
    require([
      'src/parsley',
      'parsley/form',
      'parsley/field',
      'parsley/ui',
      'parsley/utils',
      'parsley/validator',
      'i18n/fr'
    ], function (Parsley, ParsleyForm, ParsleyField, ParsleyUI, ParsleyUtils, ParsleyValidator) {

      // load full parsley.js + UT
      require([
        'features/utils',
        'features/parsley',
        'features/pubsub',
        'features/abstract',
        'features/field',
        'features/multiple',
        'features/form',
        'features/validator',
        'features/ui'
      ], function (utils, parsleyBase, pubsub, abstract, field, multiple, form, validator, ui) {
        describe('ParsleyStandard', function () {
          // Use a pristine ParsleyExtend for the standard suite:
          var previousExtend;
          before(function () {
            previousExtend = window.ParsleyExtend;
            window.ParsleyExtend = {};
          });
          after(function () {
            window.ParsleyExtend = previousExtend;
          });
          utils(ParsleyUtils);
          parsleyBase(Parsley);
          pubsub();
          abstract(Parsley);
          field(ParsleyField, Parsley);
          multiple(Parsley);
          form(ParsleyForm, Parsley);
          validator(ParsleyValidator);
          ui(ParsleyUI);
        });

        // tested by it('should handle remote validator option') in `features/remote`
        window.ParsleyExtend = {
          asyncValidators: {
            custom: {
              fn: function (xhr) {
                return xhr.status === 404;
              }
            }
          }
        };

        require([
          'features/remote',
          'features/abstract',
          'features/field',
          'features/form'
        ], function (remote, abstract, field, form) {
          describe('Parsley+Remote', function () {
            // beforeEach(function () {
            //   window.ParsleyConfig = $.extend(true, {}, window.ParsleyConfig, { excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden], input[disabled]' });
            // });
            remote(ParsleyExtend);
            abstract(Parsley);
            field(ParsleyField, Parsley);
            form(ParsleyForm, Parsley);
          });

          require([
            'features/extra'
          ], function (extra) {
            extra(ParsleyValidator);

            // run mocha
            if (window.mochaPhantomJS)
              mochaPhantomJS.run();
            else
              mocha.run();
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var request = require('request');
var assert = require('assert');
var http = require('http');
var app = require('../app');
var _ = require('lodash');

var api = app.get('api');

var server = http.createServer(app);
var port = 3001;
var url = 'http://localhost:' + port + '/api/users';
var srvUser = {
  id: '1234',
  name: 'user 1',
  email: 'name1@my.com'
};

var srvUser2 = {
  id: '2234',
  name: 'user 2',
  email: 'name2@my.com'
};

var srvUser3 = {
  id: '3234',
  name: 'user 3',
  email: 'name3@my.com'
};

describe('REST API for /users', function(){
  before (function(done){
    api.data.users = [srvUser, srvUser2];

    server.listen(port, done);
  });

  after (function(done){
    server.close(done);
  });

  it ('should return list of users', function(done) {

    request.get({url:url, json:true}, function(err, res, body){
      // console.log(body);
      assert.equal(2, body.length);
      var user = body[0];
      assert.ok(user);
      assert.deepEqual(srvUser, user);
      done();
    });

  });

  it ('should get user by id', function(done){

    request.get({url:url+'/1234', json:true}, function(err, res, body){
      var user = body;
      assert.deepEqual(srvUser, user);
      done();
    });

  });

  it ('should error when unknown user id', function(done){

    request.get({url:url+'/1235', json:true}, function(err, res, body){
      assert.equal(404, res.statusCode);
      done();
    });

  });

  it ('should create user', function(done){

    request.post({url:url, json:true, body:srvUser3}, function(err, res, body){
      assert.equal(200, res.statusCode);

      var user = _.find(api.data.users, srvUser3);
      assert.ok(user);

      done();
    });

  });
});
<commit_msg>POST for existant user: red<commit_after>var request = require('request');
var assert = require('assert');
var http = require('http');
var app = require('../app');
var _ = require('lodash');

var api = app.get('api');

var server = http.createServer(app);
var port = 3001;
var url = 'http://localhost:' + port + '/api/users';
var srvUser = {
  id: '1234',
  name: 'user 1',
  email: 'name1@my.com'
};

var srvUser2 = {
  id: '2234',
  name: 'user 2',
  email: 'name2@my.com'
};

var srvUser3 = {
  id: '3234',
  name: 'user 3',
  email: 'name3@my.com'
};

describe('REST API for /users', function(){
  before (function(done){
    api.data.users = [srvUser, srvUser2];

    server.listen(port, done);
  });

  after (function(done){
    server.close(done);
  });

  it ('should return list of users', function(done) {

    request.get({url:url, json:true}, function(err, res, body){
      // console.log(body);
      assert.equal(2, body.length);
      var user = body[0];
      assert.ok(user);
      assert.deepEqual(srvUser, user);
      done();
    });

  });

  it ('should get user by id', function(done){

    request.get({url:url+'/1234', json:true}, function(err, res, body){
      var user = body;
      assert.deepEqual(srvUser, user);
      done();
    });

  });

  it ('should error when unknown user id', function(done){

    request.get({url:url+'/1235', json:true}, function(err, res, body){
      assert.equal(404, res.statusCode);
      done();
    });

  });

  it ('should create user', function(done){
    api.data.users = [srvUser, srvUser2];

    request.post({url:url, json:true, body:srvUser3}, function(err, res, body){
      assert.equal(200, res.statusCode);

      var user = _.find(api.data.users, srvUser3);
      assert.ok(user);

      done();
    });
  });

  it ('should not create existant user', function(done){
    api.data.users = [srvUser, srvUser2];

    request.post({url:url, json:true, body:srvUser2}, function(err, res, body){
      assert.equal(400, res.statusCode);

      done();
    });
  });

});
<|endoftext|>


<commit_before>module.exports.base = {
  devDependencies: {
    'eslint': '^3.2.2',
    'eslint-config-xo-space': '^0.12.0'
  },
  eslintConfig: {
    root: true,
    env: {
      browser: true,
      jasmine: true
    }
  }
};

module.exports.vueBase = {
  devDependencies: {
    'babel-plugin-transform-object-rest-spread': '^6.8.0',
    'eslint-plugin-html': '^1.5.2',
    'babel-plugin-transform-runtime': '^6.12.0',
    'babel-runtime': '^6.11.6'
  },
  eslintConfig: {
    plugins: ['html']
  }
};

module.exports.reactBase = {
  devDependencies: {
    'babel-preset-react': '^6.1.18',
    'eslint-config-xo-react': '^0.7.0',
    'eslint-plugin-react': '^5.0.1'
  },
  eslintConfig: {
    extends: [
      'xo-react/space'
    ]
  }
};

module.exports.jsBase = {
  eslintConfig: {
    extends: [
      'xo-space'
    ]
  }
};

module.exports.angular1Base = {
  devDependencies: {
    'eslint-config-angular': '^0.5.0',
    'eslint-plugin-angular': '^1.3.0'
  }
};

module.exports.injectAngular1 = {
  eslintConfig: {
    globals: {
      angular: true
    }
  }
};

module.exports.babelBase = {
  devDependencies: {
    'babel-preset-es2015': '^6.2.0',
    'babel-core': '^6.13.0',
    'babel-polyfill': '^6.7.4'
  }
};

module.exports.angular2NotTypescriptBase = {
  eslintConfig: {
    rules: {
      'new-cap': [2, {capIsNewExceptions: ['Input', 'Output', 'Component', 'Injectable', 'RouteConfig', 'Class', 'ViewChild', 'Directive', 'Pipe', 'NgModule']}]
    }
  }
};

module.exports.systemjsAngular2 = {
  jspm: {
    devDependencies: {
      'babel-plugin-transform-es2015-typeof-symbol': 'npm:babel-plugin-transform-es2015-typeof-symbol@^6.8.0',
      'babel-plugin-angular2-annotations': 'npm:babel-plugin-angular2-annotations@^5.0.0',
      'babel-plugin-transform-decorators-legacy': 'npm:babel-plugin-transform-decorators-legacy@^1.3.4',
      'babel-plugin-transform-class-properties': 'npm:babel-plugin-transform-class-properties@^6.6.0',
      'babel-plugin-transform-flow-strip-types': 'npm:babel-plugin-transform-flow-strip-types@^6.6.4'
    }
  },
  eslintConfig: {
    globals: {
      __moduleName: true
    }
  }
};

module.exports.babelTypescriptBase = {
  devDependencies: {
    'babel-eslint': '^6.0.2',
    'eslint-plugin-babel': '^3.1.0'
  },
  eslintConfig: {
    extends: [
      'xo-space/esnext'
    ]
  }
};

module.exports.webpackBase = {
  devDependencies: {
    'eslint-loader': '^1.3.0',
    'babel-loader': '^6.2.0'
  }
};

module.exports.systemjsBase = {
  devDependencies: {
    'gulp-eslint': '^2.0.0'
  },
  eslintConfig: {
    globals: {
      SystemJS: true
    }
  }
};

module.exports.injectBase = {
  devDependencies: {
    'gulp-eslint': '^2.0.0'
  }
};

module.exports.systemjsReactBase = {
  jspm: {
    devDependencies: {
      'babel-preset-react': 'npm:babel-preset-react@^6.5.0'
    }
  }
};

module.exports.injectReactBase = {
  eslintConfig: {
    globals: {
      React: true,
      ReactDOM: true,
      axios: true
    },
    rules: {
      'react/jsx-no-undef': 0,
      'no-undef': 0,
      'no-unused-vars': 0
    }
  }
};
<commit_msg>Fix tests<commit_after>module.exports.base = {
  devDependencies: {
    'eslint': '^3.2.2',
    'eslint-config-xo-space': '^0.12.0'
  },
  eslintConfig: {
    root: true,
    env: {
      browser: true,
      jasmine: true
    }
  }
};

module.exports.vueBase = {
  devDependencies: {
    'babel-plugin-transform-object-rest-spread': '^6.8.0',
    'eslint-plugin-html': '^1.5.2',
    'babel-plugin-transform-runtime': '^6.12.0',
    'babel-runtime': '^6.11.6'
  },
  eslintConfig: {
    plugins: ['html']
  }
};

module.exports.reactBase = {
  devDependencies: {
    'babel-preset-react': '^6.1.18',
    'eslint-config-xo-react': '^0.7.0',
    'eslint-plugin-react': '^5.0.1'
  },
  eslintConfig: {
    extends: [
      'xo-react/space'
    ]
  }
};

module.exports.jsBase = {
  eslintConfig: {
    extends: [
      'xo-space'
    ]
  }
};

module.exports.angular1Base = {
  devDependencies: {
    'eslint-config-angular': '^0.5.0',
    'eslint-plugin-angular': '^1.3.0'
  }
};

module.exports.injectAngular1 = {
  eslintConfig: {
    globals: {
      angular: true
    }
  }
};

module.exports.babelBase = {
  devDependencies: {
    'babel-preset-es2015': '^6.2.0',
    'babel-core': '^6.13.0',
    'babel-polyfill': '^6.7.4'
  }
};

module.exports.angular2NotTypescriptBase = {
  eslintConfig: {
    rules: {
      'new-cap': 0
    }
  }
};

module.exports.systemjsAngular2 = {
  jspm: {
    devDependencies: {
      'babel-plugin-transform-es2015-typeof-symbol': 'npm:babel-plugin-transform-es2015-typeof-symbol@^6.8.0',
      'babel-plugin-angular2-annotations': 'npm:babel-plugin-angular2-annotations@^5.0.0',
      'babel-plugin-transform-decorators-legacy': 'npm:babel-plugin-transform-decorators-legacy@^1.3.4',
      'babel-plugin-transform-class-properties': 'npm:babel-plugin-transform-class-properties@^6.6.0',
      'babel-plugin-transform-flow-strip-types': 'npm:babel-plugin-transform-flow-strip-types@^6.6.4'
    }
  },
  eslintConfig: {
    globals: {
      __moduleName: true
    }
  }
};

module.exports.babelTypescriptBase = {
  devDependencies: {
    'babel-eslint': '^6.0.2',
    'eslint-plugin-babel': '^3.1.0'
  },
  eslintConfig: {
    extends: [
      'xo-space/esnext'
    ]
  }
};

module.exports.webpackBase = {
  devDependencies: {
    'eslint-loader': '^1.3.0',
    'babel-loader': '^6.2.0'
  }
};

module.exports.systemjsBase = {
  devDependencies: {
    'gulp-eslint': '^2.0.0'
  },
  eslintConfig: {
    globals: {
      SystemJS: true
    }
  }
};

module.exports.injectBase = {
  devDependencies: {
    'gulp-eslint': '^2.0.0'
  }
};

module.exports.systemjsReactBase = {
  jspm: {
    devDependencies: {
      'babel-preset-react': 'npm:babel-preset-react@^6.5.0'
    }
  }
};

module.exports.injectReactBase = {
  eslintConfig: {
    globals: {
      React: true,
      ReactDOM: true,
      axios: true
    },
    rules: {
      'react/jsx-no-undef': 0,
      'no-undef': 0,
      'no-unused-vars': 0
    }
  }
};
<|endoftext|>


<commit_before>function createCanvas(w, h) {
	var canvas = document.createElement('canvas');
	canvas.width = w;
	canvas.height = h;
	return canvas;
}

function readImageData(url, callback) {
	var image = new Image();

	image.onload = function() {
		var h = image.height;
		var w = image.width;
		var canvas = createCanvas(w, h);
		var ctx = canvas.getContext('2d');
		ctx.drawImage(image, 0, 0, w, h);
		callback(ctx.getImageData(0, 0, w, h));
	};

	image.src = url;
}

/**
 * Injects a new canvas (and div wrapper) and creates teh associated Chart instance
 * using the given config. Additional options allow tweaking elements generation.
 * @param {object} config - Chart config.
 * @param {object} options - Chart acquisition options.
 * @param {object} options.canvas - Canvas attributes.
 * @param {object} options.wrapper - Canvas wrapper attributes.
 * @param {boolean} options.persistent - If true, the chart will not be released after the spec.
 */
function acquireChart(config, options) {
	var wrapper = document.createElement('div');
	var canvas = document.createElement('canvas');
	var chart, key;

	config = config || {};
	options = options || {};
	options.canvas = options.canvas || {height: 512, width: 512};
	options.wrapper = options.wrapper || {class: 'chartjs-wrapper'};

	for (key in options.canvas) {
		if (options.canvas.hasOwnProperty(key)) {
			canvas.setAttribute(key, options.canvas[key]);
		}
	}

	for (key in options.wrapper) {
		if (options.wrapper.hasOwnProperty(key)) {
			wrapper.setAttribute(key, options.wrapper[key]);
		}
	}

	// by default, remove chart animation and auto resize
	config.options = config.options || {};
	config.options.animation = config.options.animation === undefined ? false : config.options.animation;
	config.options.responsive = config.options.responsive === undefined ? false : config.options.responsive;
	config.options.defaultFontFamily = config.options.defaultFontFamily || 'Arial';

	wrapper.appendChild(canvas);
	window.document.body.appendChild(wrapper);

	try {
		chart = new Chart(canvas.getContext('2d'), config);
	} catch (e) {
		window.document.body.removeChild(wrapper);
		throw e;
	}

	chart.$test = {
		persistent: options.persistent,
		wrapper: wrapper
	};

	return chart;
}

function releaseChart(chart) {
	chart.destroy();

	var wrapper = (chart.$test || {}).wrapper;
	if (wrapper && wrapper.parentNode) {
		wrapper.parentNode.removeChild(wrapper);
	}
}

function injectCSS(css) {
	// https://stackoverflow.com/q/3922139
	var head = document.getElementsByTagName('head')[0];
	var style = document.createElement('style');
	style.setAttribute('type', 'text/css');
	if (style.styleSheet) { // IE
		style.styleSheet.cssText = css;
	} else {
		style.appendChild(document.createTextNode(css));
	}
	head.appendChild(style);
}

function waitForResize(chart, callback) {
	var override = chart.resize;
	chart.resize = function() {
		chart.resize = override;
		override.apply(this, arguments);
		callback();
	};
}

function _resolveElementPoint(el) {
	var point = {x: 0, y: 0};
	if (el) {
		if (typeof el.getCenterPoint === 'function') {
			point = el.getCenterPoint();
		} else if (el.x !== undefined && el.y !== undefined) {
			point = el;
		} else if (el._model && el._model.x !== undefined && el._model.y !== undefined) {
			point = el._model;
		}
	}
	return point;
}

function triggerMouseEvent(chart, type, el) {
	var node = chart.canvas;
	var rect = node.getBoundingClientRect();
	var point = _resolveElementPoint(el);
	var event = new MouseEvent(type, {
		clientX: rect.left + point.x,
		clientY: rect.top + point.y,
		cancelable: true,
		bubbles: true,
		view: window
	});

	node.dispatchEvent(event);
}

module.exports = {
	injectCSS: injectCSS,
	createCanvas: createCanvas,
	acquireChart: acquireChart,
	releaseChart: releaseChart,
	readImageData: readImageData,
	triggerMouseEvent: triggerMouseEvent,
	waitForResize: waitForResize
};
<commit_msg>Fix typo in test utils comment (#6017)<commit_after>function createCanvas(w, h) {
	var canvas = document.createElement('canvas');
	canvas.width = w;
	canvas.height = h;
	return canvas;
}

function readImageData(url, callback) {
	var image = new Image();

	image.onload = function() {
		var h = image.height;
		var w = image.width;
		var canvas = createCanvas(w, h);
		var ctx = canvas.getContext('2d');
		ctx.drawImage(image, 0, 0, w, h);
		callback(ctx.getImageData(0, 0, w, h));
	};

	image.src = url;
}

/**
 * Injects a new canvas (and div wrapper) and creates the associated Chart instance
 * using the given config. Additional options allow tweaking elements generation.
 * @param {object} config - Chart config.
 * @param {object} options - Chart acquisition options.
 * @param {object} options.canvas - Canvas attributes.
 * @param {object} options.wrapper - Canvas wrapper attributes.
 * @param {boolean} options.persistent - If true, the chart will not be released after the spec.
 */
function acquireChart(config, options) {
	var wrapper = document.createElement('div');
	var canvas = document.createElement('canvas');
	var chart, key;

	config = config || {};
	options = options || {};
	options.canvas = options.canvas || {height: 512, width: 512};
	options.wrapper = options.wrapper || {class: 'chartjs-wrapper'};

	for (key in options.canvas) {
		if (options.canvas.hasOwnProperty(key)) {
			canvas.setAttribute(key, options.canvas[key]);
		}
	}

	for (key in options.wrapper) {
		if (options.wrapper.hasOwnProperty(key)) {
			wrapper.setAttribute(key, options.wrapper[key]);
		}
	}

	// by default, remove chart animation and auto resize
	config.options = config.options || {};
	config.options.animation = config.options.animation === undefined ? false : config.options.animation;
	config.options.responsive = config.options.responsive === undefined ? false : config.options.responsive;
	config.options.defaultFontFamily = config.options.defaultFontFamily || 'Arial';

	wrapper.appendChild(canvas);
	window.document.body.appendChild(wrapper);

	try {
		chart = new Chart(canvas.getContext('2d'), config);
	} catch (e) {
		window.document.body.removeChild(wrapper);
		throw e;
	}

	chart.$test = {
		persistent: options.persistent,
		wrapper: wrapper
	};

	return chart;
}

function releaseChart(chart) {
	chart.destroy();

	var wrapper = (chart.$test || {}).wrapper;
	if (wrapper && wrapper.parentNode) {
		wrapper.parentNode.removeChild(wrapper);
	}
}

function injectCSS(css) {
	// https://stackoverflow.com/q/3922139
	var head = document.getElementsByTagName('head')[0];
	var style = document.createElement('style');
	style.setAttribute('type', 'text/css');
	if (style.styleSheet) { // IE
		style.styleSheet.cssText = css;
	} else {
		style.appendChild(document.createTextNode(css));
	}
	head.appendChild(style);
}

function waitForResize(chart, callback) {
	var override = chart.resize;
	chart.resize = function() {
		chart.resize = override;
		override.apply(this, arguments);
		callback();
	};
}

function _resolveElementPoint(el) {
	var point = {x: 0, y: 0};
	if (el) {
		if (typeof el.getCenterPoint === 'function') {
			point = el.getCenterPoint();
		} else if (el.x !== undefined && el.y !== undefined) {
			point = el;
		} else if (el._model && el._model.x !== undefined && el._model.y !== undefined) {
			point = el._model;
		}
	}
	return point;
}

function triggerMouseEvent(chart, type, el) {
	var node = chart.canvas;
	var rect = node.getBoundingClientRect();
	var point = _resolveElementPoint(el);
	var event = new MouseEvent(type, {
		clientX: rect.left + point.x,
		clientY: rect.top + point.y,
		cancelable: true,
		bubbles: true,
		view: window
	});

	node.dispatchEvent(event);
}

module.exports = {
	injectCSS: injectCSS,
	createCanvas: createCanvas,
	acquireChart: acquireChart,
	releaseChart: releaseChart,
	readImageData: readImageData,
	triggerMouseEvent: triggerMouseEvent,
	waitForResize: waitForResize
};
<|endoftext|>


<commit_before>export class DOMUtil {
  constructor() {
  }

  findJsByDataUrl(url) {
    return document.querySelectorAll(`script[data-dactylographsy-url="${url}"]`);
  }

  findCssByDataUrl(url) {
    let
      nodes = [],
      styles = document.querySelectorAll(`style[data-dactylographsy-url="${url}"]`),
      links = document.querySelectorAll(`link[data-dactylographsy-url="${url}"]`)

    for (var i = 0; i < styles.length; i++) {
      nodes.push(styles[i]);
    }

    for (var i = 0; i < scripts.length; i++) {
      nodes.push(scripts[i]);
    }

    return nodes;
  }

  findAllCss() {
    let
      nodes = [],
      styles = document.querySelectorAll(`style[data-dactylographsy-url]`),
      links = document.querySelectorAll(`link[data-dactylographsy-url]`)

    for (var i = 0; i < styles.length; i++) {
      nodes.push(styles[i]);
    }

    for (var i = 0; i < scripts.length; i++) {
      nodes.push(scripts[i]);
    }

    return nodes;
  }

  findAllJs() {
    return document.querySelectorAll(`script[data-dactylographsy-url]`);
  }

  removeAll() {
    let
      nodes = [],
      scripts = this.findAllJs(),
      styles = this.findAllCss();

    for (var i = 0; i < styles.length; i++) {
      nodes.push(styles[i]);
    }

    for (var i = 0; i < scripts.length; i++) {
      nodes.push(scripts[i]);
    }

    for (let node of nodes) {
      node.parentNode.removeChild(node);
    }
  }
}
<commit_msg>Fix stupid naming issue :evil:.<commit_after>export class DOMUtil {
  constructor() {
  }

  findJsByDataUrl(url) {
    return document.querySelectorAll(`script[data-dactylographsy-url="${url}"]`);
  }

  findCssByDataUrl(url) {
    let
      nodes = [],
      styles = document.querySelectorAll(`style[data-dactylographsy-url="${url}"]`),
      links = document.querySelectorAll(`link[data-dactylographsy-url="${url}"]`)

    for (var i = 0; i < styles.length; i++) {
      nodes.push(styles[i]);
    }

    for (var i = 0; i < links.length; i++) {
      nodes.push(links[i]);
    }

    return nodes;
  }

  findAllCss() {
    let
      nodes = [],
      styles = document.querySelectorAll(`style[data-dactylographsy-url]`),
      links = document.querySelectorAll(`link[data-dactylographsy-url]`)

    for (var i = 0; i < styles.length; i++) {
      nodes.push(styles[i]);
    }

    for (var i = 0; i < links.length; i++) {
      nodes.push(links[i]);
    }

    return nodes;
  }

  findAllJs() {
    return document.querySelectorAll(`script[data-dactylographsy-url]`);
  }

  removeAll() {
    let
      nodes = [],
      scripts = this.findAllJs(),
      styles = this.findAllCss();

    for (var i = 0; i < styles.length; i++) {
      nodes.push(styles[i]);
    }

    for (var i = 0; i < scripts.length; i++) {
      nodes.push(scripts[i]);
    }

    for (let node of nodes) {
      node.parentNode.removeChild(node);
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-json
 *
 * iotagent-json is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-json is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-json.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var fs = require('fs');

function readExampleFile(name, raw) {
    let text = null;
    try {
        text = fs.readFileSync(name, 'UTF8');
    } catch (e) {
        /* eslint-disable no-console */
        console.error(JSON.stringify(e));
    }
    return raw ? text : JSON.parse(text);
}

function delay(ms) {
    return function(callback) {
        setTimeout(callback, ms);
    };
}

exports.readExampleFile = readExampleFile;
exports.delay = delay;
<commit_msg>Update utils.js<commit_after>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-json
 *
 * iotagent-json is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-json is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-json.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var fs = require('fs');

function readExampleFile(name, raw) {
    var text = null;
    try {
        text = fs.readFileSync(name, 'UTF8');
    } catch (e) {
        /* eslint-disable no-console */
        console.error(JSON.stringify(e));
    }
    return raw ? text : JSON.parse(text);
}

function delay(ms) {
    return function(callback) {
        setTimeout(callback, ms);
    };
}

exports.readExampleFile = readExampleFile;
exports.delay = delay;
<|endoftext|>


<commit_before>var EndDash = require('../end-dash'),
    Reaction = require("../reaction"),
    _ = require("underscore"),
    get = require("../util").get,
    rules = require("../rules");

var LoopingReaction = Reaction.extend({

  addAll: function(models, index) {
    index = index || 0;
    models.each(this.add, this);
  },

  getTemplateClass: function(model) {
      var template = this.itemTemplates[get(model, this.polymorphicKey) || "default"];
      if (!template) {
        template = this.itemTemplates["default"]
      }
      return template;
  },

  add: function(model, index) {
    var Template = this.getTemplateClass(model),
        template = new Template(model, { stack: this.stack.slice(0) }),
        children;

    template.el.data("model", model);

    if(typeof index === "undefined") {
      this.templates.push(template);
      this.el.append(template.el);
    } else if(index === 0) {
      this.templates.unshift(template);
      this.el.prepend(template.el);
    } else {
      this.templates.splice(index, 0, template);
      children = this.el.children();
      template.el.insertAfter(children[index - 1]);
    };
  },

  remove: function(model) {
    var indexToRemove,
        templateToRemove = _(this.templates).find(function(template, index) {
          indexToRemove = index;
          return template.el.data('model') === model;
      });
      templateToRemove.el.remove()
      this.templates.splice(indexToRemove, 1);
  },

  init: function(next) {
    this.collection = this.model
    this.collectionPresenter = this._presenter

    if(!this.collection)
      throw new Error("could not find collection " + this.collectionaName);

    this.templates = [];
    this.el.html("");
    this.el.data("collection", this.collection);
    this.addAll(this.collection);
    next();
  },

  observe: function(next) {
    if(typeof this.collectionPresenter.on === "function") {

      if(this.polymorphicKey) {
        this.collectionPresenter.on("change:" + this.polymorphicKey, function(model) {
          var index = this.collectionPresenter.indexOf(model);
          this.remove(model);
          this.add(model, index);
        }, this);
      }
      this.collectionPresenter.on("sort reset", function() {
        this.el.html("");
        this.addAll(this.collectionPresenter);
      }, this);

      this.collectionPresenter.on("add", function(model) {
        this.add(model, this.collectionPresenter.indexOf(model));
      }, this);

      this.collectionPresenter.on("remove", function(model, collection, opts) {
        this.remove(model);
      }, this);
    }
  }
}, {
  selector: "[data-each]",
    parse: function(el, state) {
      var polymorphicKey = rules.polymorphicKeyClass(el),
        templates = {},
        children = el.children();

    children.each(function(i, element) {
      var child = $(element),
          whenValue = rules.polymorphicValueClass(child) || 'default',
          templateName = _.last(state.pathStack) + whenValue;

      EndDash.registerTemplate(templateName, child);
      templates[whenValue] = EndDash.getTemplateClass(templateName);
      child.remove();
    })

    return {
      itemTemplates: templates,
      polymorphicKey: polymorphicKey
    };
  }
});

module.exports = LoopingReaction;
<commit_msg>Semi-colon goes right there<commit_after>var EndDash = require('../end-dash'),
    Reaction = require("../reaction"),
    _ = require("underscore"),
    get = require("../util").get,
    rules = require("../rules");

var LoopingReaction = Reaction.extend({

  addAll: function(models, index) {
    index = index || 0;
    models.each(this.add, this);
  },

  getTemplateClass: function(model) {
      var template = this.itemTemplates[get(model, this.polymorphicKey) || "default"];
      if (!template) {
        template = this.itemTemplates["default"];
      }
      return template;
  },

  add: function(model, index) {
    var Template = this.getTemplateClass(model),
        template = new Template(model, { stack: this.stack.slice(0) }),
        children;

    template.el.data("model", model);

    if(typeof index === "undefined") {
      this.templates.push(template);
      this.el.append(template.el);
    } else if(index === 0) {
      this.templates.unshift(template);
      this.el.prepend(template.el);
    } else {
      this.templates.splice(index, 0, template);
      children = this.el.children();
      template.el.insertAfter(children[index - 1]);
    };
  },

  remove: function(model) {
    var indexToRemove,
        templateToRemove = _(this.templates).find(function(template, index) {
          indexToRemove = index;
          return template.el.data('model') === model;
      });
      templateToRemove.el.remove()
      this.templates.splice(indexToRemove, 1);
  },

  init: function(next) {
    this.collection = this.model
    this.collectionPresenter = this._presenter

    if(!this.collection)
      throw new Error("could not find collection " + this.collectionaName);

    this.templates = [];
    this.el.html("");
    this.el.data("collection", this.collection);
    this.addAll(this.collection);
    next();
  },

  observe: function(next) {
    if(typeof this.collectionPresenter.on === "function") {

      if(this.polymorphicKey) {
        this.collectionPresenter.on("change:" + this.polymorphicKey, function(model) {
          var index = this.collectionPresenter.indexOf(model);
          this.remove(model);
          this.add(model, index);
        }, this);
      }
      this.collectionPresenter.on("sort reset", function() {
        this.el.html("");
        this.addAll(this.collectionPresenter);
      }, this);

      this.collectionPresenter.on("add", function(model) {
        this.add(model, this.collectionPresenter.indexOf(model));
      }, this);

      this.collectionPresenter.on("remove", function(model, collection, opts) {
        this.remove(model);
      }, this);
    }
  }
}, {
  selector: "[data-each]",
    parse: function(el, state) {
      var polymorphicKey = rules.polymorphicKeyClass(el),
        templates = {},
        children = el.children();

    children.each(function(i, element) {
      var child = $(element),
          whenValue = rules.polymorphicValueClass(child) || 'default',
          templateName = _.last(state.pathStack) + whenValue;

      EndDash.registerTemplate(templateName, child);
      templates[whenValue] = EndDash.getTemplateClass(templateName);
      child.remove();
    })

    return {
      itemTemplates: templates,
      polymorphicKey: polymorphicKey
    };
  }
});

module.exports = LoopingReaction;
<|endoftext|>


<commit_before>/*
 * patron - The cleanest command framework for discord.js and eris.
 * Copyright (C) 2019  patron contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
"use strict";
const TypeReaderResult = require("../results/TypeReaderResult.js");
const TypeReader = require("../structures/TypeReader.js");
const {regexes} = require("../utils/constants.js");

/**
 * Parses a URL.
 * @returns {TypeReaderResult<URL>}
 */
const UrlReader = new TypeReader({type: "url"});

UrlReader.default = true;
UrlReader.read = function(input, command, _, argument) {
  let value = input.replace(regexes.urlMarkdown, "");

  try {
    value = new URL(input);
  }catch{
    return TypeReaderResult.fromFailure(command, `You've provided an invalid ${argument.name}.`);
  }

  return TypeReaderResult.fromSuccess(value);
};

module.exports = UrlReader;
<commit_msg>Another UrlReader fix<commit_after>/*
 * patron - The cleanest command framework for discord.js and eris.
 * Copyright (C) 2019  patron contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
"use strict";
const TypeReaderResult = require("../results/TypeReaderResult.js");
const TypeReader = require("../structures/TypeReader.js");
const {regexes} = require("../utils/constants.js");

/**
 * Parses a URL.
 * @returns {TypeReaderResult<URL>}
 */
const UrlReader = new TypeReader({type: "url"});

UrlReader.default = true;
UrlReader.read = function(input, command, _, argument) {
  let value = input.replace(regexes.urlMarkdown, "");

  try {
    value = new URL(value);
  }catch{
    return TypeReaderResult.fromFailure(command, `You've provided an invalid ${argument.name}.`);
  }

  return TypeReaderResult.fromSuccess(value);
};

module.exports = UrlReader;
<|endoftext|>


<commit_before>//Reads withdrawals object, sends transactions
//TODO: handle address validation quirk
//TODO: re-examine self-tests
var bitcoin = require ('bitcoin'); //https://www.npmjs.org/package/bitcoin greatly simplifies interfacing with coin daemons
var coins = require ("./cryptocurrencies.json");//coin configurations
var coinDaemons = require ("./coin-daemons.js");
var transactions = require ("./lib/outgoing-bridge.js");
transactions.coinDaemons = coinDaemons; //validateAddress function needs coinDaemons object
var sep = '\n--------------------------------------------------------\n';
var logPrefix = 'process-withdrawal';

//keeping this around since it also shows rpc methods available
function showCollection(objCollection){//shows properties of objects in a collection. Like port/host/userpass of each coin in cryptocurrencies.json
    console.log(logPrefix, 'selfTest!');
    for(var obj in objCollection){
        console.log(logPrefix, 'obj:' + obj, '\ncoins[obj]:\n', objCollection[obj],'\n');
        for (var propt in objCollection[obj]){
            console.log(logPrefix, 'obj[propt]:',propt, '\ncoins[obj[propt]]:' , objCollection[obj][propt],'\n');
        }
    }
}

function selfTest(testLevel, testSelect){ //has not been kept up. Some functions may have been renamed or expect different params
    if (testLevel > 0){
        console.log(sep, logPrefix, 'Checking to see if cryptocurrencies.json was loaded. Showing coins.',sep);
        showCollection(coins);
    }
    if (testLevel > 1){
        console.log(sep, logPrefix, 'Checking to see if bitcoin Clients were created. Showing coinDaemons and available methods', sep);
        showCollection(coinDaemons);
    }

    if (testSelect != ''){
        if (testSelect.indexOf('tx' >0)){
            console.log(sep, logPrefix, 'Testing coinDaemon method calls using an example transaction. THIS WILL SEND CRYPTO so you should be on testnet!!!', sep);
            coinProcessing(exampleTx, fnClearPending = function (){console.log(logPrefix, 'fnClearPending dummy function.');});
        }
    }
}

function coinProcessing(withdrawalSet, fnClearPending){//run transaction
    if (withdrawalSet.hasOwnProperty('withdrawals') != true){
        //console.log("No withdrawals found (withdrawalSet does not have property 'withdrawals')");
        console.log(logPrefix, 'ERROR: invalid withdrawalSet:', withdrawalSet);
        return false;
    }
    console.log(logPrefix, 'valid object:', withdrawalSet.hasOwnProperty('withdrawals'));
    for (i=0; i < withdrawalSet.withdrawals.length; i++){ //for each withdrawal
        if(coinDaemons.hasOwnProperty(withdrawalSet.withdrawals[i].currency)){ //if coinDaemon exists for the currency
            validation = transactions.validateAddress(withdrawalSet.withdrawals[i], fnClearPending); //validate address
            if (validation != true) {
                console.log(logPrefix, 'address NOT VALIDATED. See output above this line.')
                return false;
            }
            else if (validation == true) {
                console.log(logPrefix, 'address VALIDATED');
                fnClearPending(true); //TODO: check what args this really takes
            }
            //IMPORTANT!!: this just quits after validating address. callback needs to direct to sendTx
        }else{
            console.log(logPrefix, 'ERROR! Coin', withdrawalSet.withdrawals[i].currency, '(rTxId='+ withdrawalSet.withdrawals[i].ripple_transaction_id + ') does not exist in cryptocurrencies.json. Skipping.');
            continue;
        }
    }
return 0;
}

runSelfTest = true;
testLevel = 0;
testSelect = 'tx'; //options: tx = test transactions. BE ON TESTNET.
//end test vars
console.log(logPrefix, 'runSelfTest:', runSelfTest);
console.log(logPrefix, 'testLevel=', testLevel);
console.log(logPrefix, 'testSelect:', testSelect);

if (runSelfTest == true){
    this.fnClearPending = function (){console.log(logPrefix, 'fnClearPending dummy function.');}

    var exampleTx = require("./exampleTX.json");
    selfTest(testLevel, testSelect);
}

//module.exports = transactions;
<commit_msg>output lines<commit_after>//Reads withdrawals object, sends transactions
//TODO: handle address validation quirk
//TODO: re-examine self-tests
var bitcoin = require ('bitcoin'); //https://www.npmjs.org/package/bitcoin greatly simplifies interfacing with coin daemons
var coins = require ("./cryptocurrencies.json");//coin configurations
var coinDaemons = require ("./coin-daemons.js");
var transactions = require ("./lib/outgoing-bridge.js");
transactions.coinDaemons = coinDaemons; //validateAddress function needs coinDaemons object
var sep = '\n--------------------------------------------------------\n';
var logPrefix = 'process-withdrawal';

//keeping this around since it also shows rpc methods available
function showCollection(objCollection){//shows properties of objects in a collection. Like port/host/userpass of each coin in cryptocurrencies.json
    console.log(logPrefix, 'selfTest!');
    for(var obj in objCollection){
        console.log(logPrefix, 'obj:' + obj, '\ncoins[obj]:\n', objCollection[obj],'\n');
        for (var propt in objCollection[obj]){
            console.log(logPrefix, 'obj[propt]:',propt, '\ncoins[obj[propt]]:' , objCollection[obj][propt],'\n');
        }
    }
}

function selfTest(testLevel, testSelect){ //has not been kept up. Some functions may have been renamed or expect different params
    if (testLevel > 0){
        console.log(sep, logPrefix, 'Checking to see if cryptocurrencies.json was loaded. Showing coins.',sep);
        showCollection(coins);
    }
    if (testLevel > 1){
        console.log(sep, logPrefix, 'Checking to see if bitcoin Clients were created. Showing coinDaemons and available methods', sep);
        showCollection(coinDaemons);
    }

    if (testSelect != ''){
        if (testSelect.indexOf('tx' >0)){
            console.log(sep, logPrefix, 'Testing coinDaemon method calls using an example transaction. THIS WILL SEND CRYPTO so you should be on testnet!!!', sep);
            coinProcessing(exampleTx, fnClearPending = function (){console.log(logPrefix, 'fnClearPending dummy function.');});
        }
    }
}

function coinProcessing(withdrawalSet, fnClearPending){//run transaction
    if (withdrawalSet.hasOwnProperty('withdrawals') != true){
        //console.log("No withdrawals found (withdrawalSet does not have property 'withdrawals')");
        console.log(logPrefix, 'ERROR: invalid withdrawalSet:', withdrawalSet);
        return false;
    }
    console.log(logPrefix, 'valid object:', withdrawalSet.hasOwnProperty('withdrawals'));
    for (i=0; i < withdrawalSet.withdrawals.length; i++){ //for each withdrawal
        currency = withdrawalSet.withdrawals[i].currency;
        if(coinDaemons.hasOwnProperty(currency)){ //if coinDaemon exists for the currency
            console.log(logPrefix, '[', currency, ']', 'on', coinDaemons[currency].port);//debug info
            validation = transactions.validateAddress(withdrawalSet.withdrawals[i], fnClearPending); //validate address
            if (validation != true) {
                console.log(logPrefix, 'address NOT VALIDATED. See output above this line.')
                return false;
            }
            else if (validation == true) {
                console.log(logPrefix, 'address VALIDATED');
                fnClearPending(true); //TODO: check what args this really takes
            }
            //IMPORTANT!!: this just quits after validating address. callback needs to direct to sendTx
        }else{
            console.log(logPrefix, 'ERROR! Coin', withdrawalSet.withdrawals[i].currency, '(rTxId='+ withdrawalSet.withdrawals[i].ripple_transaction_id + ') does not exist in cryptocurrencies.json. Skipping.');
            continue;
        }
    }
return 0;
}

runSelfTest = true;
testLevel = 0;
testSelect = 'tx'; //options: tx = test transactions. BE ON TESTNET.
//end test vars
console.log(logPrefix, 'runSelfTest:', runSelfTest);
console.log(logPrefix, 'testLevel=', testLevel);
console.log(logPrefix, 'testSelect:', testSelect);

if (runSelfTest == true){
    this.fnClearPending = function (){console.log(logPrefix, 'fnClearPending dummy function.');}

    var exampleTx = require("./exampleTX.json");
    selfTest(testLevel, testSelect);
}

//module.exports = transactions;
<|endoftext|>


<commit_before>var Listener = require('../lib/listener.js');
var nconf = require('../config/nconf.js');
var abstract = require('../lib/abstract.js');

var listener = new Listener();

listener.onPayment = function(payment) {
  if (payment.destination_account == nconf.get('gateway_cold_wallet')) {
    var dt = payment.destination_tag;
    if (dt){
      var amount = payment.destination_amount.value;
      var currency = payment.destination_amount.currency;
      var issuer = payment.destination_amount.issuer;
      if (issuer == nconf.get('gateway_cold_wallet')) {

        abstract.recordIncomingPayment(dt, currency, amount, function(err, record) {
          console.log(err, record);
        });

      }
    }
  };

};

listener.start(nconf.get('last_payment_hash'));

<commit_msg>[FEATURE] Record hash and status of incoming payments.<commit_after>var Listener = require('../lib/listener.js');
var config = require('../config/nconf.js');
var abstract = require('../lib/abstract.js');

var listener = new Listener();

listener.onPayment = function(payment) {

  if (payment.destination_account == config.get('gateway_cold_wallet')) {
    var dt = payment.destination_tag;
    var state = payment.result;
    var hash = payment.hash;

    if (dt && (state == 'tesSUCCESS')){

      var amount = payment.destination_amount.value;
      var currency = payment.destination_amount.currency;
      var issuer = payment.destination_amount.issuer;

      if (issuer == config.get('gateway_cold_wallet')) {

        abstract.recordIncomingPayment(dt, currency, amount, 'incoming', hash, function(err, record) {
          if (err) {
            console.log('error:', err);

          } else {
            try {
              console.log(record.toJSON());

            } catch(e) {
              console.log('error', e);

            }
          }
        });
      }
    }
  };
};

listener.start(config.get('last_payment_hash'));

console.log('listening for payments to '+config.get('gateway_cold_wallet')+' with destination tag');

<|endoftext|>


<commit_before>define([ "Body", "Constants", "Quaternion", "State", "Vector" ], function(Body, Constants, Quaternion, State, Vector)
{
    "use strict";
    function Environment(bodyToState)
    {
        InputValidator.validateNotNull("bodyToState", bodyToState);

        var that = this;
        var nameToShip = {};
        var shipToState = {};

        this.addShip = function(ship, position, orientation, velocity, angularVelocity)
        {
            InputValidator.validateNotNull("ship", ship);
            InputValidator.validateNotNull("position", position);
            InputValidator.validateNotNull("orientation", orientation);

            var julianDate = 0.0;
            var myVelocity = (velocity ? velocity : Vector.ZERO);
            var myAngularVelocity = (angularVelocity ? angularVelocity : Quaternion.ZERO);

            var shipKey = ship.name();
            nameToShip[shipKey] = ship;
            shipToState[shipKey] = new State.State(julianDate, position, orientation, myVelocity, myAngularVelocity);
        };

        this.bodyKeys = function()
        {
            return Object.getOwnPropertyNames(bodyToState);
        };

        this.ship = function(shipKey)
        {
            InputValidator.validateNotNull("shipKey", shipKey);

            return nameToShip[shipKey];
        };

        this.state = function(bodyKey)
        {
            InputValidator.validateNotNull("bodyKey", bodyKey);

            var answer = bodyToState[bodyKey];

            if (!answer)
            {
                answer = shipToState[bodyKey];
            }

            return answer;
        };

        this.tick = function()
        {
            LOGGER.trace("Environment.tick() start");

            // Assign acceleration due to gravity.
            var state0, mass0, position0;
            var bodyKey1, mass1, position1;
            var shipKey;

            for ( var bodyKey0 in bodyToState)
            {
                state0 = this.state(bodyKey0);
                mass0 = Body.properties[bodyKey0].mass;
                position0 = state0.position();

                for (bodyKey1 in bodyToState)
                {
                    if (bodyKey0 !== bodyKey1)
                    {
                        mass1 = Body.properties[bodyKey1].mass;
                        position1 = that.state(bodyKey1).position();
                        state0.addAcceleration(computeGravityAcceleration(mass1, position1, mass0, position0));
                    }
                }
            }

            for (shipKey in shipToState)
            {
                var ship = nameToShip[shipKey];
                state0 = shipToState[shipKey];
                mass0 = ship.mass();
                position0 = state0.position();

                for (bodyKey1 in bodyToState)
                {
                    if (bodyKey0 !== bodyKey1)
                    {
                        mass1 = Body.properties[bodyKey1].mass;
                        position1 = that.state(bodyKey1).position();
                        state0.addAcceleration(computeGravityAcceleration(mass1, position1, mass0, position0));
                    }
                }
            }

            // Integrate states.
            for ( var bodyKey in bodyToState)
            {
                bodyToState[bodyKey].tick();
            }

            for (shipKey in shipToState)
            {
                shipToState[shipKey].tick();
            }

            this.trigger("dataUpdated", this);

            LOGGER.trace("Environment.tick() end");
        };

        function computeGravityAcceleration(mass1, position1, mass2, position2)
        {
            // F = G * m1 * m2 / r^2
            var r = position2.subtract(position1);
            var rmag2 = r.magnitudeSquared();

            // the force applied on object 2 due to object 1
            var fmag = -Constants.G * mass1 * mass2 / rmag2;

            // a = F / m
            var amag = fmag / mass2;
            var runit = r.unit();

            return new Vector(amag * runit.x(), amag * runit.y(), amag * runit.z());
        }
    }

    MicroEvent.mixin(Environment);

    return Environment;
});
<commit_msg>Changed to update ship devices. Removed use of MicroEvent.<commit_after>define([ "Body", "Constants", "Quaternion", "State", "Vector" ], function(Body, Constants, Quaternion, State, Vector)
{
    "use strict";
    function Environment(bodyToState)
    {
        InputValidator.validateNotNull("bodyToState", bodyToState);

        var that = this;
        var nameToShip = {};
        var shipToState = {};

        this.addShip = function(ship, position, orientation, velocity, angularVelocity)
        {
            InputValidator.validateNotNull("ship", ship);
            InputValidator.validateNotNull("position", position);
            InputValidator.validateNotNull("orientation", orientation);

            var julianDate = 0.0;
            var myVelocity = (velocity ? velocity : Vector.ZERO);
            var myAngularVelocity = (angularVelocity ? angularVelocity : Quaternion.ZERO);

            var shipKey = ship.name();
            nameToShip[shipKey] = ship;
            shipToState[shipKey] = new State.State(julianDate, position, orientation, myVelocity, myAngularVelocity);
        };

        this.bodyKeys = function()
        {
            return Object.getOwnPropertyNames(bodyToState);
        };

        this.ship = function(shipKey)
        {
            InputValidator.validateNotNull("shipKey", shipKey);

            return nameToShip[shipKey];
        };

        this.state = function(bodyKey)
        {
            InputValidator.validateNotNull("bodyKey", bodyKey);

            var answer = bodyToState[bodyKey];

            if (!answer)
            {
                answer = shipToState[bodyKey];
            }

            return answer;
        };

        this.tick = function()
        {
            LOGGER.trace("Environment.tick() start");

            // Assign acceleration due to gravity.
            var state0, mass0, position0;
            var bodyKey1, mass1, position1;
            var shipKey;

            for ( var bodyKey0 in bodyToState)
            {
                state0 = this.state(bodyKey0);
                mass0 = Body.properties[bodyKey0].mass;
                position0 = state0.position();

                for (bodyKey1 in bodyToState)
                {
                    if (bodyKey0 !== bodyKey1)
                    {
                        mass1 = Body.properties[bodyKey1].mass;
                        position1 = that.state(bodyKey1).position();
                        state0.addAcceleration(computeGravityAcceleration(mass1, position1, mass0, position0));
                    }
                }
            }

            var ship;

            for (shipKey in shipToState)
            {
                ship = nameToShip[shipKey];
                state0 = shipToState[shipKey];
                mass0 = ship.mass();
                position0 = state0.position();

                for (bodyKey1 in bodyToState)
                {
                    if (bodyKey0 !== bodyKey1)
                    {
                        mass1 = Body.properties[bodyKey1].mass;
                        position1 = that.state(bodyKey1).position();
                        state0.addAcceleration(computeGravityAcceleration(mass1, position1, mass0, position0));
                    }
                }
            }

            // Update ship devices.
            for (shipKey in shipToState)
            {
                ship = nameToShip[shipKey];
                ship.tick();
            }

            // Integrate states.
            for ( var bodyKey in bodyToState)
            {
                bodyToState[bodyKey].tick();
            }

            for (shipKey in shipToState)
            {
                shipToState[shipKey].tick();
            }

            LOGGER.trace("Environment.tick() end");
        };

        function computeGravityAcceleration(mass1, position1, mass2, position2)
        {
            // F = G * m1 * m2 / r^2
            var r = position2.subtract(position1);
            var rmag2 = r.magnitudeSquared();

            // the force applied on object 2 due to object 1
            var fmag = -Constants.G * mass1 * mass2 / rmag2;

            // a = F / m
            var amag = fmag / mass2;
            var runit = r.unit();

            return new Vector(amag * runit.x(), amag * runit.y(), amag * runit.z());
        }
    }

    return Environment;
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin, {
  init() {
    this._super(...arguments);
    Ember.run.scheduleOnce('afterRender', this, 'processLegacyDomOperations');
  },

  processLegacyDomOperations() {
    window.legacySearch();
    // window.legacyTree();
    window.legacyMain();
  }
})<commit_msg>Updates application route: Adds todo and some code style updates<commit_after>import Ember from 'ember';
import ApplicationRouteMixin
  from 'ember-simple-auth/mixins/application-route-mixin';

const {
  Route,
  run
} = Ember;

export default Route.extend(ApplicationRouteMixin, {
  init() {
    this._super(...arguments);
    run.scheduleOnce('afterRender', this, 'processLegacyDomOperations');
  },

  processLegacyDomOperations() {
    window.legacySearch();
    // TODO: DSS-6122 Refactor Remove tree legacy operations & references
    // window.legacyTree();
    window.legacyMain();
  }
});
<|endoftext|>


<commit_before>/**
 * https://github.com/RaphaelDeLaGhetto/grunt-init-gebo
 *
 * Copyright 2013 Daniel Bidulock
 * MIT license
 */

'use strict';

// Basic template description.
exports.description = 'A vanilla gebo agent with nodeunit unit tests.';

// Template-specific notes to be displayed before question prompts.
exports.notes = '';

// Template-specific notes to be displayed after question prompts.
exports.after = 'Be sure to install project dependencies with _npm ' +
    'install_ and _bower install_. After that, you may execute project tasks with _grunt_. For ' +
    'more information about installing and configuring Grunt, see ' +
    'the Getting Started guide:' +
    '\n\n' +
    'http://gruntjs.com/getting-started';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The actual init template.
exports.template = function(grunt, init, done) {

    init.process({}, [
            // Prompt for these values.
            init.prompt('name'),
            init.prompt('description'),
            init.prompt('version', '0.0.0'),
            init.prompt('repository'),
            init.prompt('homepage'),
            init.prompt('bugs'),
            init.prompt('licenses'),
            init.prompt('author_name'),
            init.prompt('author_email'),
            init.prompt('author_url'),
            init.prompt('node_version'),
            init.prompt('main', '<project-name>.js'),
            init.prompt('npm_test', 'grunt nodeunit')
        ],
        function(err, props) {
            props.main = props.name + '.js';

            // Remove hyphens from name and conver to camel case
            props.camelCasedName = props.name.replace(/-([a-z])/g,
                    function (g) { return g[1].toUpperCase(); });

            props.keywords = [
                    'gebo',
                    'agent',
                ];
            props.dependencies = {
                    'gebo-server': '*',
                    'mongoose': '*',
                    'nconf': '*',
                    'q': '*',
                };
            props.devDependencies = {
                    'database-cleaner': '~0.7.0',
                    'grunt': '~0.4.1',
                    'grunt-contrib-jshint': '~0.6.2',
                    'grunt-contrib-nodeunit': '~0.2.0',
                    'grunt-contrib-watch': '~0.4.0',
                    'nock': '~0.22.1',
                };

            // Files to copy (and process).
            var files = init.filesToCopy(props);

            // Add properly-named license files.
            init.addLicenseFiles(files, props.licenses);

            // Actually copy (and process) files.
            init.copyAndProcess(files, props);

            // Remove the camelCasedName, because we
            // don't really need it anymore
            delete props.camelCasedName;

            // Generate package.json file.
            init.writePackageJSON('package.json', props);

            // All done!
            done();
      });
  };

<commit_msg>Add strong-cluster-connect-store dependency<commit_after>/**
 * https://github.com/RaphaelDeLaGhetto/grunt-init-gebo
 *
 * Copyright 2013 Daniel Bidulock
 * MIT license
 */

'use strict';

// Basic template description.
exports.description = 'A vanilla gebo agent with nodeunit unit tests.';

// Template-specific notes to be displayed before question prompts.
exports.notes = '';

// Template-specific notes to be displayed after question prompts.
exports.after = 'Be sure to install project dependencies with _npm ' +
    'install_ and _bower install_. After that, you may execute project tasks with _grunt_. For ' +
    'more information about installing and configuring Grunt, see ' +
    'the Getting Started guide:' +
    '\n\n' +
    'http://gruntjs.com/getting-started';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The actual init template.
exports.template = function(grunt, init, done) {

    init.process({}, [
            // Prompt for these values.
            init.prompt('name'),
            init.prompt('description'),
            init.prompt('version', '0.0.0'),
            init.prompt('repository'),
            init.prompt('homepage'),
            init.prompt('bugs'),
            init.prompt('licenses'),
            init.prompt('author_name'),
            init.prompt('author_email'),
            init.prompt('author_url'),
            init.prompt('node_version'),
            init.prompt('main', '<project-name>.js'),
            init.prompt('npm_test', 'grunt nodeunit')
        ],
        function(err, props) {
            props.main = props.name + '.js';

            // Remove hyphens from name and conver to camel case
            props.camelCasedName = props.name.replace(/-([a-z])/g,
                    function (g) { return g[1].toUpperCase(); });

            props.keywords = [
                    'gebo',
                    'agent',
                ];
            props.dependencies = {
                    'gebo-server': '*',
                    'mongoose': '*',
                    'nconf': '*',
                    'q': '*',
                    'strong-cluster-connect-store': '*',
                };
            props.devDependencies = {
                    'database-cleaner': '~0.7.0',
                    'grunt': '~0.4.1',
                    'grunt-contrib-jshint': '~0.6.2',
                    'grunt-contrib-nodeunit': '~0.2.0',
                    'grunt-contrib-watch': '~0.4.0',
                    'nock': '~0.22.1',
                };

            // Files to copy (and process).
            var files = init.filesToCopy(props);

            // Add properly-named license files.
            init.addLicenseFiles(files, props.licenses);

            // Actually copy (and process) files.
            init.copyAndProcess(files, props);

            // Remove the camelCasedName, because we
            // don't really need it anymore
            delete props.camelCasedName;

            // Generate package.json file.
            init.writePackageJSON('package.json', props);

            // All done!
            done();
      });
  };

<|endoftext|>