<commit_before>var Q = require('q'),
    QFS = require('q-fs'),
    INHERIT = require('inherit'),
    CP = require('child_process'),
    PATH = require('path'),
    UTIL = require('util'),

    Node = require('./node').Node;

var LibraryNode = exports.LibraryNode = INHERIT(Node, {

    __constructor: function(dest, repo, paths, treeish) {
        this.dest = dest;
        this.repo = repo;
        this.treeish = treeish || 'master';
        this.paths = paths || [''];

        // TODO: path relative to the project root must be passed
        this.__base(PATH.basename(this.dest));
    },

    getInitialCheckoutCmd: function() {

    },

    getUpdateCmd: function() {

    },

    make: function() {
        var _this = this;

        return Q.all(this.paths.map(function(p){
            var dest = PATH.join(_this.dest, p),
                repo = _this.repo + p;

            return QFS.exists(dest)
                .then(function(exists){
                    var cmd = exists?_this.getUpdateCmd(repo, dest):_this.getInitialCheckoutCmd(repo, dest),
                        d = Q.defer();

                    _this.log(cmd);

                    CP.exec(cmd, function(err, stdout, stderr) {
                        stdout && _this.log(stdout);
                        stderr && _this.log(stderr);

                        err? d.reject(err) : d.resolve();
                    });

                    return d.promise;
                });
        }));
    }
});

exports.GitLibraryNode = INHERIT(LibraryNode, {

    getInitialCheckoutCmd: function(repo, dest) {
        return UTIL.format('git clone --progress %s %s && cd %s && git checkout %s', repo, dest, dest, this.treeish);
    },

    getUpdateCmd: function(repo, dest) {
        return UTIL.format('cd %s && git checkout HEAD~ && git branch -D %s ; git fetch origin && git checkout --track -b %s origin/%s', dest, this.treeish, this.treeish, this.treeish);
    }
});

exports.SvnLibraryNode = INHERIT(LibraryNode, {

    getInitialCheckoutCmd: function(repo, dest) {
        return UTIL.format('svn co -r %s %s %s', this.treeish, repo, dest);
    },

    getUpdateCmd: function(repo, dest) {
        return UTIL.format('svn up -r %s %s', this.treeish, dest);
    }
});<commit_msg>- library node is considered valid for 1 minute since last execution<commit_after>var Q = require('q'),
    QFS = require('q-fs'),
    INHERIT = require('inherit'),
    CP = require('child_process'),
    PATH = require('path'),
    UTIL = require('util'),

    Node = require('./node').Node;

var LibraryNode = exports.LibraryNode = INHERIT(Node, {

    __constructor: function(dest, repo, paths, treeish) {
        this.dest = dest;
        this.repo = repo;
        this.treeish = treeish || 'master';
        this.paths = paths || [''];

        // TODO: path relative to the project root must be passed
        this.__base(PATH.basename(this.dest));
    },

    getInitialCheckoutCmd: function() {

    },

    getUpdateCmd: function() {

    },

    isValid: function() {return true;
        var now = new Date();
        if (!this.lastRunTime || (now - this.lastRunTime) > 60000) return false;

        return true;
    },

    make: function() {
        var _this = this;

        this.lastRunTime = new Date();

        return Q.all(this.paths.map(function(p){
            var dest = PATH.join(_this.dest, p),
                repo = _this.repo + p;

            return QFS.exists(dest)
                .then(function(exists){
                    var cmd = exists?_this.getUpdateCmd(repo, dest):_this.getInitialCheckoutCmd(repo, dest),
                        d = Q.defer();

                    _this.log(cmd);

                    CP.exec(cmd, function(err, stdout, stderr) {
                        stdout && _this.log(stdout);
                        stderr && _this.log(stderr);

                        err? d.reject(err) : d.resolve();
                    });

                    return d.promise;
                });
        }));
    }
});

exports.GitLibraryNode = INHERIT(LibraryNode, {

    getInitialCheckoutCmd: function(repo, dest) {
        return UTIL.format('git clone --progress %s %s && cd %s && git checkout %s', repo, dest, dest, this.treeish);
    },

    getUpdateCmd: function(repo, dest) {
        return UTIL.format('cd %s && git checkout HEAD~ && git branch -D %s ; git fetch origin && git checkout --track -b %s origin/%s', dest, this.treeish, this.treeish, this.treeish);
    }
});

exports.SvnLibraryNode = INHERIT(LibraryNode, {

    getInitialCheckoutCmd: function(repo, dest) {
        return UTIL.format('svn co -r %s %s %s', this.treeish, repo, dest);
    },

    getUpdateCmd: function(repo, dest) {
        return UTIL.format('svn up -r %s %s', this.treeish, dest);
    }
});<|endoftext|>


<commit_before>module.exports = normalize

function normalize(name, opts) {
    if (!opts.marker) {
        throw new Error(name + "(opts): opts.marker is required " +
            JSON.stringify(opts))
    }

    if (!opts.label) {
        opts.label = spaced(opts.marker)
    }

    if (!opts.placeholder) {
        opts.placeholder = "Please enter your " + opts.label
    }

    if (!opts.name) {
        opts.name = opts.marker
    }

    return opts
}
<commit_msg>fix normalize<commit_after>var spaced = require("./spaced.js")

module.exports = normalize

function normalize(name, opts) {
    if (!opts.marker) {
        throw new Error(name + "(opts): opts.marker is required " +
            JSON.stringify(opts))
    }

    if (!opts.label) {
        opts.label = spaced(opts.marker)
    }

    if (!opts.placeholder) {
        opts.placeholder = "Please enter your " + opts.label
    }

    if (!opts.name) {
        opts.name = opts.marker
    }

    return opts
}
<|endoftext|>


<commit_before>// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

define(['jquery', 'admin.plugs'], function () {

    /*! 定义当前body对象 */
    this.$body = $('body');

    /*! 注册 data-load 事件行为 */
    this.$body.on('click', '[data-load]', function () {
        var url = $(this).attr('data-load'), tips = $(this).attr('data-tips');
        function _goLoad() {
            $.form.load(url, {}, 'GET', null, true, tips);
        }
        if ($(this).attr('data-confirm')) {
            return $.msg.confirm($(this).attr('data-confirm'), _goLoad);
        }
        return _goLoad.call(this);
    });

    /*! 注册 data-serach 表单搜索行为 */
    this.$body.on('submit', 'form.form-search', function () {
        var url = $(this).attr('action');
        var split = url.indexOf('?') === -1 ? '?' : '&';
        if ((this.method || 'get').toLowerCase() === 'get') {
            window.location.href = '#' + $.menu.parseUri(url + split + $(this).serialize());
        } else {
            $.form.load(url, this, 'post');
        }
    });

    /*! 注册 data-modal 事件行为 */
    this.$body.on('click', '[data-modal]', function () {
        return $.form.modal($(this).attr('data-modal'), 'open_type=modal', $(this).attr('data-title') || '编辑');
    });

    /*! 注册 data-open 事件行为 */
    this.$body.on('click', '[data-open]', function () {
        $.form.href($(this).attr('data-open'), this);
    });

    /*! 注册 data-reload 事件行为 */
    this.$body.on('click', '[data-reload]', function () {
        $.form.reload();
    });

    /*! 注册 data-check 事件行为 */
    this.$body.on('click', '[data-check-target]', function () {
        var checked = !!this.checked;
        $($(this).attr('data-check-target')).map(function () {
            this.checked = checked;
        });
    });

    /*! 注册 data-update 事件行为 */
    this.$body.on('click', '[data-update]', function () {
        var id = $(this).attr('data-update') || (function () {
            var data = [];
            return $($(this).attr('data-list-target') || 'input.list-check-box').map(function () {
                (this.checked) && data.push(this.value);
            }), data.join(',');
        }).call(this);
        if (id.length < 1) {
            return $.msg.tips('请选择需要操作的数据！');
        }
        var action = $(this).attr('data-action') || $(this).parents('[data-location]').attr('data-location');
        var value = $(this).attr('data-value') || 0, field = $(this).attr('data-field') || 'status';
        $.msg.confirm('确定要操作这些数据吗？', function () {
            $.form.load(action, {field: field, value: value, id: id}, 'POST');
        });
    });

    /*! 注册 data-href 事件行为 */
    this.$body.on('click', '[data-href]', function () {
        var href = $(this).attr('data-href');
        if (href && href.indexOf('#') !== 0) {
            window.location.href = href;
        }
    });

    /*! 注册 data-page-href 事件行为 */
    this.$body.on('click', 'a[data-page-href]', function () {
        window.location.href = '#' + $.menu.parseUri(this.href, this);
    });

    /*! 注册 data-file 事件行为 */
    this.$body.on('click', '[data-file]', function () {
        var type = $(this).attr('data-type') || 'jpg,png';
        var field = $(this).attr('data-field') || 'file';
        var method = $(this).attr('data-file') === 'one' ? 'one' : 'mtl';
        var title = $(this).attr('data-title') || '文件上传';
        var uptype = $(this).attr('data-uptype') || '';
        var url = window.ROOT_URL + '/index.php/admin/plugs/upfile/mode/' + method + '.html?uptype=' + uptype + '&type=' + type + '&field=' + field;
        $.form.iframe(url, title || '文件管理');
    });

    /*! 注册 data-iframe 事件行为 */
    this.$body.on('click', '[data-iframe]', function () {
        $.form.iframe($(this).attr('data-iframe'), $(this).attr('data-title') || '窗口');
    });

    /*! 注册 data-icon 事件行为 */
    this.$body.on('click', '[data-icon]', function () {
        var field = $(this).attr('data-icon') || $(this).attr('data-field') || 'icon';
        var url = window.ROOT_URL + '/index.php/admin/plugs/icon.html?field=' + field;
        $.form.iframe(url, '图标选择');
    });

    /*! 注册 data-tips-image 事件行为 */
    this.$body.on('click', '[data-tips-image]', function () {
        var src = this.getAttribute('data-tips-image') || this.src, img = new Image();
        var imgWidth = this.getAttribute('data-width') || '480px';
        img.onload = function () {
            layer.open({
                type: 1, area: imgWidth, title: false, closeBtn: 1, skin: 'layui-layer-nobg', shadeClose: true,
                content: $(img).appendTo('body').css({background: '#fff', width: imgWidth, height: 'auto'}),
                end: function () {
                    $(img).remove();
                }
            });
        };
        img.src = src;
    });

    /*! 注册 data-tips-text 事件行为 */
    this.$body.on('mouseenter', '[data-tips-text]', function () {
        var text = $(this).attr('data-tips-text');
        var placement = $(this).attr('data-tips-placement') || 'auto';
        $(this).tooltip({title: text, placement: placement}).tooltip('show');
    });

    /*! 注册 data-phone-view 事件行为 */
    this.$body.on('click', '[data-phone-view]', function () {
        var src = this.getAttribute('data-phone-view') || this.href;
        var $container = $('

公众号

').appendTo('body');
        var $iframe = $container.find('iframe').attr('src', src);
        $container.find('.mobile-header').on('click', function () {
            $iframe.attr('src', src);
        });
        layer.style(layer.open({type: 1, scrollbar: !1, area: ['330px', '600px'], title: !1, closeBtn: 1, skin: 'layui-layer-nobg', shadeClose: !!1, content: $container, end: function () {
                $container.remove();
            }
        }), {boxShadow: 'none'});
    });

    /*! 后台菜单控制初始化 */
    $.menu.listen();

    /*! 表单监听初始化 */
    $.validate.listen(this);
});<commit_msg>[更新]修改微信手机预览<commit_after>// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

define(['jquery', 'admin.plugs'], function () {

    /*! 定义当前body对象 */
    this.$body = $('body');

    /*! 注册 data-load 事件行为 */
    this.$body.on('click', '[data-load]', function () {
        var url = $(this).attr('data-load'), tips = $(this).attr('data-tips');
        function _goLoad() {
            $.form.load(url, {}, 'GET', null, true, tips);
        }
        if ($(this).attr('data-confirm')) {
            return $.msg.confirm($(this).attr('data-confirm'), _goLoad);
        }
        return _goLoad.call(this);
    });

    /*! 注册 data-serach 表单搜索行为 */
    this.$body.on('submit', 'form.form-search', function () {
        var url = $(this).attr('action');
        var split = url.indexOf('?') === -1 ? '?' : '&';
        if ((this.method || 'get').toLowerCase() === 'get') {
            window.location.href = '#' + $.menu.parseUri(url + split + $(this).serialize());
        } else {
            $.form.load(url, this, 'post');
        }
    });

    /*! 注册 data-modal 事件行为 */
    this.$body.on('click', '[data-modal]', function () {
        return $.form.modal($(this).attr('data-modal'), 'open_type=modal', $(this).attr('data-title') || '编辑');
    });

    /*! 注册 data-open 事件行为 */
    this.$body.on('click', '[data-open]', function () {
        $.form.href($(this).attr('data-open'), this);
    });

    /*! 注册 data-reload 事件行为 */
    this.$body.on('click', '[data-reload]', function () {
        $.form.reload();
    });

    /*! 注册 data-check 事件行为 */
    this.$body.on('click', '[data-check-target]', function () {
        var checked = !!this.checked;
        $($(this).attr('data-check-target')).map(function () {
            this.checked = checked;
        });
    });

    /*! 注册 data-update 事件行为 */
    this.$body.on('click', '[data-update]', function () {
        var id = $(this).attr('data-update') || (function () {
            var data = [];
            return $($(this).attr('data-list-target') || 'input.list-check-box').map(function () {
                (this.checked) && data.push(this.value);
            }), data.join(',');
        }).call(this);
        if (id.length < 1) {
            return $.msg.tips('请选择需要操作的数据！');
        }
        var action = $(this).attr('data-action') || $(this).parents('[data-location]').attr('data-location');
        var value = $(this).attr('data-value') || 0, field = $(this).attr('data-field') || 'status';
        $.msg.confirm('确定要操作这些数据吗？', function () {
            $.form.load(action, {field: field, value: value, id: id}, 'POST');
        });
    });

    /*! 注册 data-href 事件行为 */
    this.$body.on('click', '[data-href]', function () {
        var href = $(this).attr('data-href');
        if (href && href.indexOf('#') !== 0) {
            window.location.href = href;
        }
    });

    /*! 注册 data-page-href 事件行为 */
    this.$body.on('click', 'a[data-page-href]', function () {
        window.location.href = '#' + $.menu.parseUri(this.href, this);
    });

    /*! 注册 data-file 事件行为 */
    this.$body.on('click', '[data-file]', function () {
        var type = $(this).attr('data-type') || 'jpg,png';
        var field = $(this).attr('data-field') || 'file';
        var method = $(this).attr('data-file') === 'one' ? 'one' : 'mtl';
        var title = $(this).attr('data-title') || '文件上传';
        var uptype = $(this).attr('data-uptype') || '';
        var url = window.ROOT_URL + '/index.php/admin/plugs/upfile/mode/' + method + '.html?uptype=' + uptype + '&type=' + type + '&field=' + field;
        $.form.iframe(url, title || '文件管理');
    });

    /*! 注册 data-iframe 事件行为 */
    this.$body.on('click', '[data-iframe]', function () {
        $.form.iframe($(this).attr('data-iframe'), $(this).attr('data-title') || '窗口');
    });

    /*! 注册 data-icon 事件行为 */
    this.$body.on('click', '[data-icon]', function () {
        var field = $(this).attr('data-icon') || $(this).attr('data-field') || 'icon';
        var url = window.ROOT_URL + '/index.php/admin/plugs/icon.html?field=' + field;
        $.form.iframe(url, '图标选择');
    });

    /*! 注册 data-tips-image 事件行为 */
    this.$body.on('click', '[data-tips-image]', function () {
        var src = this.getAttribute('data-tips-image') || this.src, img = new Image();
        var imgWidth = this.getAttribute('data-width') || '480px';
        img.onload = function () {
            layer.open({
                type: 1, area: imgWidth, title: false, closeBtn: 1, skin: 'layui-layer-nobg', shadeClose: true,
                content: $(img).appendTo('body').css({background: '#fff', width: imgWidth, height: 'auto'}),
                end: function () {
                    $(img).remove();
                }
            });
        };
        img.src = src;
    });

    /*! 注册 data-tips-text 事件行为 */
    this.$body.on('mouseenter', '[data-tips-text]', function () {
        var text = $(this).attr('data-tips-text');
        var placement = $(this).attr('data-tips-placement') || 'auto';
        $(this).tooltip({title: text, placement: placement}).tooltip('show');
    });

    /*! 注册 data-phone-view 事件行为 */
    this.$body.on('click', '[data-phone-view]', function () {
        var $container = $('

公众号

').appendTo('body');
        $container.find('iframe').attr('src', this.getAttribute('data-phone-view') || this.href);
        layer.style(layer.open({type: 1, scrollbar: !1, area: ['330px', '600px'], title: !1, closeBtn: 1, skin: 'layui-layer-nobg', shadeClose: !!1,
            content: $container,
            end: function () {
                $container.remove();
            }
        }), {boxShadow: 'none'});
    });

    /*! 后台菜单控制初始化 */
    $.menu.listen();

    /*! 表单监听初始化 */
    $.validate.listen(this);
});<|endoftext|>


<commit_before>const moji = require('moji');

const normalizeString = string => (
  moji(string)
    .convert('ZEtoHE')
    .convert('ZStoHS')
    .convert('HKtoZK')
    .toString()
);

const normalizeTitle = normalizeString;

const normalizeAuthor = author => {
  const name = normalizeString(author);
  // if consists only of double-byte/blanks characters, remove blanks
  return (/^([^\x01-\x7E]|\s)+$/.test(name) ? name.replace(/\s+/g, '') : name);
};
const normalizeAuthors = authors => authors.map(normalizeAuthor);

const normalizeDescription = desc => desc.replace(/<br \/>/g, '');

module.exports = {
  normalizeTitle,
  normalizeAuthor,
  normalizeAuthors,
  normalizeDescription,
};
<commit_msg>add normalize title method of series(bundle)<commit_after>const moji = require('moji');

const normalizeString = string => (
  moji(string)
    .convert('ZEtoHE')
    .convert('ZStoHS')
    .convert('HKtoZK')
    .toString()
);

const normalizeTitle = normalizeString;

const normalizeBundleTitle = title => (
  normalizeTitle(title).replace(/^\[まとめ買い\] /, '')
);

const normalizeAuthor = author => {
  const name = normalizeString(author);
  // if consists only of double-byte/blanks characters, remove blanks
  return (/^([^\x01-\x7E]|\s)+$/.test(name) ? name.replace(/\s+/g, '') : name);
};
const normalizeAuthors = authors => authors.map(normalizeAuthor);

const normalizeDescription = desc => desc.replace(/<br \/>/g, '');

module.exports = {
  normalizeTitle,
  normalizeBundleTitle,
  normalizeAuthor,
  normalizeAuthors,
  normalizeDescription,
};
<|endoftext|>


<commit_before>
/**
 * @fileoverview
 * Provides methods for the Hello Endpoints sample UI and interaction with the
 * Hello Endpoints API.
 *
 * @author danielholevoet@google.com (Dan Holevoet)
 */

/** google global namespace for Google projects. */
var google = google || {};

/** devrel namespace for Google Developer Relations projects. */
google.devrel = google.devrel || {};

/** samples namespace for DevRel sample code. */
google.devrel.samples = google.devrel.samples || {};

/** hello namespace for this sample. */
google.devrel.samples.hello = google.devrel.samples.hello || {};

/**
 * Client ID of the application (from the APIs Console).
 * @type {string}
 */
google.devrel.samples.hello.CLIENT_ID =
    '1001315827289-em9jhbuphg99hnk98un4heo3ffhdi83m.apps.googleusercontent.com';

/**
 * Scopes used by the application.
 * @type {string}
 */
google.devrel.samples.hello.SCOPES =
    'https://www.googleapis.com/auth/userinfo.email';

/**
 * Whether or not the user is signed in.
 * @type {boolean}
 */
google.devrel.samples.hello.signedIn = false;

/**
 * Loads the application UI after the user has completed auth.
 */
google.devrel.samples.hello.userAuthed = function() {
  var request = gapi.client.oauth2.userinfo.get().execute(function(resp) {
    if (!resp.code) {
      google.devrel.samples.hello.signedIn = true;
      document.getElementById('signinButton').innerHTML = 'Sign out';
      document.getElementById('userInfoButton').disabled = false;
    }
  });
};

/**
 * Handles the auth flow, with the given value for immediate mode.
 * @param {boolean} mode Whether or not to use immediate mode.
 * @param {Function} callback Callback to call on completion.
 */
google.devrel.samples.hello.signin = function(mode, callback) {
  gapi.auth.authorize({client_id: google.devrel.samples.hello.CLIENT_ID,
      scope: google.devrel.samples.hello.SCOPES, immediate: mode},
      callback);
};

/**
 * Presents the user with the authorization popup.
 */
google.devrel.samples.hello.auth = function() {
  if (!google.devrel.samples.hello.signedIn) {
    google.devrel.samples.hello.signin(false,
        google.devrel.samples.hello.userAuthed);
  } else {
    google.devrel.samples.hello.signedIn = false;
    document.getElementById('signinButton').innerHTML = 'Sign in';
    document.getElementById('userInfoButton').disabled = true;
  }
};

/**
 * Enables the button callbacks in the UI.
 */
google.devrel.samples.hello.enableButtons = function() {
    document.getElementById('signinButton').onclick = function() {
    google.devrel.samples.hello.auth();
    gapi.client.endpoints.aveProfile().execute();
  }
  document.getElementById('userInfoButton').onclick = function() {
	  google.devrel.samples.hello.getUserInfo();
  }

  document.getElementById('getUserFromDatastore').onclick = function() {
	  google.devrel.samples.hello.getMeFromDatastore();
  }
  document.getElementById('sendFormButton').onclick = function() {
	  createGame();
  }
  document.getElementById('getGamesQueryButton').onclick = function() {
	 getGamesQueryButton();
  }
};

/**
 * Initializes the application.
 * @param {string} apiRoot Root of the API's path.
 */
google.devrel.samples.hello.init = function(apiRoot) {
  // Loads the OAuth and helloworld APIs asynchronously, and triggers login
  // when they have completed.
  var apisToLoad;
  var callback = function() {
    if (--apisToLoad == 0) {
      google.devrel.samples.hello.enableButtons();
      google.devrel.samples.hello.signin(true,
      google.devrel.samples.hello.userAuthed);
    }
  }

  apisToLoad = 2; // must match number of calls to gapi.client.load()
  gapi.client.load('endpoints', 'v1', callback, apiRoot);
  gapi.client.load('oauth2', 'v2', callback);
};

createGame = function() {
	var name =document.getElementById("name").value;
	var description =document.getElementById("description").value;
	var date =document.getElementById("date").value;
	var attendees =document.getElementById("attendees").value;
	var request =  gapi.client.endpoints.createGame({'name': name, 'description':description, 'date':date, 'maxAttendees':attendees,
		'seatsAvailable':attendees, 'latitude':40, 'longitude':40, 'cancelable':true});
	request.execute(alertInfo);
}

getGamesQueryButton = function(){
	var request = gapi.client.endpoints.getAllGames().execute(
		function(resp) {
			if (!resp.code) {
				resp.items = resp.items || [];
		        for (var i = 0; i < resp.items.length; i++) {
		        	print(resp.items[i]);
		        }
		        alert("END! Items: "+ resp.items.length);
		    }
			else{
				alert("Smth went wrong! resp.code: "+resp.code);
			}
		}
	);
}
print = function(game) {
	  var node = document.createElement("p");
	  var textnode = document.createTextNode("Game name: "+game.name+"/n"+"Game description: "+game.description);
	  node.appendChild(textnode);
	  document.getElementById("gameNode").appendChild(node);
};

google.devrel.samples.hello.getUserInfo = function() {
	var request =  gapi.client.endpoints.getMyInfo();
	request.execute(alertInfo);
}
google.devrel.samples.hello.getMeFromDatastore = function() {
	var request =  gapi.client.endpoints.getMeFromDatastore();
	request.execute(alertInfo);
}
function alertInfo (response) {
	alert(response.message);
}<commit_msg>fixed<commit_after>
/**
 * @fileoverview
 * Provides methods for the Hello Endpoints sample UI and interaction with the
 * Hello Endpoints API.
 *
 * @author danielholevoet@google.com (Dan Holevoet)
 */

/** google global namespace for Google projects. */
var google = google || {};

/** devrel namespace for Google Developer Relations projects. */
google.devrel = google.devrel || {};

/** samples namespace for DevRel sample code. */
google.devrel.samples = google.devrel.samples || {};

/** hello namespace for this sample. */
google.devrel.samples.hello = google.devrel.samples.hello || {};

/**
 * Client ID of the application (from the APIs Console).
 * @type {string}
 */
google.devrel.samples.hello.CLIENT_ID =
    '1001315827289-em9jhbuphg99hnk98un4heo3ffhdi83m.apps.googleusercontent.com';

/**
 * Scopes used by the application.
 * @type {string}
 */
google.devrel.samples.hello.SCOPES =
    'https://www.googleapis.com/auth/userinfo.email';

/**
 * Whether or not the user is signed in.
 * @type {boolean}
 */
google.devrel.samples.hello.signedIn = false;

/**
 * Loads the application UI after the user has completed auth.
 */
google.devrel.samples.hello.userAuthed = function() {
  var request = gapi.client.oauth2.userinfo.get().execute(function(resp) {
    if (!resp.code) {
      google.devrel.samples.hello.signedIn = true;
      document.getElementById('signinButton').innerHTML = 'Sign out';
      document.getElementById('userInfoButton').disabled = false;
    }
  });
};

/**
 * Handles the auth flow, with the given value for immediate mode.
 * @param {boolean} mode Whether or not to use immediate mode.
 * @param {Function} callback Callback to call on completion.
 */
google.devrel.samples.hello.signin = function(mode, callback) {
  gapi.auth.authorize({client_id: google.devrel.samples.hello.CLIENT_ID,
      scope: google.devrel.samples.hello.SCOPES, immediate: mode},
      callback);
};

/**
 * Presents the user with the authorization popup.
 */
google.devrel.samples.hello.auth = function() {
  if (!google.devrel.samples.hello.signedIn) {
    google.devrel.samples.hello.signin(false,
        google.devrel.samples.hello.userAuthed);
  } else {
    google.devrel.samples.hello.signedIn = false;
    document.getElementById('signinButton').innerHTML = 'Sign in';
    document.getElementById('userInfoButton').disabled = true;
  }
};

/**
 * Enables the button callbacks in the UI.
 */
google.devrel.samples.hello.enableButtons = function() {
    document.getElementById('signinButton').onclick = function() {
    google.devrel.samples.hello.auth();
    gapi.client.endpoints.aveProfile().execute();
  }
  document.getElementById('userInfoButton').onclick = function() {
	  google.devrel.samples.hello.getUserInfo();
  }

  document.getElementById('getUserFromDatastore').onclick = function() {
	  google.devrel.samples.hello.getMeFromDatastore();
  }
  document.getElementById('sendFormButton').onclick = function() {
	  createGame();
  }
  document.getElementById('getGamesQueryButton').onclick = function() {
	 getGamesQueryButton();
  }
};

/**
 * Initializes the application.
 * @param {string} apiRoot Root of the API's path.
 */
google.devrel.samples.hello.init = function(apiRoot) {
  // Loads the OAuth and helloworld APIs asynchronously, and triggers login
  // when they have completed.
  var apisToLoad;
  var callback = function() {
    if (--apisToLoad == 0) {
      google.devrel.samples.hello.enableButtons();
      google.devrel.samples.hello.signin(true,
      google.devrel.samples.hello.userAuthed);
    }
  }

  apisToLoad = 2; // must match number of calls to gapi.client.load()
  gapi.client.load('endpoints', 'v1', callback, apiRoot);
  gapi.client.load('oauth2', 'v2', callback);
};

createGame = function() {
	var name =document.getElementById("name").value;
	var description =document.getElementById("description").value;
	//var date =document.getElementById("date").value;
	var attendees =document.getElementById("attendees").value;
	var request =  gapi.client.endpoints.createGame({'name': name, 'description':description, 'maxAttendees':attendees,
		'seatsAvailable':attendees, 'latitude':40, 'longitude':40, 'cancelable':true});
	request.execute(alertInfo);
}

getGamesQueryButton = function(){
	var request = gapi.client.endpoints.getAllGames().execute(
		function(resp) {
			if (!resp.code) {
				resp.items = resp.items || [];
		        for (var i = 0; i < resp.items.length; i++) {
		        	print(resp.items[i]);
		        }
		        alert("END! Items: "+ resp.items.length);
		    }
			else{
				alert("Smth went wrong! resp.code: "+resp.code);
			}
		}
	);
}
print = function(game) {
	  var node = document.createElement("div");
	  var textnode = document.createTextNode("Game name: "+game.name+" "+"Game description: "+game.description);
	  node.appendChild(textnode);
	  document.getElementById("gameNode").appendChild(node);
};

google.devrel.samples.hello.getUserInfo = function() {
	var request =  gapi.client.endpoints.getMyInfo();
	request.execute(alertInfo);
}
google.devrel.samples.hello.getMeFromDatastore = function() {
	var request =  gapi.client.endpoints.getMeFromDatastore();
	request.execute(alertInfo);
}
function alertInfo (response) {
	alert(response.message);
}<|endoftext|>


<commit_before>var asyncMap = require('slide').asyncMap;

var semver = require('./semver');
var github = require('./github');
var npmWrapper = require('./npm');
var db = require('./db');
var emailWrapper = require('./email');

var running = false;

exports.start = function() {
  // Only allow one instance to run at a time
  if (running) {
    console.log("Check already running.");
    return false;
  }
  console.log("Starting check.");
  running = true;
  var retriesLeft = 2;
  checkUpdates(onDone);
  return true;

  function onDone(error) {
    if (error) {
      console.error(error);
      if (retriesLeft--) {
        return checkUpdates(onDone);
      }
      running = false;
      console.log("Giving up!");
    }
    else {
      running = false;
      console.log("Check finished.");
    }
  }
};

function checkUpdates(callback) {

  // Mapping of unique email address to list of packages
  var emails = {};

  // List of packages to monitor, indexed by user/name string
  // Each entry contains:
  //   dependencies - a map of dependency name to version
  //   devDependencies - a map of dev dependency name to version
  var packages = {};

  // This is a mapping of dependency name to dependent package
  // key is dependency name, value is direct reference to entry in packages hash
  var dependents = {};

  // First we need to load all the subscriptions
  db.readSubscriptions(onSubscriptions);

  function onSubscriptions(error, subscriptions) {
    if (error) return callback(error);

    asyncMap(subscriptions, function (subscription, callback) {
      var user = github.getUserFromUrl(subscription.repourl);
      var repo = github.getRepoFromUrl(subscription.repourl);
      var key = user + "/" + repo;

      // Record this email/package combo
      var watching = emails[subscription.email];
      if (watching) watching.push(key);
      else emails[subscription.email] = [key];

      if (packages[key]) {
        // Someone else is already watching for changes in this project
        return;
      }

      packages[key] = {};

      github.getPackageJson(user, repo, function (error, meta) {
        if (error) return callback(error);
        if (meta.dependencies) {
          packages[key].dependencies = meta.dependencies;
          Object.keys(meta.dependencies).forEach(addLink);
        }
        if (meta.devDependencies) {
          packages[key].devDependencies = meta.devDependencies;
          Object.keys(meta.devDependencies).forEach(addLink);
        }
        callback();
      });

      function addLink(name) {
        if (dependents[name]) dependents[name].push(key);
        else dependents[name] = [key];
      }

    }, onProcessed);
  }

  function onProcessed(error) {
    if (error) return callback(error);
    console.log("Checking %s unique packages with %s total unique dependencies for %s unique email addresses.",
                Object.keys(packages).length,
                Object.keys(dependents).length,
                Object.keys(emails).length);
    npmWrapper.getLatestVersions(Object.keys(dependents), onVersions);
  }

  function onVersions(error, versions) {
    if (error) return callback(error);
    console.log({
      emails: emails,
      dependents: dependents,
      packages: packages,
      versions: versions
    });

    // We now have emails of all the people interested in updates.
    // We also have the list of subscriptions grouped by user/name projects key.
    // We also have the latest version of any npm package that we care about.
    // We also have the dependencies and devDependencies of all subscribed packages.

    // Now the task is to loop through the packages, find dependencies and
    // devDependencies that are out of date.  Record a list of packages with
    // out of data deps.
    var newPackages = {};
    Object.keys(packages).forEach(findDependencies);
    var yesterday = new Date();
    yesterday.setHours(yesterday.getHours() - 24);

    function findDependencies(repo) {
      if (!newPackages[repo])
        newPackages[repo] = {};
      newPackages[repo].dependencies = {};
      newPackages[repo].devDependencies = {};

      Object.keys(packages[repo].dependencies).forEach(checkDepVersionFor(packages[repo].dependencies, newPackages[repo].dependencies));
      Object.keys(packages[repo].devDependencies).forEach(checkDepVersionFor(packages[repo].devDependencies, newPackages[repo].devDependencies));

      function checkDepVersionFor(dep, result) {
        return function (package) {
          if (versions[package].updated >= yesterday && semver.isNew(versions[package].latest, dep[package]))
            result[package] = { old: dep[package], current: versions[package].latest };
        };
      }
    }

    // Then loop through the email address and for each one, loop through it's
    // packages.  If any of them had out-of-date deps, prepare and send an email.
    // If sending an email is an async operation, you can do it in an asyncMap
    // so that you can catch errors and be notified when they are all done.
    asyncMap(emails, processEmail, onProcessedEmails);

    function processEmail(email, callback) {
      if (error) return callback(error);

      Object.keys(email).forEach(sendEmail);

      function sendEmail(key) {
        var repo = emails[key];
        var newPacks = newPackages[repo];
        var numNewPacks = Object.keys(newPacks.dependencies).length + Object.keys(newPacks.devDependencies).length;
        if (numNewPacks === 0)
          return callback();

        var repourl = github.getUrlFromUserWithRepo(repo);
        console.info('Sending email to ' + key + ' for ' + repourl + ' about ' + numNewPacks + ' packages.');
        emailWrapper.send(key, repourl, newPacks, callback);
      }
    }

    function onProcessedEmails(error) {
      // Once done, call the outer `callback` to release the global lock and let
      // the server log that the action is complete.
      callback(error);
    }
  }

}
<commit_msg>Minor prettyfying.<commit_after>var asyncMap = require('slide').asyncMap;

var semver = require('./semver');
var github = require('./github');
var npmWrapper = require('./npm');
var db = require('./db');
var emailWrapper = require('./email');

var running = false;

exports.start = function() {
  // Only allow one instance to run at a time
  if (running) {
    console.log("Check already running.");
    return false;
  }
  console.log("Starting check.");
  running = true;
  var retriesLeft = 2;
  checkUpdates(onDone);
  return true;

  function onDone(error) {
    if (error) {
      console.error(error);
      if (retriesLeft--) {
        return checkUpdates(onDone);
      }
      running = false;
      console.log("Giving up!");
    }
    else {
      running = false;
      console.log("Check finished.");
    }
  }
};

function checkUpdates(callback) {

  // Mapping of unique email address to list of packages
  var emails = {};

  // List of packages to monitor, indexed by user/name string
  // Each entry contains:
  //   dependencies - a map of dependency name to version
  //   devDependencies - a map of dev dependency name to version
  var packages = {};

  // This is a mapping of dependency name to dependent package
  // key is dependency name, value is direct reference to entry in packages hash
  var dependents = {};

  // First we need to load all the subscriptions
  db.readSubscriptions(onSubscriptions);

  function onSubscriptions(error, subscriptions) {
    if (error) return callback(error);

    asyncMap(subscriptions, function (subscription, callback) {
      var user = github.getUserFromUrl(subscription.repourl);
      var repo = github.getRepoFromUrl(subscription.repourl);
      var key = user + "/" + repo;

      // Record this email/package combo
      var watching = emails[subscription.email];
      if (watching) watching.push(key);
      else emails[subscription.email] = [key];

      if (packages[key]) {
        // Someone else is already watching for changes in this project
        return;
      }

      packages[key] = {};

      github.getPackageJson(user, repo, function (error, meta) {
        if (error) return callback(error);
        if (meta.dependencies) {
          packages[key].dependencies = meta.dependencies;
          Object.keys(meta.dependencies).forEach(addLink);
        }
        if (meta.devDependencies) {
          packages[key].devDependencies = meta.devDependencies;
          Object.keys(meta.devDependencies).forEach(addLink);
        }
        callback();
      });

      function addLink(name) {
        if (dependents[name]) dependents[name].push(key);
        else dependents[name] = [key];
      }

    }, onProcessed);
  }

  function onProcessed(error) {
    if (error) return callback(error);
    console.log("Checking %s unique packages with %s total unique dependencies for %s unique email addresses.",
                Object.keys(packages).length,
                Object.keys(dependents).length,
                Object.keys(emails).length);
    npmWrapper.getLatestVersions(Object.keys(dependents), onVersions);
  }

  function onVersions(error, versions) {
    if (error) return callback(error);

    console.info({
      emails: emails,
      dependents: dependents,
      packages: packages,
      versions: versions
    });

    // We now have emails of all the people interested in updates.
    // We also have the list of subscriptions grouped by user/name projects key.
    // We also have the latest version of any npm package that we care about.
    // We also have the dependencies and devDependencies of all subscribed packages.

    // Now the task is to loop through the packages, find dependencies and
    // devDependencies that are out of date.  Record a list of packages with
    // out of data deps.
    var newPackages = {};
    var yesterday = new Date();
    yesterday.setHours(yesterday.getHours() - 24);
    Object.keys(packages).forEach(findDependencies);

    function findDependencies(repo) {
      if (!newPackages[repo])
        newPackages[repo] = {};
      newPackages[repo].dependencies = {};
      newPackages[repo].devDependencies = {};

      Object.keys(packages[repo].dependencies).forEach(checkDepVersionFor(packages[repo].dependencies, newPackages[repo].dependencies));
      Object.keys(packages[repo].devDependencies).forEach(checkDepVersionFor(packages[repo].devDependencies, newPackages[repo].devDependencies));

      function checkDepVersionFor(dep, result) {
        return function (package) {
          if (versions[package].updated >= yesterday && semver.isNew(versions[package].latest, dep[package]))
            result[package] = { old: dep[package], current: versions[package].latest };
        };
      }
    }

    // Then loop through the email address and for each one, loop through it's
    // packages.  If any of them had out-of-date deps, prepare and send an email.
    // If sending an email is an async operation, you can do it in an asyncMap
    // so that you can catch errors and be notified when they are all done.
    asyncMap(emails, processEmail, onProcessedEmails);

    function processEmail(email, callback) {
      if (error) return callback(error);

      Object.keys(email).forEach(sendEmail);

      function sendEmail(key) {
        var repo = emails[key];
        var newPacks = newPackages[repo];
        var numNewPacks = Object.keys(newPacks.dependencies).length + Object.keys(newPacks.devDependencies).length;
        if (numNewPacks === 0)
          return callback();

        var repourl = github.getUrlFromUserWithRepo(repo);
        console.info('Sending email to ' + key + ' for ' + repourl + ' about ' + numNewPacks + ' packages.');
        emailWrapper.send(key, repourl, newPacks, callback);
      }
    }

    function onProcessedEmails(error) {
      // Once done, call the outer `callback` to release the global lock and let
      // the server log that the action is complete.
      callback(error);
    }
  }

}
<|endoftext|>


<commit_before>let container = null

Array
  .from(document.querySelectorAll('code.lang-javascript'))
  .forEach(element => {
    container = createContainer(element.parentNode)
    eval(element.textContent)
  })

function createElementFrom (string) {
  const div = document.createElement('div')
  div.innerHTML = string
  return div.firstChild
}

function createContainer (element) {
  const div = document.createElement('div')
  div.innerHTML = '

'
  return element.parentNode.insertBefore(div.firstChild, element.nextSibling)
}

function loadScript (url, callback) {
  const head = document.getElementsByTagName('head')[0]
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = url

  script.onreadystatechange = callback
  script.onload = callback

  head.appendChild(script)
}

function startLoop (callback) {
  const renderFrame = () => {
    window.requestAnimationFrame(renderFrame)
    callback()
  }
  renderFrame()
}

function three (init) {
  const currentContainer = container
  loadScript('https://cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js', () => {
    const width = currentContainer.offsetWidth
    const height = 300

    const scene = new THREE.Scene()

    const camera = new THREE.PerspectiveCamera(50, width / height, 1, 10000)
    camera.position.z = 500
    scene.add(camera)

    const renderer = new THREE.WebGLRenderer({antialias: true, alpha: true})
    renderer.setSize(width, height)

    currentContainer.appendChild(renderer.domElement)

    const onWindowResize = () => {
      const width = currentContainer.offsetWidth
      const height = 300

      camera.aspect = width / height
      camera.updateProjectionMatrix()

      renderer.setSize(width, height)
      renderer.render(scene, camera)
    }

    window.addEventListener('resize', onWindowResize, false)

    const render = (updateFn) => {
      startLoop(() => {
        updateFn()
        renderer.render(scene, camera)
      })
    }

    const renderOnce = () => {
      renderer.render(scene, camera)
    }

    init({
      scene,
      renderer,
      camera,
      render,
      renderOnce
    })
  })
}

function canvas (renderFn) {
  const currentContainer = container
  const pixelRatio = window.devicePixelRatio
  const canvas = container.appendChild(document.createElement('canvas'))
  const context = canvas.getContext('2d')

  const resizeAndRender = () => {
    const width = currentContainer.offsetWidth
    const height = 300

    canvas.width = width * pixelRatio
    canvas.height = height * pixelRatio
    canvas.style.width = width + 'px'
    canvas.style.height = height + 'px'

    renderFn({
      context,
      width: canvas.width,
      height: canvas.height
    })
  }

  window.addEventListener('resize', resizeAndRender, false)

  resizeAndRender()
}

function display (...objects) {
  objects.forEach(o => {
    const prettyObject = JSON.stringify(o)
    const element = createElementFrom(`<pre><code>${prettyObject}</code><i class="fa fa-check-circle-o" aria-hidden="true"></i></pre>`)
    container.appendChild(element)
  })
}

window.three = three
window.canvas = canvas
window.display = display
<commit_msg>run code on animation end<commit_after>let container = null

const whichAnimationEvent = () => {
  var el = document.createElement('fakeelement')
  var animations = {
    'animation': 'animationend',
    'OAnimation': 'oAnimationEnd',
    'MozAnimation': 'animationend',
    'WebkitAnimation': 'webkitAnimationEnd'
  }

  for (let a in animations) {
    if (el.style[a] !== undefined) {
      return animations[a]
    }
  }
}

const heart = document.querySelector('.sidebar-about .fa')

/* Listen for a transition! */
var animationEvent = whichAnimationEvent()
animationEvent && heart.addEventListener(animationEvent, () => {
  Array
  .from(document.querySelectorAll('code.lang-javascript'))
  .forEach(element => {
    container = createContainer(element.parentNode)
    eval(element.textContent)
  })
})

function createElementFrom (string) {
  const div = document.createElement('div')
  div.innerHTML = string
  return div.firstChild
}

function createContainer (element) {
  const div = document.createElement('div')
  div.innerHTML = '

'
  return element.parentNode.insertBefore(div.firstChild, element.nextSibling)
}

function loadScript (url, callback) {
  const head = document.getElementsByTagName('head')[0]
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = url

  script.onreadystatechange = callback
  script.onload = callback

  head.appendChild(script)
}

function startLoop (callback) {
  const renderFrame = () => {
    window.requestAnimationFrame(renderFrame)
    callback()
  }
  renderFrame()
}

function three (init) {
  const currentContainer = container
  loadScript('https://cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js', () => {
    const width = currentContainer.offsetWidth
    const height = 300

    const scene = new THREE.Scene()

    const camera = new THREE.PerspectiveCamera(50, width / height, 1, 10000)
    camera.position.z = 500
    scene.add(camera)

    const renderer = new THREE.WebGLRenderer({antialias: true, alpha: true})
    renderer.setSize(width, height)

    currentContainer.appendChild(renderer.domElement)

    const onWindowResize = () => {
      const width = currentContainer.offsetWidth
      const height = 300

      camera.aspect = width / height
      camera.updateProjectionMatrix()

      renderer.setSize(width, height)
      renderer.render(scene, camera)
    }

    window.addEventListener('resize', onWindowResize, false)

    const render = (updateFn) => {
      startLoop(() => {
        updateFn()
        renderer.render(scene, camera)
      })
    }

    const renderOnce = () => {
      renderer.render(scene, camera)
    }

    init({
      scene,
      renderer,
      camera,
      render,
      renderOnce
    })
  })
}

function canvas (renderFn) {
  const currentContainer = container
  const pixelRatio = window.devicePixelRatio
  const canvas = container.appendChild(document.createElement('canvas'))
  const context = canvas.getContext('2d')

  const resizeAndRender = () => {
    const width = currentContainer.offsetWidth
    const height = 300

    canvas.width = width * pixelRatio
    canvas.height = height * pixelRatio
    canvas.style.width = width + 'px'
    canvas.style.height = height + 'px'

    renderFn({
      context,
      width: canvas.width,
      height: canvas.height
    })
  }

  window.addEventListener('resize', resizeAndRender, false)

  resizeAndRender()
}

function display (...objects) {
  objects.forEach(o => {
    const prettyObject = JSON.stringify(o)
    const element = createElementFrom(`<pre><code>${prettyObject}</code><i class="fa fa-check-circle-o" aria-hidden="true"></i></pre>`)
    container.appendChild(element)
  })
}

window.three = three
window.canvas = canvas
window.display = display
<|endoftext|>


<commit_before>var Parse = require('parse').Parse,
		usr = require('user-settings').file('.omgconfig'),
		inquirer = require('inquirer'),
		validator = require('validator'),
		models = require(__dirname + '/models'),
		spinner = require(__dirname + '/spinner');
require('colors');

function noop() {}

function logOut(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	usr.unset('sessionToken');
	console.log('ACCESS TERMINATED'.green);
	process.exit(0);
	fn();
}

function logIn(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	var inqUser = {name:'username', message:'username: '};
	var inqPass = {name:'password', message:'password: ', type:'password'};
	inquirer.prompt([inqUser, inqPass], function(input) {
		Parse.User.logIn(input.username, input.password, {
			success: function(user) {
				console.log('ACCESS GRANTED'.green);
				usr.set('sessionToken', user.getSessionToken());
				fn(user);
			},
			error: function(user, error) {
				if (error.code === 101) {
					console.error('ACCESS DENIED'.red.bold);
					process.exit(1);
				} else {
					console.error((error.message).red);
					process.exit(1);
				}
			}
		});
	});
}

function signUp(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	var inqUser = {name:'username', message:'username: '};
	var inqPass = {name:'password', message:'password: ', type:'password'};
	var inqEmail = {name:'email', message:'email: ', validate:validator.isEmail};
	inquirer.prompt([inqUser, inqPass, inqEmail], function(input) {
		var user = new Parse.User();
		user.set('username', input.username);
		user.set('password', input.password);
		user.set('email', input.email);
		user.signUp(null, {
			success: function(user) {
				console.log('ACCESS GRANTED'.green);
				usr.set('sessionToken', user.getSessionToken());
				fn(user);
			},
			error: function(user, error) {
				console.error((error.message).red);
				process.exit(1);
			}
		});
	});
}

function session(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	var sessionToken = usr.get('sessionToken');

	if(sessionToken) {
		spinner.start('Authenticating'.grey);
		Parse.User.become(sessionToken, {
			success: function(user) {
				spinner.stop();
				fn(user);
			},
			error: function(user, error) {
				spinner.stop();
				usr.unset('sessionToken');
				console.error('ACCESS EXPIRED'.red);
				process.exit(1);
			}
		})
	} else {
		var inqAuth = {
			name:'auth',
			message:'Authorization',
			type:'list',
			choices: [ 'Log In', 'Register', 'Leave' ]
		};
		inquirer.prompt([inqAuth], function(input) {
			if (input.auth === 'Log In') logIn(fn);
			else if (input.auth === 'Register') signUp(fn);
			else process.exit(0);
		});
	}
}

module.exports = {
	session: function(fn) { session(fn); },
	signUp: function() { signUp(noop); },
	logIn: function() { logIn(noop); },
	logOut:  function() { logOut(noop); }
};<commit_msg>Add spinner message to login and signup commands<commit_after>var Parse = require('parse').Parse,
		usr = require('user-settings').file('.omgconfig'),
		inquirer = require('inquirer'),
		validator = require('validator'),
		models = require(__dirname + '/models'),
		spinner = require(__dirname + '/spinner');
require('colors');

function noop() {}

function logOut(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	usr.unset('sessionToken');
	console.log('ACCESS TERMINATED'.green);
	process.exit(0);
	fn();
}

function logIn(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	var inqUser = {name:'username', message:'username: '};
	var inqPass = {name:'password', message:'password: ', type:'password'};
	inquirer.prompt([inqUser, inqPass], function(input) {
		spinner.start('Authenticating'.grey);
		Parse.User.logIn(input.username, input.password, {
			success: function(user) {
				spinner.stop();
				console.log('ACCESS GRANTED'.green);
				usr.set('sessionToken', user.getSessionToken());
				fn(user);
			},
			error: function(user, error) {
				spinner.stop();
				if (error.code === 101) {
					console.error('ACCESS DENIED'.red.bold);
					process.exit(1);
				} else {
					console.error((error.message).red);
					process.exit(1);
				}
			}
		});
	});
}

function signUp(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	var inqUser = {name:'username', message:'username: '};
	var inqPass = {name:'password', message:'password: ', type:'password'};
	var inqEmail = {name:'email', message:'email: ', validate:validator.isEmail};
	inquirer.prompt([inqUser, inqPass, inqEmail], function(input) {
		var user = new Parse.User();
		user.set('username', input.username);
		user.set('password', input.password);
		user.set('email', input.email);
		spinner.start('Signing up'.grey);
		user.signUp(null, {
			success: function(user) {
				spinner.stop();
				console.log('ACCESS GRANTED'.green);
				usr.set('sessionToken', user.getSessionToken());
				fn(user);
			},
			error: function(user, error) {
				spinner.stop();
				console.error((error.message).red);
				process.exit(1);
			}
		});
	});
}

function session(fn) {
	if (fn && typeof fn !== 'function') throw new Error('argument must be a function');
	var sessionToken = usr.get('sessionToken');

	if(sessionToken) {
		spinner.start('Authenticating'.grey);
		Parse.User.become(sessionToken, {
			success: function(user) {
				spinner.stop();
				fn(user);
			},
			error: function(user, error) {
				spinner.stop();
				usr.unset('sessionToken');
				console.error('ACCESS EXPIRED'.red);
				process.exit(1);
			}
		})
	} else {
		var inqAuth = {
			name:'auth',
			message:'Authorization',
			type:'list',
			choices: [ 'Log In', 'Register', 'Leave' ]
		};
		inquirer.prompt([inqAuth], function(input) {
			if (input.auth === 'Log In') logIn(fn);
			else if (input.auth === 'Register') signUp(fn);
			else process.exit(0);
		});
	}
}

module.exports = {
	session: function(fn) { session(fn); },
	signUp: function() { signUp(noop); },
	logIn: function() { logIn(noop); },
	logOut:  function() { logOut(noop); }
};<|endoftext|>


<commit_before>var inherits = require('util').inherits;
var Transform = require('stream').Transform;
var toIntArr = require('./tools').toIntArr;
var optimist = require('./tools').optimist;
var FixedQueue = require('./fixedqueue');
var csv = require('csv');
var _ = require('underscore');

var operators = {
  incsv: function(args) {
    var argv = optimist()
      .options({
        d: {alias: 'delimiter', default: ',', string: true},
        e: {alias: 'encoding', default: 'utf-8', string: true},
        p: {alias: 'escapechar', default: '\\', string: true},
        q: {alias: 'quotechar', default: '\"', string: true},
        t: {alias: 'tabs', boolean: true},
        H: {alias: 'no-header-row', boolean: true},
        S: {alias: 'skipinitialspace', boolean: true},
      })
      .parse(args)
    ;
    if (argv.t) {
      // tabs switch overrides delimiter opt
      argv.d = '\t';
    }
    return csv()
      .from.options({
        delimiter: argv.d,
        encoding: argv.e,
        escape: argv.p,
        quote: argv.q,
        ltrim: argv.S,
      })
      .transform(function(row, index) {
        return JSON.stringify({'row': row, 'index': index});
      });
  },

  // return our HEAD transformation
  head: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options('n', {
        default: 10,
      })
      .parse(args)
    ;

    this._number = argv.n;
    this._lines = 0;
  },

  // return our tail transformation
  tail: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options('n', {
        default: '10',
        string: true
      })
      .parse(args)
    ;

    var number = argv.n;

    if (number.charAt(0) == '+') {
      // relative to the beginning of the stream
      this._rel = 'beginning';
      this._lines = 0;
      this._number = number;
    } else {
      // relative to the end of the stream
      this._rel = 'end';
      if (number.charAt(0) == '-') {
        number = -number;
      }
      this._fixedqueue = new FixedQueue(number);
    }
  },

  // return a transformation that will cut columns.
  // Accepts a comma separated list of column positions to remove.
  // This is 0-indexed.
  cut: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .boolean('complement')
      .demand(1)
      .parse(args)
    ;

    var columns = argv._[0].toString();
    // Convert the indices to ints
    this._idxes = toIntArr(columns);
    this._complement = argv.complement;
    // have we performed the complement yet?
    this._complemented = false;
  },

  // transformation that will grep for a pattern
  grep: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options({
        c: {alias: 'columns', string: true},
        e: {alias: 'regexp', string: true},
        v: {alias: 'invert-match', boolean: true},
      })
      .parse(args)
    ;

    if (argv.c !== undefined) {
      this._cols = toIntArr(argv.c);
    }

    var regex;
    if (argv.e !== undefined) {
      regex = argv.e;
    } else {
      regex = argv._[0];
    }
    this._pattern = new RegExp(regex);

    this._invert = argv.v;
  },

  // return a transformation that will delete empty rows
  strip: function(args) {
    Transform.call(this, {objectMode: true});
  },

  // transformation that will delete rows
  delete: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .demand(1)
      .parse(args)
    ;

    var range = argv._[0].toString();
    this._parts = range.split(',');
    this._index = 0;
  },

  outcsv: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options({
        d: {alias: 'delimiter', default: ',', string: true},
        p: {alias: 'escapechar', default: '\\', string: true},
        q: {alias: 'quotechar', default: '\"', string: true},
        t: {alias: 'tabs', boolean: true},
        H: {alias: 'no-header-row', boolean: true},
      })
      .parse(args)
    ;
    if (argv.t) {
      // tabs switch overrides delimiter opt
      argv.d = '\t';
    }
    this._options = {
      delimiter: argv.d,
      escape: argv.p,
      quote: argv.q,
    };
  },

  // return our HTML transformation
  outhtml: function(args) {
    Transform.call(this, {objectMode: true});
    this._initialHtmlSent = false;
  },
};

inherits(operators.head, Transform);

operators.head.prototype._transform = function(chunk, encoding, done) {
  if (this._lines < this._number) {
    this._lines += 1;
    this.push(chunk);
  }

  done();
};

inherits(operators.tail, Transform);

operators.tail.prototype._transform = function(chunk, encoding, done) {
  if (this._rel == 'end') {
    this._fixedqueue.push(chunk);
  } else {
    if (this._lines < this._number) {
      this._lines += 1;
    } else {
      this.push(chunk);
    }
  }
  done();
};

operators.tail.prototype._flush = function(done) {
  if (this._rel == 'end') {
    var chunk = this._fixedqueue.shift();
    while (chunk !== undefined) {
      this.push(chunk);
      chunk = this._fixedqueue.shift();
    }
  }
  done();
};

inherits(operators.cut, Transform);

operators.cut.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);

  if (this._complement && !this._complemented) {
    this._idxes = _.difference(_.range(json.row.length), this._idxes);
    this._complemented = true;
  }

  _.each(this._idxes, function(position) {
    delete json.row[position];
  });

  json.row = _.without(json.row, undefined);

  this.push(JSON.stringify(json));

  done();
};

inherits(operators.grep, Transform);

operators.grep.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);

  if (json.index === 0) {
    this.push(chunk);
    return done();
  }

  var match = false;
  var self = this;

  if (this._cols !== undefined) {
    _.each(this._cols, function(col) {
      if (self._pattern.test(json.row[col])) {
        match = true;
      }
    });
  } else {
    _.each(json.row, function(value) {
      if (self._pattern.test(value)) {
        match = true;
      }
    });
  }

  if (this._invert) {
    match = !match;
  }

  if (match) {
    this.push(chunk);
  }

  done();
};

inherits(operators.strip, Transform);

operators.strip.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);

  var keep = _.some(json.row, function(val) {
    return val !== '';
  });

  if (keep) {
    this.push(chunk);
  }

  done();
};

inherits(operators.delete, Transform);

operators.delete.prototype._transform = function(chunk, encoding, done) {
  if(_.isUndefined(this._parts)){
    this.push(chunk);
  }

  var idx = this._index;

  var matches = false;
  _.each(this._parts, function(part) {
    if (part.indexOf(':') != -1) {
      var _t = part.split(':');
      if (idx >= _t[0] && idx <= _t[1]) {
        matches = true;
      }
    } else {
      part = parseInt(part);
      if (idx == part) {
        matches = true;
      }
    }
  });

  if (!matches) this.push(chunk);

  this._index += 1;

  done();
};

inherits(operators.outcsv, Transform);

operators.outcsv.prototype._transform = function(chunk, encoding, done) {
  var self = this;
  var row = JSON.parse(chunk).row;

  csv()
    .from.array([row])
    .to.string(function(data){
      self.push(data + '\n');
      done();
    }, self._options)
  ;
};

operators.outcsv.prototype.contentType = function() {
  return "text/plain; charset=utf-8";
};

inherits(operators.outhtml, Transform);

operators.outhtml.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);
  var self = this;

  if (!this._initialHtmlSent) {
    this.push('');
    this.push('');
    this.push('<link rel="stylesheet" href="/css/style.css" />');
    this.push('');
    this.push('');
    this.push('
');
    this.push('
');
    this.push('
	');

    this._initialHtmlSent = true;
  }

  if (json.index === 0) {
    json.row.forEach(function(item) {
      self.push('%s	'.replace(/%s/g, item));
    });
    this.push('

');
  } else {
    this.push('
%s	'.replace(/%s/g, json.index));
    json.row.forEach(function(item) {
      self.push('
' + item + '
	');
    });
    this.push('
');
  }

  done();
};

operators.outhtml.prototype._flush = function(done) {
  this.push('
');
  this.push('
');
  this.push('');
  this.push('');
  this.push('');
  this.push('');

  done();
};

operators.outhtml.prototype.contentType = function() {
  return "text/html; charset=utf-8";
};

module.exports = operators;
<commit_msg>Stop streaming and respond once we’ve read enough.<commit_after>var inherits = require('util').inherits;
var Transform = require('stream').Transform;
var toIntArr = require('./tools').toIntArr;
var optimist = require('./tools').optimist;
var FixedQueue = require('./fixedqueue');
var csv = require('csv');
var _ = require('underscore');

var operators = {
  incsv: function(args) {
    var argv = optimist()
      .options({
        d: {alias: 'delimiter', default: ',', string: true},
        e: {alias: 'encoding', default: 'utf-8', string: true},
        p: {alias: 'escapechar', default: '\\', string: true},
        q: {alias: 'quotechar', default: '\"', string: true},
        t: {alias: 'tabs', boolean: true},
        H: {alias: 'no-header-row', boolean: true},
        S: {alias: 'skipinitialspace', boolean: true},
      })
      .parse(args)
    ;
    if (argv.t) {
      // tabs switch overrides delimiter opt
      argv.d = '\t';
    }
    return csv()
      .from.options({
        delimiter: argv.d,
        encoding: argv.e,
        escape: argv.p,
        quote: argv.q,
        ltrim: argv.S,
      })
      .transform(function(row, index) {
        return JSON.stringify({'row': row, 'index': index});
      });
  },

  // return our HEAD transformation
  head: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options('n', {
        default: 10,
      })
      .parse(args)
    ;

    this._number = argv.n;
    this._lines = 0;
  },

  // return our tail transformation
  tail: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options('n', {
        default: '10',
        string: true
      })
      .parse(args)
    ;

    var number = argv.n;

    if (number.charAt(0) == '+') {
      // relative to the beginning of the stream
      this._rel = 'beginning';
      this._lines = 0;
      this._number = number;
    } else {
      // relative to the end of the stream
      this._rel = 'end';
      if (number.charAt(0) == '-') {
        number = -number;
      }
      this._fixedqueue = new FixedQueue(number);
    }
  },

  // return a transformation that will cut columns.
  // Accepts a comma separated list of column positions to remove.
  // This is 0-indexed.
  cut: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .boolean('complement')
      .demand(1)
      .parse(args)
    ;

    var columns = argv._[0].toString();
    // Convert the indices to ints
    this._idxes = toIntArr(columns);
    this._complement = argv.complement;
    // have we performed the complement yet?
    this._complemented = false;
  },

  // transformation that will grep for a pattern
  grep: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options({
        c: {alias: 'columns', string: true},
        e: {alias: 'regexp', string: true},
        v: {alias: 'invert-match', boolean: true},
      })
      .parse(args)
    ;

    if (argv.c !== undefined) {
      this._cols = toIntArr(argv.c);
    }

    var regex;
    if (argv.e !== undefined) {
      regex = argv.e;
    } else {
      regex = argv._[0];
    }
    this._pattern = new RegExp(regex);

    this._invert = argv.v;
  },

  // return a transformation that will delete empty rows
  strip: function(args) {
    Transform.call(this, {objectMode: true});
  },

  // transformation that will delete rows
  delete: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .demand(1)
      .parse(args)
    ;

    var range = argv._[0].toString();
    this._parts = range.split(',');
    this._index = 0;
  },

  outcsv: function(args) {
    Transform.call(this, {objectMode: true});

    var argv = optimist()
      .options({
        d: {alias: 'delimiter', default: ',', string: true},
        p: {alias: 'escapechar', default: '\\', string: true},
        q: {alias: 'quotechar', default: '\"', string: true},
        t: {alias: 'tabs', boolean: true},
        H: {alias: 'no-header-row', boolean: true},
      })
      .parse(args)
    ;
    if (argv.t) {
      // tabs switch overrides delimiter opt
      argv.d = '\t';
    }
    this._options = {
      delimiter: argv.d,
      escape: argv.p,
      quote: argv.q,
    };
  },

  // return our HTML transformation
  outhtml: function(args) {
    Transform.call(this, {objectMode: true});
    this._initialHtmlSent = false;
  },
};

inherits(operators.head, Transform);

operators.head.prototype._transform = function(chunk, encoding, done) {
  if (this._lines < this._number) {
    this._lines += 1;
    this.push(chunk);
  } else {
    this.push(null);
  }

  done();
};

inherits(operators.tail, Transform);

operators.tail.prototype._transform = function(chunk, encoding, done) {
  if (this._rel == 'end') {
    this._fixedqueue.push(chunk);
  } else {
    if (this._lines < this._number) {
      this._lines += 1;
    } else {
      this.push(chunk);
    }
  }
  done();
};

operators.tail.prototype._flush = function(done) {
  if (this._rel == 'end') {
    var chunk = this._fixedqueue.shift();
    while (chunk !== undefined) {
      this.push(chunk);
      chunk = this._fixedqueue.shift();
    }
  }
  done();
};

inherits(operators.cut, Transform);

operators.cut.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);

  if (this._complement && !this._complemented) {
    this._idxes = _.difference(_.range(json.row.length), this._idxes);
    this._complemented = true;
  }

  _.each(this._idxes, function(position) {
    delete json.row[position];
  });

  json.row = _.without(json.row, undefined);

  this.push(JSON.stringify(json));

  done();
};

inherits(operators.grep, Transform);

operators.grep.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);

  if (json.index === 0) {
    this.push(chunk);
    return done();
  }

  var match = false;
  var self = this;

  if (this._cols !== undefined) {
    _.each(this._cols, function(col) {
      if (self._pattern.test(json.row[col])) {
        match = true;
      }
    });
  } else {
    _.each(json.row, function(value) {
      if (self._pattern.test(value)) {
        match = true;
      }
    });
  }

  if (this._invert) {
    match = !match;
  }

  if (match) {
    this.push(chunk);
  }

  done();
};

inherits(operators.strip, Transform);

operators.strip.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);

  var keep = _.some(json.row, function(val) {
    return val !== '';
  });

  if (keep) {
    this.push(chunk);
  }

  done();
};

inherits(operators.delete, Transform);

operators.delete.prototype._transform = function(chunk, encoding, done) {
  if(_.isUndefined(this._parts)){
    this.push(chunk);
  }

  var idx = this._index;

  var matches = false;
  _.each(this._parts, function(part) {
    if (part.indexOf(':') != -1) {
      var _t = part.split(':');
      if (idx >= _t[0] && idx <= _t[1]) {
        matches = true;
      }
    } else {
      part = parseInt(part);
      if (idx == part) {
        matches = true;
      }
    }
  });

  if (!matches) this.push(chunk);

  this._index += 1;

  done();
};

inherits(operators.outcsv, Transform);

operators.outcsv.prototype._transform = function(chunk, encoding, done) {
  var self = this;
  var row = JSON.parse(chunk).row;

  csv()
    .from.array([row])
    .to.string(function(data){
      self.push(data + '\n');
      done();
    }, self._options)
  ;
};

operators.outcsv.prototype.contentType = function() {
  return "text/plain; charset=utf-8";
};

inherits(operators.outhtml, Transform);

operators.outhtml.prototype._transform = function(chunk, encoding, done) {
  var json = JSON.parse(chunk);
  var self = this;

  if (!this._initialHtmlSent) {
    this.push('');
    this.push('');
    this.push('<link rel="stylesheet" href="/css/style.css" />');
    this.push('');
    this.push('');
    this.push('
');
    this.push('
');
    this.push('
	');

    this._initialHtmlSent = true;
  }

  if (json.index === 0) {
    json.row.forEach(function(item) {
      self.push('%s	'.replace(/%s/g, item));
    });
    this.push('

');
  } else {
    this.push('
%s	'.replace(/%s/g, json.index));
    json.row.forEach(function(item) {
      self.push('
' + item + '
	');
    });
    this.push('
');
  }

  done();
};

operators.outhtml.prototype._flush = function(done) {
  this.push('
');
  this.push('
');
  this.push('');
  this.push('');
  this.push('');
  this.push('');

  done();
};

operators.outhtml.prototype.contentType = function() {
  return "text/html; charset=utf-8";
};

module.exports = operators;
<|endoftext|>


<commit_before>$(document).ready(function() {
    c3.generate({
        bindto: '#circle-donut',
        data: {
            // iris data from R
            columns: [
                ['data1', 30],
                ['data2', 120],
            ],
            type : 'pie',
            onclick: function (d, i) { console.log("onclick", d, i); },
            onmouseover: function (d, i) { console.log("onmouseover", d, i); },
            onmouseout: function (d, i) { console.log("onmouseout", d, i); }
        }
    });

    setTimeout(function () {
        chart.load({
            columns: [
                ["setosa", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
                ["versicolor", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3],
                ["virginica", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8],
            ]
        });
    }, 1500);

    setTimeout(function () {
        chart.unload({
            ids: 'data1'
        });
        chart.unload({
            ids: 'data2'
        });
    }, 2500);

    c3.generate({
        bindto: '#line-chart',
        data: {
            columns: [
                ['data1', 100, 200, 150, 300, 200],
                ['data2', 400, 500, 250, 700, 300],
            ]
        }
    });
});<commit_msg>fix animation timeout<commit_after>$(document).ready(function() {
    const circleDonut = c3.generate({
        bindto: '#circle-donut',
        data: {
            // iris data from R
            columns: [
                ['data1', 30],
                ['data2', 120],
            ],
            type : 'pie',
            onclick: function (d, i) { console.log("onclick", d, i); },
            onmouseover: function (d, i) { console.log("onmouseover", d, i); },
            onmouseout: function (d, i) { console.log("onmouseout", d, i); }
        }
    });

    setTimeout(function () {
        circleDonut.load({
            columns: [
                ["setosa", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
                ["versicolor", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3],
                ["virginica", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8],
            ]
        });
    }, 1500);

    setTimeout(function () {
        circleDonut.unload({
            ids: 'data1'
        });
        circleDonut.unload({
            ids: 'data2'
        });
    }, 2500);

    const lineChart = c3.generate({
        bindto: '#line-chart',
        data: {
            columns: [
                ['data1', 100, 200, 150, 300, 200],
                ['data2', 400, 500, 250, 700, 300],
            ]
        }
    });
});<|endoftext|>


<commit_before>
import { expect } from 'chai';
import transform from 'xod-espruino/transformer';

describe('Transformer', () => {
  it('should transform empty json to empty result', () => {
    const result = transform({});
    expect(result.nodes).to.be.eql({});
    expect(result.impl).to.be.eql({});
  });

  it('should merge node and node type', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: {
              id: 42,
              typeId: 'core/add100',
              properties: { someValue: 'foo' },
            },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          key: 'core/add100',
          pure: true,
          pins: {
            valueIn: {
              direction: 'input',
              key: 'valueIn',
              type: 'number',
            },
            valueOut: {
              direction: 'output',
              key: 'valueOut',
              type: 'number',
            },
          },
        },
      },
    });

    expect(result.nodes).to.be.eql({
      42: {
        id: 42,
        implId: 'core/add100',
        pure: true,
        inputTypes: {
          valueIn: Number,
        },
        outLinks: {},
        props: { someValue: 'foo' },
      },
    });
  });

  it('should extract implementation', () => {
    const js = 'module.exports.setup = function() {}';
    const cpp = 'void setup(void*) {}';

    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          impl: { js, cpp },
        },
      },
    }, ['es6', 'js']);

    expect(result.impl).to.be.eql({ 'core/add100': js });
  });

  it('should merge links', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
            43: { id: 43, typeId: 'core/add100' },
          },
          pins: {
            421: { id: 421, nodeId: 42, key: 'valueIn' },
            422: { id: 422, nodeId: 42, key: 'valueOut' },
            431: { id: 431, nodeId: 43, key: 'valueIn' },
            432: { id: 432, nodeId: 43, key: 'valueOut' },
          },
          links: {
            1: { id: 1, pins: [422, 431] },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          pins: {
            valueIn: {
              direction: 'input',
              key: 'valueIn',
              type: 'number',
            },
            valueOut: {
              direction: 'output',
              key: 'valueOut',
              type: 'number',
            },
          },
        },
      },
    });

    expect(result.nodes[42].outLinks).to.be.eql({
      valueOut: [{
        nodeId: 43,
        key: 'valueIn',
      }],
    });
  });

  it('should merge patches', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
          },
        },
        2: {
          id: 2,
          nodes: {
            43: { id: 43, typeId: 'core/add100' },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          pins: {},
        },
      },
    });

    expect(result.nodes).to.have.property(42);
    expect(result.nodes).to.have.property(43);
  });

  it('should sort nodes', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
            43: { id: 43, typeId: 'core/add100' },
          },
          pins: {
            421: { id: 421, nodeId: 42, key: 'valueIn' },
            422: { id: 422, nodeId: 42, key: 'valueOut' },
            431: { id: 431, nodeId: 43, key: 'valueIn' },
            432: { id: 432, nodeId: 43, key: 'valueOut' },
          },
          links: {
            1: { id: 1, pins: [422, 431] },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          pins: {
            valueIn: {
              direction: 'input',
              key: 'valueIn',
              type: 'number',
            },
            valueOut: {
              direction: 'output',
              key: 'valueOut',
              type: 'number',
            },
          },
        },
      },
    });

    expect(result.topology).to.be.eql([42, 43]);
  });
});
<commit_msg>fix(test): fix transformerSpec tests (removed pins and replaced old links definition that uses pin Ids with new that uses nodeId and pinKey)<commit_after>
import { expect } from 'chai';
import transform from 'xod-espruino/transformer';

describe('Transformer', () => {
  it('should transform empty json to empty result', () => {
    const result = transform({});
    expect(result.nodes).to.be.eql({});
    expect(result.impl).to.be.eql({});
  });

  it('should merge node and node type', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: {
              id: 42,
              typeId: 'core/add100',
              properties: { someValue: 'foo' },
            },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          key: 'core/add100',
          pure: true,
          pins: {
            valueIn: {
              direction: 'input',
              key: 'valueIn',
              type: 'number',
            },
            valueOut: {
              direction: 'output',
              key: 'valueOut',
              type: 'number',
            },
          },
        },
      },
    });

    expect(result.nodes).to.be.eql({
      42: {
        id: 42,
        implId: 'core/add100',
        pure: true,
        inputTypes: {
          valueIn: Number,
        },
        outLinks: {},
        props: { someValue: 'foo' },
      },
    });
  });

  it('should extract implementation', () => {
    const js = 'module.exports.setup = function() {}';
    const cpp = 'void setup(void*) {}';

    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          impl: { js, cpp },
        },
      },
    }, ['es6', 'js']);

    expect(result.impl).to.be.eql({ 'core/add100': js });
  });

  it('should merge links', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
            43: { id: 43, typeId: 'core/add100' },
          },
          links: {
            1: {
              id: 1,
              pins: [
                { nodeId: 42, pinKey: 'valueOut' },
                { nodeId: 43, pinKey: 'valueIn' },
              ],
            },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          pins: {
            valueIn: {
              direction: 'input',
              key: 'valueIn',
              type: 'number',
            },
            valueOut: {
              direction: 'output',
              key: 'valueOut',
              type: 'number',
            },
          },
        },
      },
    });

    expect(result.nodes[42].outLinks).to.be.eql({
      valueOut: [{
        nodeId: 43,
        key: 'valueIn',
      }],
    });
  });

  it('should merge patches', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
          },
        },
        2: {
          id: 2,
          nodes: {
            43: { id: 43, typeId: 'core/add100' },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          pins: {},
        },
      },
    });

    expect(result.nodes).to.have.property(42);
    expect(result.nodes).to.have.property(43);
  });

  it('should sort nodes', () => {
    const result = transform({
      patches: {
        1: {
          id: 1,
          nodes: {
            42: { id: 42, typeId: 'core/add100' },
            43: { id: 43, typeId: 'core/add100' },
          },
          links: {
            1: {
              id: 1,
              pins: [
                { nodeId: 42, pinKey: 'valueOut' },
                { nodeId: 43, pinKey: 'valueIn' },
              ],
            },
          },
        },
      },
      nodeTypes: {
        'core/add100': {
          id: 'core/add100',
          pins: {
            valueIn: {
              direction: 'input',
              key: 'valueIn',
              type: 'number',
            },
            valueOut: {
              direction: 'output',
              key: 'valueOut',
              type: 'number',
            },
          },
        },
      },
    });

    expect(result.topology).to.be.eql([42, 43]);
  });
});
<|endoftext|>


<commit_before>const exec     = require('./exec');
const parallel = require('./parallel');

const auto = (tasks) => {
  const results = typeof tasks.length === 'number' ? [] : {};

  const executeNextTasks = (lastTaskName) => {
    const nextTaskNames = Object.keys(tasks)
      .filter(n => typeof tasks[n][0] === 'function');

    if (nextTaskNames.length < 0) {
      return Promise.resolve();
    }

    const promises = nextTaskNames.map((nextTaskName) => {
      const task = tasks[nextTaskName];
      delete tasks[nextTaskName];

      return exec(task[0])
        .then((value) => {
          results[nextTaskName] = value;
        })
        .then(() => {
          for (const taskName in tasks) {
            const task = tasks[taskName];
            const i    = task.indexOf(nextTaskName);
            if (i > -1) { task.splice(i, 1); }
          }
        })
        .then(executeNextTasks);
    });

    return Promise.all(promises).then(() => results);
  }

  const taskNames = Object.keys(tasks);
  for (const taskName of taskNames) {
    if (typeof tasks[taskName] === 'function') {
      tasks[taskName] = [tasks[taskName]];
    }
    for (const depTaskName of tasks[taskName]) {
      if (typeof depTaskName === 'string' && !taskNames.includes(depTaskName)) {
        throw new Error(
          `The task ${taskName} is depends upon a task named ${depTaskName}, ` +
          `but ${depTaskName} does not exist`
        );
      }
    }
  }

  return executeNextTasks();
};

module.exports = auto;
<commit_msg>auto always returns an object<commit_after>const exec     = require('./exec');
const parallel = require('./parallel');

const auto = (tasks) => {
  const results = {};

  const executeNextTasks = (lastTaskName) => {
    const nextTaskNames = Object.keys(tasks)
      .filter(n => typeof tasks[n][0] === 'function');

    if (nextTaskNames.length < 0) {
      return Promise.resolve();
    }

    const promises = nextTaskNames.map((nextTaskName) => {
      const task = tasks[nextTaskName];
      delete tasks[nextTaskName];

      return exec(task[0])
        .then((value) => {
          results[nextTaskName] = value;
        })
        .then(() => {
          for (const taskName in tasks) {
            const task = tasks[taskName];
            const i    = task.indexOf(nextTaskName);
            if (i > -1) { task.splice(i, 1); }
          }
        })
        .then(executeNextTasks);
    });

    return Promise.all(promises).then(() => results);
  }

  const taskNames = Object.keys(tasks);
  for (const taskName of taskNames) {
    if (typeof tasks[taskName] === 'function') {
      tasks[taskName] = [tasks[taskName]];
    }
    for (const depTaskName of tasks[taskName]) {
      if (typeof depTaskName === 'string' && !taskNames.includes(depTaskName)) {
        throw new Error(
          `The task ${taskName} is depends upon a task named ${depTaskName}, ` +
          `but ${depTaskName} does not exist`
        );
      }
    }
  }

  return executeNextTasks();
};

module.exports = auto;
<|endoftext|>