<commit_before>/**
 * ------------------------------------------
 * 播放器控件实现文件
 * @version  1.0
 * @author   genify(caijf@corp.netease.com)
 * ------------------------------------------
 */
var f = function() {
    // variable declaration
    var _  = NEJ.P,
        _e = _('nej.e'),
        _u = _('nej.u'),
        _t = _('nej.ut'),
        _n = _('nej.n'),
        _p = _('nej.cef.ut'),
        _player = _('window.player'),
        _proPlayer;
    /**
     * 播放器控件，单例模式使用
     *
     * @singleton
     * @class   {nej.cef.ut._$$Player}
     * @extends {nej.ut._$$Event}
     * @param   {Object} 配置参数
     *
     * [hr]
     * 播放状态变化触发事件，播放状态值说明
     * [ntb]
     *   状态值  |  说明
     *   ------------------
     *   0    |  缓冲阶段
     *   1    |  播放状态
     *   2    |  暂停状态
     *   3    |  停止状态
     *   4    |  播放至结尾
     *   5    |  播放异常
     * [/ntb]
     * @event  {onstatechange}
     * @param  {Object} 状态信息
     * @config {Number} state 状态值，见说明表
     *
     * [hr]
     * 播放位置变化触发事件
     * @event  {onpositionchange}
     * @param  {Object} 播放信息
     * @config {Float} current  当前位置
     * @config {Float} duration 音乐总时长
     *
     * [hr]
     * 音量变化触发事件
     * @event  {onvolumechange}
     * @param  {Object} 音量信息
     * @config {Float}  volume 当前音量值，0.0-1.0
     *
     * [hr]
     * 静音状态变化触发事件
     * @event  {onmutechange}
     * @param  {Object}  静音状态信息
     * @config {Boolean} mute 静音状态，true-静音，false-非静音
     *
     * [hr]
     * 歌曲变化触发事件
     * @event  {ontrackchange}
     * @param  {Object}  静音状态信息
     * @config {Boolean} flag 变化标识，-1-上一首，1-下一首
     *
     * [hr]
     * 播放模式变化触发事件，模式说明
     * [ntb]
     *   名称                       |  说明
     *   -----------------------
     *   playorder  |  顺序播放
     *   playcycle  |  循环播放
     *   playrandom |  随机播放
     * [/ntb]
     * @event  {onmodechange}
     * @param  {Object}  静音状态信息
     * @config {Boolean} mode 模式，见描述
     *
     * [hr]
     * 歌词更新触发事件
     * @event  {onlrcupdate}
     * @param  {Object}  歌词信息
     * @config {String}  id  歌曲ID
     * @config {String}  lrc 歌词内容
     *
     *
     */
    _p._$$Player = NEJ.C();
      _proPlayer = _p._$$Player._$extend(_t._$$Event);
    /**
     * 控件初始化
     * @return {Void}
     */
    _proPlayer.__init = function(){
        this.__nevt = [
            'volumechange','notify',
            'dataloaded','play','pause',
            'ended',,'playmode','error','playpre',
            'playnext','timeupdate','lyricsupdate'
        ];
        this.__supInit();
    };
    /**
     * 控件重置
     * @param  {Object} 配置信息
     * @return {Void}
     */
    _proPlayer.__reset = (function(){
        // add native event
        var _doAddEvent = function(_name){
            _player['on'+_name] = this.
                __onNativeEvent._$bind(this,_name);
        };
        return function(_options){
            this.__supReset(_options);
            _u._$forEach(
                this.__nevt,_doAddEvent,this
            );
        };
    })();
    /**
     * 控件销毁
     * @return {Void}
     */
    _proPlayer.__destroy = (function(){
        var _doDelEvent = function(_name){
            delete _player['on'+_name];
        };
        return function(){
            this.__supDestroy();
            _u._$forEach(
                this.__nevt,_doDelEvent
            );
        };
    })();
    /**
     * 播放音乐
     * @param  {Object} 音乐信息
     * @return {Void}
     */
    _proPlayer._$play = function(_options){
        _n._$exec('player.load',_options);
        _n._$exec('player.setCover',_options.songId,'album');
        this._$dispatchEvent('onstatechange',{
            state:0
        });
    };
    /**
     * 恢复状态
     * @return {Void}
     */
    _proPlayer._$resume = function(){
        _n._$exec('player.play');
    };
    /**
     * 暂停播放
     * @return {Void}
     */
    _proPlayer._$pause = function(){
        _n._$exec('player.pause');
    };
    /**
     * 停止播放
     * @return {Void}
     */
    _proPlayer._$stop = function(){
        _n._$exec('player.stop');
    };
    /**
     * 设置静音
     * @param  {Boolean} 静音，true-静音，false-非静音
     * @return {Void}
     */
    _proPlayer._$setMute = function(_mute){
        _n._$exec('player.mute',!!_mute);
        this._$dispatchEvent('onmutechange',{
            mute:!!_mute
        });
    };
    /**
     * 设置模式
     * @param  {String} 播放模式
     * @return {Void}
     */
    _proPlayer._$setMode = function(_mode){
        _n._$exec('player.setPlayMode',_mode);
        this.__onNativeEvent('playmode',_mode);
    };
    /**
     * 设置音量
     * @param  {Float} 音量，范围：[0.0,1.0]
     * @return {Void}
     */
    _proPlayer._$setVolume = function(_volume){
        _n._$exec('player.setVolume',_volume);
    };
    /**
     * 设置播放位置
     * @param  {Float} 播放位置，百分比
     * @return {Void}
     */
    _proPlayer._$setPosition = function(_ratio){
        _n._$exec('player.setCurrentTime',_ratio*(_player.duration||0));
    };
    /**
     * 设置歌词
     * @param  {String} 歌词内容
     * @return {Void}
     */
    _proPlayer._$setLRC = function(_lrc){
        _n._$exec(!_lrc?'player.setLRCEmpty':'player.setLRC',_lrc||'');
    };
    /**
     * native事件回调
     * @param  {String} 事件名称
     * @return {Void}
     */
    _proPlayer.__onNativeEvent = function(_name){
        switch(_name){
            case 'dataloaded':
                this._$resume();
            return;
            case 'play':
                this._$dispatchEvent('onstatechange',{
                    state:1
                });
            return;
            case 'pause':
                this._$dispatchEvent('onstatechange',{
                    state:2
                });
            return;
            case 'ended':
                this._$dispatchEvent('onstatechange',{
                    state:4
                });
            return;
            case 'timeupdate':
                this._$dispatchEvent('onpositionchange',{
                    current:_n._$exec('player.getCurrentTime')||0,
                    duration:_player.duration||0
                });
            return;
            case 'volumechange':
                this._$dispatchEvent('onvolumechange',{
                    volume:_n._$exec('player.getVolume')
                });
            return;
            case 'error':
                this._$dispatchEvent('onstatechange',{
                    state:5
                });
            return;
            case 'notify':

            return;
            case 'playpre':
            case 'playnext':
                this._$dispatchEvent('ontrackchange',{
                    flag:_name=='playpre'?-1:1
                });
            return;
            case 'playmode':
                this._$dispatchEvent('onmodechange',{
                    mode:arguments[1]
                });
            return;
            case 'lyricsupdate':
                this._$dispatchEvent('onlrcupdate',{
                    id:arguments[1],lrc:arguments[2]
                });
            return;
        }
    };
};
NEJ.define('{lib}native/cef/util/player.js',
          ['{lib}util/event.js'
          ,'{lib}native/command.js'],f);<commit_msg>cef player<commit_after>/**
 * ------------------------------------------
 * 播放器控件实现文件
 * @version  1.0
 * @author   genify(caijf@corp.netease.com)
 * ------------------------------------------
 */
var f = function() {
    // variable declaration
    var _  = NEJ.P,
        _e = _('nej.e'),
        _u = _('nej.u'),
        _t = _('nej.ut'),
        _n = _('nej.n'),
        _p = _('nej.cef.ut'),
        _player = _('window.player'),
        _proPlayer;
    /**
     * 播放器控件，单例模式使用
     *
     * @singleton
     * @class   {nej.cef.ut._$$Player}
     * @extends {nej.ut._$$Event}
     * @param   {Object} 配置参数
     *
     * [hr]
     * 播放状态变化触发事件，播放状态值说明
     * [ntb]
     *   状态值  |  说明
     *   ------------------
     *   0    |  缓冲阶段
     *   1    |  播放状态
     *   2    |  暂停状态
     *   3    |  停止状态
     *   4    |  播放至结尾
     *   5    |  播放异常
     * [/ntb]
     * @event  {onstatechange}
     * @param  {Object} 状态信息
     * @config {Number} state 状态值，见说明表
     *
     * [hr]
     * 播放位置变化触发事件
     * @event  {onpositionchange}
     * @param  {Object} 播放信息
     * @config {Float} current  当前位置
     * @config {Float} duration 音乐总时长
     *
     * [hr]
     * 音量变化触发事件
     * @event  {onvolumechange}
     * @param  {Object} 音量信息
     * @config {Float}  volume 当前音量值，0.0-1.0
     *
     * [hr]
     * 静音状态变化触发事件
     * @event  {onmutechange}
     * @param  {Object}  静音状态信息
     * @config {Boolean} mute 静音状态，true-静音，false-非静音
     *
     * [hr]
     * 歌曲变化触发事件
     * @event  {ontrackchange}
     * @param  {Object}  静音状态信息
     * @config {Boolean} flag 变化标识，-1-上一首，1-下一首
     *
     * [hr]
     * 播放模式变化触发事件，模式说明
     * [ntb]
     *   名称                       |  说明
     *   -----------------------
     *   playorder  |  顺序播放
     *   playcycle  |  循环播放
     *   playrandom |  随机播放
     * [/ntb]
     * @event  {onmodechange}
     * @param  {Object}  静音状态信息
     * @config {Boolean} mode 模式，见描述
     *
     * [hr]
     * 歌词更新触发事件
     * @event  {onlrcupdate}
     * @param  {Object}  歌词信息
     * @config {String}  id  歌曲ID
     * @config {String}  lrc 歌词内容
     *
     *
     */
    _p._$$Player = NEJ.C();
      _proPlayer = _p._$$Player._$extend(_t._$$Event);
    /**
     * 控件初始化
     * @return {Void}
     */
    _proPlayer.__init = function(){
        this.__nevt = [
            'volumechange','notify',
            'dataloaded','play','pause',
            'ended',,'playmode','error','playpre',
            'playnext','timeupdate','lyricsupdate'
        ];
        this.__supInit();
    };
    /**
     * 控件重置
     * @param  {Object} 配置信息
     * @return {Void}
     */
    _proPlayer.__reset = (function(){
        // add native event
        var _doAddEvent = function(_name){
            _player['on'+_name] = this.
                __onNativeEvent._$bind(this,_name);
        };
        return function(_options){
            this.__supReset(_options);
            _u._$forEach(
                this.__nevt,_doAddEvent,this
            );
        };
    })();
    /**
     * 控件销毁
     * @return {Void}
     */
    _proPlayer.__destroy = (function(){
        var _doDelEvent = function(_name){
            delete _player['on'+_name];
        };
        return function(){
            this.__supDestroy();
            _u._$forEach(
                this.__nevt,_doDelEvent
            );
        };
    })();
    /**
     * 播放音乐
     * @param  {Object} 音乐信息
     * @return {Void}
     */
    _proPlayer._$play = function(_options){
        _n._$exec('player.load',_options);
        _n._$exec('player.setCover',''+_options.songId,'album');
        this._$dispatchEvent('onstatechange',{
            state:0
        });
    };
    /**
     * 恢复状态
     * @return {Void}
     */
    _proPlayer._$resume = function(){
        _n._$exec('player.play');
    };
    /**
     * 暂停播放
     * @return {Void}
     */
    _proPlayer._$pause = function(){
        _n._$exec('player.pause');
    };
    /**
     * 停止播放
     * @return {Void}
     */
    _proPlayer._$stop = function(){
        _n._$exec('player.stop');
    };
    /**
     * 设置静音
     * @param  {Boolean} 静音，true-静音，false-非静音
     * @return {Void}
     */
    _proPlayer._$setMute = function(_mute){
        _n._$exec('player.mute',!!_mute);
        this._$dispatchEvent('onmutechange',{
            mute:!!_mute
        });
    };
    /**
     * 设置模式
     * @param  {String} 播放模式
     * @return {Void}
     */
    _proPlayer._$setMode = function(_mode){
        _n._$exec('player.setPlayMode',_mode);
        this.__onNativeEvent('playmode',_mode);
    };
    /**
     * 设置音量
     * @param  {Float} 音量，范围：[0.0,1.0]
     * @return {Void}
     */
    _proPlayer._$setVolume = function(_volume){
        _n._$exec('player.setVolume',_volume);
    };
    /**
     * 设置播放位置
     * @param  {Float} 播放位置，百分比
     * @return {Void}
     */
    _proPlayer._$setPosition = function(_ratio){
        _n._$exec('player.setCurrentTime',_ratio*(_player.duration||0));
    };
    /**
     * 设置歌词
     * @param  {String} 歌词内容
     * @return {Void}
     */
    _proPlayer._$setLRC = function(_lrc){
        _n._$exec(!_lrc?'player.setLRCEmpty':'player.setLRC',_lrc||'');
    };
    /**
     * native事件回调
     * @param  {String} 事件名称
     * @return {Void}
     */
    _proPlayer.__onNativeEvent = function(_name){
        switch(_name){
            case 'dataloaded':
                this._$resume();
            return;
            case 'play':
                this._$dispatchEvent('onstatechange',{
                    state:1
                });
            return;
            case 'pause':
                this._$dispatchEvent('onstatechange',{
                    state:2
                });
            return;
            case 'ended':
                this._$dispatchEvent('onstatechange',{
                    state:4
                });
            return;
            case 'timeupdate':
                this._$dispatchEvent('onpositionchange',{
                    current:_n._$exec('player.getCurrentTime')||0,
                    duration:_player.duration||0
                });
            return;
            case 'volumechange':
                this._$dispatchEvent('onvolumechange',{
                    volume:_n._$exec('player.getVolume')
                });
            return;
            case 'error':
                this._$dispatchEvent('onstatechange',{
                    state:5
                });
            return;
            case 'notify':

            return;
            case 'playpre':
            case 'playnext':
                this._$dispatchEvent('ontrackchange',{
                    flag:_name=='playpre'?-1:1
                });
            return;
            case 'playmode':
                this._$dispatchEvent('onmodechange',{
                    mode:arguments[1]
                });
            return;
            case 'lyricsupdate':
                this._$dispatchEvent('onlrcupdate',{
                    id:arguments[1],lrc:arguments[2]
                });
            return;
        }
    };
};
NEJ.define('{lib}native/cef/util/player.js',
          ['{lib}util/event.js'
          ,'{lib}native/command.js'],f);<|endoftext|>


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

    // Declare app level module which depends on views, and components
    angular
        .module('owh')
        .config(appConfig);
    appConfig.$inject = ['$stateProvider', '$urlRouterProvider', '$locationProvider', '$translateProvider'];

    function appConfig($stateProvider, $urlRouterProvider, $locationProvider, $translateProvider ) {

        // use the HTML5 History API
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        //TODO: move these route definitions inside of their respective modules
        //Routes
        $stateProvider.state('home', {
                url:'/',
                templateUrl: 'app/modules/home/home.html',
                controller: 'HomeController',
                controllerAs: 'hc'
        }).state('search', {
                url:'/search/:queryID',
                templateUrl: 'app/modules/search/search.html',
                controller: 'SearchController',
                controllerAs: 'sc',
                params: {primaryFilterKey: 'deaths', allFilters: null, selectedFilters: null, tableView: 'number_of_deaths', cacheQuery: false}
        }).state('description',  {
                url:'/description',
                templateUrl: 'app/modules/description/description.html',
                controller: 'DescriptionController',
                controllerAs: 'dsc'
                params: {primaryFilterKey: 'deaths', allFilters: null, selectedFilters: null, tableView: 'number_of_deaths', cacheQuery: false},
                onEnter: function () {
                    $('html, body').animate({ scrollTop: -10000 }, 100);
                }
        }).state('404',  {
                url:'/404',
                templateUrl: '404.html'
        });

        $urlRouterProvider.otherwise('/404');

        // configures staticFilesLoader
        $translateProvider.useStaticFilesLoader({
            prefix: 'app/i18n/messages-',
            suffix: '.json'
        });

        // load 'en' table on startup
        $translateProvider.preferredLanguage('en');
        $translateProvider.useSanitizeValueStrategy('sanitize');
    }
}());
<commit_msg>Description page, controller created<commit_after>(function(){
    'use strict';

    // Declare app level module which depends on views, and components
    angular
        .module('owh')
        .config(appConfig);
    appConfig.$inject = ['$stateProvider', '$urlRouterProvider', '$locationProvider', '$translateProvider'];

    function appConfig($stateProvider, $urlRouterProvider, $locationProvider, $translateProvider ) {

        // use the HTML5 History API
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        //TODO: move these route definitions inside of their respective modules
        //Routes
        $stateProvider.state('home', {
                url:'/',
                templateUrl: 'app/modules/home/home.html',
                controller: 'HomeController',
                controllerAs: 'hc'
        }).state('search', {
                url:'/search/:queryID',
                templateUrl: 'app/modules/search/search.html',
                controller: 'SearchController',
                controllerAs: 'sc',
                params: {primaryFilterKey: 'deaths', allFilters: null, selectedFilters: null, tableView: 'number_of_deaths', cacheQuery: false}
        }).state('description',  {
                url:'/description',
                templateUrl: 'app/modules/description/description.html',
                controller: 'DescriptionController',
                controllerAs: 'dsc',
                params: {primaryFilterKey: 'deaths', allFilters: null, selectedFilters: null, tableView: 'number_of_deaths', cacheQuery: false},
                onEnter: function () {
                    $('html, body').animate({ scrollTop: -10000 }, 100);
                }
        }).state('404',  {
                url:'/404',
                templateUrl: '404.html'
        });

        $urlRouterProvider.otherwise('/404');

        // configures staticFilesLoader
        $translateProvider.useStaticFilesLoader({
            prefix: 'app/i18n/messages-',
            suffix: '.json'
        });

        // load 'en' table on startup
        $translateProvider.preferredLanguage('en');
        $translateProvider.useSanitizeValueStrategy('sanitize');
    }
}());
<|endoftext|>


<commit_before>var yaml = require('js-yaml'),
  fs = require('fs'),
  path = require('path'),
  p = path.join(__dirname, '..', 'locale', 'en', 'get-involved', 'events.md'),
  buf = fs.readFileSync(p),
  lines = buf.toString().split('\n'),
  str = lines.slice(lines.indexOf('---') + 1, lines.indexOf('---', lines.indexOf('---') + 1)).join('\n'),
  store = yaml.safeLoad(str)

exports.getRegion = (region) => {
  for (const reg in store.regions) {
    if (store.regions[reg].region === region) return store.regions[reg]
  }
  const reg = { region: region }
  store.regions.push(reg)
  return reg
}

exports.removeEmpty = (dict) => {
  for (const i in dict) {
    if (!dict[i]) delete dict[i]
  }
}

exports.replace = (list, key, keyValue, value) => {
  exports.removeEmpty(value)
  for (const i = 0;i < list.length;i++) {
    if (list[i][key] === keyValue) {
      list[i] = value
      return
    }
  }
  list.push(value)
}

exports.save = () => {
  const str = ['---', yaml.dump(store), '---'].join('\n')
  fs.writeFileSync(p, str)
}

function rebalance () {
  store.regions = store.regions.slice(0, 6)
  exports.save()
}

function clearMeetups () {
  store.regions.forEach((reg) => {
    delete reg.meetups
  })
  exports.save()
}
// clearMeetups()
<commit_msg>Fix const redeclaration error<commit_after>var yaml = require('js-yaml'),
  fs = require('fs'),
  path = require('path'),
  p = path.join(__dirname, '..', 'locale', 'en', 'get-involved', 'events.md'),
  buf = fs.readFileSync(p),
  lines = buf.toString().split('\n'),
  str = lines.slice(lines.indexOf('---') + 1, lines.indexOf('---', lines.indexOf('---') + 1)).join('\n'),
  store = yaml.safeLoad(str)

exports.getRegion = (region) => {
  let reg;
  for (reg in store.regions) {
    if (store.regions[reg].region === region) return store.regions[reg]
  }
  reg = { region: region }
  store.regions.push(reg)
  return reg
}

exports.removeEmpty = (dict) => {
  for (const i in dict) {
    if (!dict[i]) delete dict[i]
  }
}

exports.replace = (list, key, keyValue, value) => {
  exports.removeEmpty(value)
  for (let i = 0;i < list.length;i++) {
    if (list[i][key] === keyValue) {
      list[i] = value
      return
    }
  }
  list.push(value)
}

exports.save = () => {
  const str = ['---', yaml.dump(store), '---'].join('\n')
  fs.writeFileSync(p, str)
}

function rebalance () {
  store.regions = store.regions.slice(0, 6)
  exports.save()
}

function clearMeetups () {
  store.regions.forEach((reg) => {
    delete reg.meetups
  })
  exports.save()
}
// clearMeetups()
<|endoftext|>


<commit_before>#!/usr/bin/env node

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

var shell = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    ROOT  = path.join(__dirname, '..', '..');

// Get valid target from framework/project.properties
module.exports.get_target = function() {
    if(fs.existsSync(path.join(ROOT, 'framework', 'project.properties'))) {
        var target = shell.grep(/target=android-[\d+]/, path.join(ROOT, 'framework', 'project.properties'));
        return target.split('=')[1].replace('\n', '').replace('\r', '').replace(' ', '');
    } else if (fs.existsSync(path.join(ROOT, 'project.properties'))) {
        // if no target found, we're probably in a project and project.properties is in ROOT.
        // this is called on the project itself, and can support Google APIs AND Vanilla Android
        var target = shell.grep(/target=android-[\d+]/, path.join(ROOT, 'project.properties')) ||
          shell.grep(/target=Google Inc.:Google APIs:[\d+]/, path.join(ROOT, 'project.properties'));
        return target.split('=')[1].replace('\n', '').replace('\r', '');
    }
}

// Returns a promise.
module.exports.check_ant = function() {
    var d = Q.defer();
    child_process.exec('ant -version', function(err, stdout, stderr) {
        if (err) d.reject(new Error('ERROR : executing command \'ant\', make sure you have ant installed and added to your path.'));
        else d.resolve();
    });
    return d.promise;
}

// Returns a promise.
module.exports.check_java = function() {
    var d = Q.defer();
    child_process.exec('java -version', function(err, stdout, stderr) {
        if(err) {
            var msg =
                'Failed to run \'java -version\', make sure your java environment is set up\n' +
                'including JDK and JRE.\n' +
                'Your JAVA_HOME variable is ' + process.env.JAVA_HOME + '\n';
            d.reject(new Error(msg + err));
        }
        else d.resolve();
    });
    return d.promise;
}

// Returns a promise.
module.exports.check_android = function() {
    var valid_target = this.get_target();
    var d = Q.defer();
    child_process.exec('android list targets', function(err, stdout, stderr) {
        if (err) d.reject(stderr);
        else d.resolve(stdout);
    });

    return d.promise.then(function(output) {
        if (!output.match(valid_target)) {
            return Q.reject(new Error('Please install Android target ' + valid_target.split('-')[1] + ' (the Android newest SDK). Make sure you have the latest Android tools installed as well. Run \"android\" from your command-line to install/update any missing SDKs or tools.'));
        } else {
            var awv_interface_expected_path=path.join(ROOT, 'framework','libs');
            if (!fs.existsSync(path.join(awv_interface_expected_path,awv_interface))) {
                return Q.reject(new Error('awv_interface.jar not found in ' + awv_interface_expected_path +' folder. \nPlease download the AmazonWebView SDK from http://developer.amazon.com/sdk/fire/IntegratingAWV.html#installawv and copy the awv_interface.jar file to this folder:' + awv_interface_expected_path + ' and re-run cordova platform add amazon-fireos command.'));
                }
        }
        return Q();
    }, function(stderr) {
        if (stderr.match(/command\snot\sfound/)) {
            return Q.reject(new Error('The command \"android\" failed. Make sure you have the latest Android SDK installed, and the \"android\" command (inside the tools/ folder) is added to your path.'));
        } else {
            return Q.reject(new Error('An error occurred while listing Android targets'));
        }
    });
}

// Returns a promise.
module.exports.run = function() {
    return Q.all([this.check_ant(), this.check_java(), this.check_android()]);
}
<commit_msg>[CB-6392]Addig amazon-fireos platform fails with not so good error reporting Fixes 2 issues while adding amazon-fireos platform after fresh cordova install. 1. create.js updated to create "libs" folder before copying it to the project's platform folder. Also, checking for awv_interface.jar existance is moved to create_project(). 2. check_reqs.js no longer checks for awv_interface.jar.<commit_after>#!/usr/bin/env node

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

var shell = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    ROOT  = path.join(__dirname, '..', '..');

// Get valid target from framework/project.properties
module.exports.get_target = function() {
    if(fs.existsSync(path.join(ROOT, 'framework', 'project.properties'))) {
        var target = shell.grep(/target=android-[\d+]/, path.join(ROOT, 'framework', 'project.properties'));
        return target.split('=')[1].replace('\n', '').replace('\r', '').replace(' ', '');
    } else if (fs.existsSync(path.join(ROOT, 'project.properties'))) {
        // if no target found, we're probably in a project and project.properties is in ROOT.
        // this is called on the project itself, and can support Google APIs AND Vanilla Android
        var target = shell.grep(/target=android-[\d+]/, path.join(ROOT, 'project.properties')) ||
          shell.grep(/target=Google Inc.:Google APIs:[\d+]/, path.join(ROOT, 'project.properties'));
        return target.split('=')[1].replace('\n', '').replace('\r', '');
    }
}

// Returns a promise.
module.exports.check_ant = function() {
    var d = Q.defer();
    child_process.exec('ant -version', function(err, stdout, stderr) {
        if (err) d.reject(new Error('ERROR : executing command \'ant\', make sure you have ant installed and added to your path.'));
        else d.resolve();
    });
    return d.promise;
}

// Returns a promise.
module.exports.check_java = function() {
    var d = Q.defer();
    child_process.exec('java -version', function(err, stdout, stderr) {
        if(err) {
            var msg =
                'Failed to run \'java -version\', make sure your java environment is set up\n' +
                'including JDK and JRE.\n' +
                'Your JAVA_HOME variable is ' + process.env.JAVA_HOME + '\n';
            d.reject(new Error(msg + err));
        }
        else d.resolve();
    });
    return d.promise;
}

// Returns a promise.
module.exports.check_android = function() {
    var valid_target = this.get_target();
    var d = Q.defer();
    child_process.exec('android list targets', function(err, stdout, stderr) {
        if (err) d.reject(stderr);
        else d.resolve(stdout);
    });

    return d.promise.then(function(output) {
        if (!output.match(valid_target)) {
            return Q.reject(new Error('Please install Android target ' + valid_target.split('-')[1] + ' (the Android newest SDK). Make sure you have the latest Android tools installed as well. Run \"android\" from your command-line to install/update any missing SDKs or tools.'));
        }
        return Q();
    }, function(stderr) {
        if (stderr.match(/command\snot\sfound/)) {
            return Q.reject(new Error('The command \"android\" failed. Make sure you have the latest Android SDK installed, and the \"android\" command (inside the tools/ folder) is added to your path.'));
        } else {
            return Q.reject(new Error('An error occurred while listing Android targets'));
        }
    });
}

// Returns a promise.
module.exports.run = function() {
    return Q.all([this.check_ant(), this.check_java(), this.check_android()]);
}
<|endoftext|>


<commit_before>module.exports = {
  help: {
    name: 'eval',
    desc: 'Runs a JavaScript snippet',
    usage: '<js snippet>',
    aliases: ['e']
  },

  exec: (client, msg, params) => {
    let input = params.join(' ');

    try {
      let output = eval(input.replace(/\r?\n|\r/g, ' '));

      if(typeof output != 'string') {
        output = require('util').inspect(output, { depth: 1 });
      }

      output = output.replace(client.token, '[token redacted]').replace(client.user.email, '[email redacted]');

      //msg.edit(`***\`Input\`*** \`\`\`js\n${input}\n\`\`\`\n***\`Output\`*** \`\`\`js\n${output}\n\`\`\``).catch(console.error); OLD
      msg.edit(`${msg.content}\n\`\`\`js\n${output}\n\`\`\``).catch(console.error);

    } catch (error) {
      //msg.edit(`***\`Input\`*** \`\`\`js\n${input}\n\`\`\`\n***\`Error\`*** \`\`\`js\n${error}\n\`\`\``).catch(console.error); OLD
      msg.edit(`${msg.content}\n\`\`\`js\n${error}\n\`\`\``).catch(console.error);
    }
  }
};<commit_msg>Remove commented-out code<commit_after>module.exports = {
  help: {
    name: 'eval',
    desc: 'Runs a JavaScript snippet',
    usage: '<js snippet>',
    aliases: ['e']
  },

  exec: (client, msg, params) => {
    let input = params.join(' ');

    try {
      let output = eval(input.replace(/\r?\n|\r/g, ' '));

      if(typeof output != 'string') {
        output = require('util').inspect(output, { depth: 1 });
      }

      output = output.replace(client.token, '[token redacted]').replace(client.user.email, '[email redacted]');

      msg.edit(`${msg.content}\n\`\`\`js\n${output}\n\`\`\``).catch(console.error);

    } catch (error) {
      msg.edit(`${msg.content}\n\`\`\`js\n${error}\n\`\`\``).catch(console.error);
    }
  }
};
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.

/**
 * @fileoverview cin file parser.
 * @author zork@google.com (Zach Kuznia)
 */

// Returns an array, which is [true, parsed_data] on success, or [false, error
// message] on failure. parsed_data is an object, containing metadata and data.
function parseCin(cin_input) {
  var lines = cin_input.split('\n');
  var data = {};
  var runningcmd = null;
  var cmd;
  var table_command = {keyname: 1, chardef: 1,
                       quick: 1, quickkey: 1,
                       sel1st: 1, // re-order mappings, deprecated.
                       KEYSTROKE_REMAP: 1, KEYGROUPS: 1 };

  // TODO for very old XCIN table (1.x~2.1b), there's no %chardef -- anything
  // not inside commands are chardefs.

  var failed = function(lineno, msg) {
    return [false, 'line ' + (lineno+1) + ': ' + msg];
  }

  for (var lineno in lines) {
    var line = lines[lineno];

    // Comment line start with '#'
    if (line.match(/^#/)) {
      continue;
    }

    // Command line
    var m = line.match(/^%(\w+)(?:\s+(\S+))?/);
    if (m) {
      cmd = m[1];
      var arg = m[2];
      if (table_command[cmd]) {
        if (arg == 'begin') {
          runningcmd = cmd;
          if (data[cmd] != undefined)
            return failed(lineno, 'section already exists');
          data[cmd] = {};
        } else if (arg == 'end') {
          if (!runningcmd)
            return failed(lineno, 'end before begin');
          runningcmd = null;
        } else {
          return failed(lineno, 'should be begin/end');
        }
      } else {
        if (runningcmd)
          return failed(lineno, 'previous section has no end');
        if (arg == undefined)
          arg = true;
        else if (arg == 'false')
          arg = false;
        data[cmd] = arg;
      }
    } else if (table_command[cmd]) {
      // Extra arguments
      if (!cmd) continue;
      m = line.match(/^\s*(\S+)\s+(\S+)/);
      if (m) {
        var key = m[1];
        // TODO(hungte) Don't convert if %keep_key_case is found.
        key = key.toLowerCase();
        if (data[cmd][key] == undefined)
          data[cmd][key] = '';
        data[cmd][key] += m[2];
      } else {
        // bad line, just ignore
      }
    }
  }

  if (runningcmd && runningcmd != 'chardef') // iBus tables has no "%chardef end"
    return failed(lineno, 'previous section has no end');

  // verify mandatory fields
  if (data['prompt']) {  // gcin format
    data['cname'] = data['prompt'];
  }
  var mandatory_command = [
      'ename', 'cname', 'selkey', 'keyname', 'chardef'
      ];
  for (var i in mandatory_command) {
    if (data[mandatory_command[i]] == undefined)
      return failed(-1, 'mandatory section %' + mandatory_command[i] +
                    ' missing');
  }

  // TODO(hungte) Add more module parsers.
  var module = undefined;
  if (data.EXTENSION_ID)
    module = 'CrExtInp';

  var parsed_data = {
    metadata: {
      ename: data.ename,
      cname: data.cname,
      module: module,
    },
    data: data,
  };
  console.log('parse file:', data.ename, parsed_data);

  return [true, parsed_data];
}
<commit_msg>Don't call console in cin_parser which may run in non-browser worlds.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.

/**
 * @fileoverview cin file parser.
 * @author zork@google.com (Zach Kuznia)
 */

// Returns an array, which is [true, parsed_data] on success, or [false, error
// message] on failure. parsed_data is an object, containing metadata and data.
function parseCin(cin_input) {
  var lines = cin_input.split('\n');
  var data = {};
  var runningcmd = null;
  var cmd;
  var table_command = {keyname: 1, chardef: 1,
                       quick: 1, quickkey: 1,
                       sel1st: 1, // re-order mappings, deprecated.
                       KEYSTROKE_REMAP: 1, KEYGROUPS: 1 };

  // TODO for very old XCIN table (1.x~2.1b), there's no %chardef -- anything
  // not inside commands are chardefs.

  var failed = function(lineno, msg) {
    return [false, 'line ' + (lineno+1) + ': ' + msg];
  }

  for (var lineno in lines) {
    var line = lines[lineno];

    // Comment line start with '#'
    if (line.match(/^#/)) {
      continue;
    }

    // Command line
    var m = line.match(/^%(\w+)(?:\s+(\S+))?/);
    if (m) {
      cmd = m[1];
      var arg = m[2];
      if (table_command[cmd]) {
        if (arg == 'begin') {
          runningcmd = cmd;
          if (data[cmd] != undefined)
            return failed(lineno, 'section already exists');
          data[cmd] = {};
        } else if (arg == 'end') {
          if (!runningcmd)
            return failed(lineno, 'end before begin');
          runningcmd = null;
        } else {
          return failed(lineno, 'should be begin/end');
        }
      } else {
        if (runningcmd)
          return failed(lineno, 'previous section has no end');
        if (arg == undefined)
          arg = true;
        else if (arg == 'false')
          arg = false;
        data[cmd] = arg;
      }
    } else if (table_command[cmd]) {
      // Extra arguments
      if (!cmd) continue;
      m = line.match(/^\s*(\S+)\s+(\S+)/);
      if (m) {
        var key = m[1];
        // TODO(hungte) Don't convert if %keep_key_case is found.
        key = key.toLowerCase();
        if (data[cmd][key] == undefined)
          data[cmd][key] = '';
        data[cmd][key] += m[2];
      } else {
        // bad line, just ignore
      }
    }
  }

  if (runningcmd && runningcmd != 'chardef') // iBus tables has no "%chardef end"
    return failed(lineno, 'previous section has no end');

  // verify mandatory fields
  if (data['prompt']) {  // gcin format
    data['cname'] = data['prompt'];
  }
  var mandatory_command = [
      'ename', 'cname', 'selkey', 'keyname', 'chardef'
      ];
  for (var i in mandatory_command) {
    if (data[mandatory_command[i]] == undefined)
      return failed(-1, 'mandatory section %' + mandatory_command[i] +
                    ' missing');
  }

  // TODO(hungte) Add more module parsers.
  var module = undefined;
  if (data.EXTENSION_ID)
    module = 'CrExtInp';

  var parsed_data = {
    metadata: {
      ename: data.ename,
      cname: data.cname,
      module: module,
    },
    data: data,
  };

  return [true, parsed_data];
}
<|endoftext|>


<commit_before>const semver = require('semver');
const settings = require('./Settings');
const request = require('request');

let infos;

function loadEtherpadInformations() {
  return new Promise((resolve, reject) => {
    request('https://static.etherpad.org/info.json', (er, response, body) => {
      if (er) return reject(er);

      try {
        infos = JSON.parse(body);
        return resolve(infos);
      } catch (err) {
        return reject(err);
      }
    });
  });
}

exports.getLatestVersion = function () {
  exports.needsUpdate();
  return infos.latestVersion;
};

exports.needsUpdate = function (cb) {
  loadEtherpadInformations().then((info) => {
    if (semver.gt(info.latestVersion, settings.getEpVersion())) {
      if (cb) return cb(true);
    }
  }).catch((err) => {
    console.error(`Can not perform Etherpad update check: ${err}`);
    if (cb) return cb(false);
  });
};

exports.check = function () {
  exports.needsUpdate((needsUpdate) => {
    if (needsUpdate) {
      console.warn(`Update available: Download the actual version ${infos.latestVersion}`);
    }
  });
};
<commit_msg>lint: src/node/utils/UpdateCheck.js<commit_after>'use strict';
const semver = require('semver');
const settings = require('./Settings');
const request = require('request');

let infos;

const loadEtherpadInformations = () => new Promise((resolve, reject) => {
  request('https://static.etherpad.org/info.json', (er, response, body) => {
    if (er) return reject(er);

    try {
      infos = JSON.parse(body);
      return resolve(infos);
    } catch (err) {
      return reject(err);
    }
  });
});

exports.getLatestVersion = () => {
  exports.needsUpdate();
  return infos.latestVersion;
};

exports.needsUpdate = (cb) => {
  loadEtherpadInformations().then((info) => {
    if (semver.gt(info.latestVersion, settings.getEpVersion())) {
      if (cb) return cb(true);
    }
  }).catch((err) => {
    console.error(`Can not perform Etherpad update check: ${err}`);
    if (cb) return cb(false);
  });
};

exports.check = () => {
  exports.needsUpdate((needsUpdate) => {
    if (needsUpdate) {
      console.warn(`Update available: Download the actual version ${infos.latestVersion}`);
    }
  });
};
<|endoftext|>


<commit_before>const
    discord = require('discord.js'),
    config = require('../config/config.json'),
    fs = require('fs'),
    alias = require('../events/message.js').alias;

exports.run = async (bot,msg,args) => {
  const embedClass  = require('../classes/embedMessage.js');
    let = embedMessage      = new embedClass(msg)

    if (args[0]) {
        msg.delete();
        if (args[0].toLowerCase() === 'fun') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'fun') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else if (args[0].toLowerCase() === 'util') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'util') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else if (args[0].toLowerCase() === 'moderation') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'moderation') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else if (args[0].toLowerCase() === 'music') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'music') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else {
            try {
                let
                    cmd = require('./' + args[0]),
                    help = cmd.help,
                    usage = config.PREFIX + args[0] + ' ' + help.usage,
                    detail = help.detail,
                    alias3 = help.alias.join(', '),
                    embed = new discord.RichEmbed()
                        .setTitle('Command Information | ' + args[0])
                        .setDescription(detail)
                        .addField('Usage', usage)
                        .addField('Alias', alias3 ? alias3 : 'None')
                        .setTimestamp()
                        .setFooter(bot.user.username);
                msg.channel.send({embed});
            } catch (err) {
                if (alias[args[0]]) {
                    let cmd = require('./' + alias[args[0]] + '.js'),
                        help = cmd.help,
                        usage = config.PREFIX + alias[args[0]] + ' ' + help.usage,
                        detail = help.detail,
                        alias2 = help.alias.join(', '),
                        embed = new discord.RichEmbed()
                            .setTitle('Command Information | ' + alias[args[0]])
                            .setDescription(detail)
                            .addField('Usage', usage)
                            .addField('Alias', alias2 ? alias2 : 'None')
                            .setTimestamp()
                            .setFooter(bot.user.username);
                    msg.channel.send({embed});
                }
                else {
                    msg.channel.send(`:x: ${config.PREFIX}${args[0]} is no command`)
                }
            }
        }
    }
    else {
        msg.delete();
        let count = 0;
        let batch = '';
        fs.readdir('./commands/', (err, files) => {
            if (err) return logger.error(err);
            files.forEach(file => {
                let help = "";
                count++;
                let
                    helpInfo = require('./' + file),
                    helpName = file.split('.')[0],
                    info = helpInfo.help,
                    description = info.description;
                if (info.category === 'fun') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                else if (info.category === 'util') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                else if (info.category === 'moderation') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                else if (info.category === 'music') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                let newBatch = batch + help;
                if (newBatch.length > (1024 - 8)) {
                    msg.channel.send({
                      embed : {
                        description : newBatch
                      }
                    });
                    batch = help;
                }
                else {
                    batch = newBatch;
                }
            });
            batch += `\nTotal Command Count: ${count}`;
            msg.channel.send({
              embed : {
                description : batch
              }
            });
        });

    }

};

exports.help = {
    category: 'util',
    usage: '[command Name]',
    description: 'shows the commands',
    detail: 'shows the commands',
    botPerm    : ['SEND_MESSAGES'],
    authorPerm : ['SEND_MESSAGES'],
    alias      : [
        'h',
        'halp'
    ]
};
<commit_msg>added perms to help<commit_after>const
    discord = require('discord.js'),
    config = require('../config/config.json'),
    fs = require('fs'),
    alias = require('../events/message.js').alias;

exports.run = async (bot,msg,args) => {
  const embedClass  = require('../classes/embedMessage.js');
    let = embedMessage      = new embedClass(msg)

    if (args[0]) {
        msg.delete();
        if (args[0].toLowerCase() === 'fun') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'fun') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else if (args[0].toLowerCase() === 'util') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'util') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else if (args[0].toLowerCase() === 'moderation') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'moderation') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else if (args[0].toLowerCase() === 'music') {
            let comm = [];
            fs.readdir('./commands/', (err,files) => {
                if (err) logger.error(err);
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'music') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`)
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend
                })
            });

        }
        else {
            try {
                let
                    cmd = require('./' + args[0]),
                    help = cmd.help,
                    usage = config.PREFIX + args[0] + ' ' + help.usage,
                    detail = help.detail,
                    alias3 = help.alias.join(', '),
                    embed = new discord.RichEmbed()
                        .setTitle('Command Information | ' + args[0])
                        .setDescription(detail)
                        .addField('Usage', usage)
                        .addField('Alias', alias3 ? alias3 : 'None')
                        .setTimestamp()
                        .setFooter(bot.user.username);
                msg.channel.send({embed});
            } catch (err) {
                if (alias[args[0]]) {
                    let cmd = require('./' + alias[args[0]] + '.js'),
                        help = cmd.help,
                        usage = config.PREFIX + alias[args[0]] + ' ' + help.usage,
                        detail = help.detail,
                        alias2 = help.alias.join(', '),
                        embed = new discord.RichEmbed()
                            .setTitle('Command Information | ' + alias[args[0]])
                            .setDescription(detail)
                            .addField('Usage', usage)
                            .addField('Alias', alias2 ? alias2 : 'None')
                            .setTimestamp()
                            .setFooter(bot.user.username);
                    msg.channel.send({embed});
                }
                else {
                    msg.channel.send(`:x: ${config.PREFIX}${args[0]} is no command`)
                }
            }
        }
    }
    else {
        msg.delete();
        let count = 0;
        let batch = '';
        fs.readdir('./commands/', (err, files) => {
            if (err) return logger.error(err);
            files.forEach(file => {
                let help = "";
                count++;
                let
                    helpInfo = require('./' + file),
                    helpName = file.split('.')[0],
                    info = helpInfo.help,
                    description = info.description;
                if (info.category === 'fun') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                else if (info.category === 'util') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                else if (info.category === 'moderation') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                else if (info.category === 'music') {
                    help += `**${config.PREFIX}${helpName}** ${description}\n`
                }
                let newBatch = batch + help;
                if (newBatch.length > (1024 - 8)) {
                    msg.channel.send({
                      embed : {
                        description : newBatch
                      }
                    });
                    batch = help;
                }
                else {
                    batch = newBatch;
                }
            });
            batch += `\nTotal Command Count: ${count}`;
            msg.channel.send({
              embed : {
                description : batch
              }
            });
        });

    }

};

exports.help = {
    category: 'util',
    usage: '[command Name]',
    description: 'shows the commands',
    detail: 'shows the commands',
    botPerm    : ['SEND_MESSAGES', "EMBED_LINKS"],
    authorPerm : ['SEND_MESSAGES'],
    alias      : [
        'h',
        'halp'
    ]
};
<|endoftext|>


<commit_before>(function ($) {
  $(document).ready(function () {
    $('.replaceSelect').find('select').each(function (index) {
			let customSelect = '

<button class="btn btn-primary dropdown dropdown-toggle" data-toggle="dropdown">' + $(this).val() + ' </button>
';

			$(this).find('option').each(function (index) {
				customSelect = customSelect + '
' + $(this).html() + '
'
				setTimeout(function () {
					$('.dropdownElement.' + index).on('click', function () {
						$(this).parents('select').val($(this).attr('value'))
						$(this).parents('select').trigger('change')
					})
				}, 500)
			})

			customSelect = customSelect + '

'
			$(this).before(customSelect)
			$(this).hide()
		})
		setTimeout(function () {
			$('li.disabled').off('click')
		}, 500)
  })
})(jQuery)
<commit_msg>fixed issues<commit_after>(function ($) {
  $(document).ready(function () {
    $('.replaceSelect').find('select').each(function (index) {
			let customSelect = '

<button class="btn btn-primary dropdown dropdown-toggle" data-toggle="dropdown">' + $(this).find('option:selected').text() + ' </button>
';

			$(this).find('option').each(function (index) {
				let temp = this
				customSelect = customSelect + '
' + $(this).html() + '
'
				setTimeout(function () {
					$('.dropdownElement.' + index).on('click', function () {
						$(temp).parents('select').val($(temp).attr('value'))
						$(temp).parents('select').trigger('change')
					})
				}, 500)
			})

			customSelect = customSelect + '

'
			$(this).before(customSelect)
			$(this).hide()
		})
		setTimeout(function () {
			$('li.disabled').off('click')
		}, 500)
  })
})(jQuery)
<|endoftext|>


<commit_before>// from jQuery: https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/ajax/parseXML.js

/**
 * Parses a string of XML data into an XML document that can be traversed.
 *
 * @param {String} data
 *
 * @returns XMLDocument
 *
 * @throws Error
 */
var parseXML = function(data){
    var xml;

    if ( !data || typeof data !== "string" ) {
        return null;
    }

    // Support: IE9
    try {
        xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
    } catch ( e ) {
        xml = undefined;
    }

    if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
        throw new Error( "Invalid XML: " + data );
    }

    return xml;
};

export default parseXML;<commit_msg>Enh. to parseXML<commit_after>// from jQuery: https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/ajax/parseXML.js

/**
 * Parses a string of XML data into an XML document that can be traversed.
 *
 * @param {String} data
 *
 * @returns XMLDocument
 *
 * @throws Error
 */
var parseXML = function(data){
    var xml;

    if (!data || typeof data !== "string") {
        return null;
    }

    // Support: IE9
    try {
        xml = (new window.DOMParser()).parseFromString(data, "text/xml");
    } catch (e) {
        xml = undefined;
    }

    var errors;
    if (!xml || (errors = xml.getElementsByTagName("parsererror")).length) {
        var err;
        try {
            err = new Error( "Invalid XML: " + errors[0].textContent);
            err.xmlData = data;
        } catch (e) {
            err = new Error("Invalid XML: " + data);
        }
        throw err;
    }

    return xml;
};

export default parseXML;<|endoftext|>


<commit_before>#!/usr/bin/env node

exports.command = {
  description: 'query your projects',
  arguments: '[term]'
};

if (require.main !== module) {
  return;
}

var chalk = require('chalk');
var program = require('commander');
var _ = require('lodash');

var storage = require('../lib/storage.js');

// TODO: Think about colors and display
var projectName = chalk.bold;

function formatStatus(project) {
  return project.status === 'active' ? chalk.green(project.status) :
    chalk.red(project.status);
}

function formatRole(project) {
  return project.role === 'creator' ? chalk.green(project.role) :
    chalk.gray(project.role);
}

function query(term) {
  var projects = storage.query({ name: { $likeI: term } },
    { sortBy: function (project) { return project.name.toLowerCase(); } });

  projects.forEach(function (project) {
    var output = _.filter([
      projectName(project.name),
      formatStatus(project),
      formatRole(project),
      project.language
    ]).join(', ');

    console.log(output);
  });
}

program._name = 'query';
program.usage('<term>');
program.parse(process.argv);

storage.setup(function () {
  query(program.args.join(' '));
});
<commit_msg>Support searching by attribute<commit_after>#!/usr/bin/env node

exports.command = {
  description: 'query your projects',
  arguments: '[term]'
};

if (require.main !== module) {
  return;
}

var chalk = require('chalk');
var program = require('commander');
var _ = require('lodash');

var storage = require('../lib/storage.js');

// TODO: Think about colors and display
var projectName = chalk.bold;

function formatStatus(project) {
  return project.status === 'active' ? chalk.green(project.status) :
    chalk.red(project.status);
}

function formatRole(project) {
  return project.role === 'creator' ? chalk.green(project.role) :
    chalk.gray(project.role);
}

function query(term) {
  var projects;

  if (term.indexOf(':') !== -1) {
    term = term.split(':');

    var attribute = term[0];
    var value = term[1];

    var predicate = {};

    predicate[attribute] = { $equal: value };

    projects = storage.query(predicate,
      { sortBy: function (project) { return project.name.toLowerCase(); } });
  } else {
    projects = storage.query({ name: { $likeI: term } },
      { sortBy: function (project) { return project.name.toLowerCase(); } });
  }

  projects.forEach(function (project) {
    var output = _.filter([
      projectName(project.name),
      formatStatus(project),
      formatRole(project),
      project.language
    ]).join(', ');

    console.log(output);
  });
}

program._name = 'query';
program.usage('<term>');
program.parse(process.argv);

storage.setup(function () {
  query(program.args.join(' '));
});
<|endoftext|>


<commit_before>'use strict';

var Command = require('../lib/command');
var api = require('../lib/api');
var requireAuth = require('../lib/requireAuth');
var chalk = require('chalk');
var Table = require('cli-table');
var _ = require('lodash');
var logger = require('../lib/logger');
var Config = require('../lib/config');

module.exports = new Command('list')
  .description('list the Firebases to which you have access')
  .before(requireAuth)
  .action(function(options) {
    var config = Config.load(options, true);

    return api.getProjects().then(function(projects) {
      var table = new Table({
        head: ['Name', 'Permissions'],
        style: {head: ['yellow']}
      });

      var out = [];
      _.forEach(projects, function(data, name) {
        var project = {
          id: name,
          permission: data.permission
        };

        var displayPermission;
        switch (data.permission) {
        case 'own':
          displayPermission = chalk.bold('Is owner');
          break;
        case 'edit':
          displayPermission = chalk.bold('Can edit');
          break;
        case 'view':
        default:
          displayPermission = 'Can view';
        }

        var displayName = name;
        if (_.get(config, 'defaults.project') === name) {
          displayName = chalk.cyan.bold(displayName + ' (current)');
        }
        out.push(project);
        table.push([
          displayName,
          displayPermission
        ]);
      });

      logger.info(table.toString());
      return out;
    });
  });
<commit_msg>Adding Project name to list<commit_after>'use strict';

var Command = require('../lib/command');
var api = require('../lib/api');
var requireAuth = require('../lib/requireAuth');
var chalk = require('chalk');
var Table = require('cli-table');
var _ = require('lodash');
var logger = require('../lib/logger');
var Config = require('../lib/config');

module.exports = new Command('list')
  .description('list the Firebases to which you have access')
  .before(requireAuth)
  .action(function(options) {
    var config = Config.load(options, true);

    return api.getProjects().then(function(projects) {
      var table = new Table({
        head: ['Name', 'ID', 'Permissions'],
        style: {head: ['yellow']}
      });

      var out = [];
      _.forEach(projects, function(data, id) {
        var project = {
          name: data.name,
          id: id,
          permission: data.permission
        };

        var displayPermission;
        switch (data.permission) {
        case 'own':
          displayPermission = chalk.bold('Is owner');
          break;
        case 'edit':
          displayPermission = chalk.bold('Can edit');
          break;
        case 'view':
        default:
          displayPermission = 'Can view';
        }

        var displayName = data.name;
        if (_.get(config, 'defaults.project') === id) {
          displayName = chalk.cyan.bold(displayName + ' (current)');
        }
        out.push(project);
        table.push([
          displayName,
          id,
          displayPermission
        ]);
      });

      logger.info(table.toString());
      return out;
    });
  });
<|endoftext|>


<commit_before>#! /usr/bin/env node

let fs = require('fs');
let path = require('path');
let read = require('fs-readdir-recursive');

require('../package.json');

let builtins = require('repl')._builtinLibs;
let deps = [];
if(fs.existsSync('package.json'))
  deps = Object.keys(JSON.parse(fs.readFileSync('package.json')).dependencies);
else
  console.warn('[warn] no package.json');

let installed = fs.readdirSync('node_modules');

//if(require.main === module)

let files = read(process.cwd()).filter(x => !x.includes('node_modules') && x.endsWith('.js'));

console.log('Output will only appear below if there is a problem.');

files.forEach(function(file){
  fs.readFile(file, function(err, data){
    if(err) console.error('can\'t read file ' + file + ':', err);
    let regex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
    let match = regex.exec(data.toString());
    while(match != null){
      let req = match[1]; // won't properly handle wonky things like require(__dirname + '../index');
      if(!builtins.includes(req) && !deps.includes(req) && !installed.includes(req)){
        if(req.includes('/') || req.includes('\\')){
          let joined = path.join(path.dirname(file), req);
          let candidates = [joined];
          if(!joined.endsWith('.js'))
            candidates = [joined, joined + '.js', joined + path.sep + 'index.js']

          if(!candidates.find(p => fs.existsSync(p)))
            console.log(file, req, 'does not exist');
        }
        else
          console.log(file, req, 'is not a dep.');
      }
      match = regex.exec(data.toString());
    }
  });
});
<commit_msg>Fixing line ending problem??<commit_after>#! /usr/bin/env node

let fs = require('fs');
let path = require('path');
let read = require('fs-readdir-recursive');

require('../package.json');

let builtins = require('repl')._builtinLibs;
let deps = [];
if(fs.existsSync('package.json'))
  deps = Object.keys(JSON.parse(fs.readFileSync('package.json')).dependencies);
else
  console.warn('[warn] no package.json');

let installed = fs.readdirSync('node_modules');

//if(require.main === module)

let files = read(process.cwd()).filter(x => !x.includes('node_modules') && x.endsWith('.js'));

console.log('Output will only appear below if there is a problem.');

files.forEach(function(file){
  fs.readFile(file, function(err, data){
    if(err) console.error('can\'t read file ' + file + ':', err);
    let regex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
    let match = regex.exec(data.toString());
    while(match != null){
      let req = match[1]; // won't properly handle wonky things like require(__dirname + '../index');
      if(!builtins.includes(req) && !deps.includes(req) && !installed.includes(req)){
        if(req.includes(path.sep)){
          let joined = path.join(path.dirname(file), req);
          let candidates = [joined];
          if(!joined.endsWith('.js'))
            candidates = [joined, joined + '.js', joined + path.sep + 'index.js']

          if(!candidates.find(p => fs.existsSync(p)))
            console.log(file, req, 'does not exist');
        }
        else
          console.log(file, req, 'is not a dep.');
      }
      match = regex.exec(data.toString());
    }
  });
});
<|endoftext|>


<commit_before>exports.run = function(msg, args) {
	msg.delete()

	require('request').get('http://smugs.safe.moe/api/v1/i/r', function (error, response, body) {
		if (!error && response.statusCode === 200) {
			try {
				JSON.parse(body)
			} catch (e) {
				msg.channel.sendMessage('**API Error**')
				return
			}
			let response = JSON.parse(body)
			msg.channel.sendFile('https://smugs.safe.moe/'+response.url, 'smug.jpg')
		}
	})
}
<commit_msg>add imageid to filename<commit_after>exports.run = function(msg, args) {
	msg.delete()

	require('request').get('http://smugs.safe.moe/api/v1/i/r', function (error, response, body) {
		if (!error && response.statusCode === 200) {
			try {
				JSON.parse(body)
			} catch (e) {
				msg.channel.sendMessage('**API Error**')
				return
			}
			let response = JSON.parse(body)
			msg.channel.sendFile('https://smugs.safe.moe/'+response.url, response.imageID + '.png')
		}
	})
}
<|endoftext|>


<commit_before>module.exports.name = 'user';

module.exports.alias = [
  'user',
  'u'
];
module.exports.isAllowed = () => {
  return true;
};

module.exports.help = '`,u [name, @mention]` Defaults to the invoked user. Note that the name search only works if the user has said something in the past 30 days. Else, @mention them.';

const Discord = require('discord.js');
const Util = require('../classes/Util.js');
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

module.exports.command = async (message, content, bot, server) => {
  let user = content == '' ? message.author : Util.searchUser(message, content, server);
  let record;
  let member;
  if (!user) {
    if (!(record = server.users[content])) {
      message.react('❓');
      return;
    }
  } else {
    record = server.users[user.id];
    member = await server.guild.fetchMember(user.id);

    if (record == undefined) { // the user hasn't sent anything in the past 30 days
      let embed = new Discord.RichEmbed();
      embed.title = `Stats for ${user.tag}`;
      embed.description = 'Hasn\'t said anything in the past 30 days';
      embed.color = Number('0x3A8EDB');
      if (member) { // ban check
        embed.setFooter('Joined ');
        embed.timestamp = member.joinedAt;
      }
      message.channel.send({embed});
      return;
    }
  }

  let chans = record.chans;
  let ignoreHidden = !server.hiddenChannels.includes(message.channel.id);

  // Most active channels
  let topCHannels = {};
  for (let ch in chans) {
    if (server.hiddenChannels.includes(ch) && ignoreHidden) continue;
    if (topCHannels[ch]) {
      topCHannels[ch] += chans[ch];
    } else {
      topCHannels[ch] = chans[ch];
    }
  }

  // Sorts the active channels
  let sortable = [];
  for (let c in topCHannels) {
    sortable.push([c, topCHannels[c]]);
  }
  sortable.sort(function(a, b) {
    return b[1] - a[1];
  });
  let topChans = '';
  for (let i = 0; i < 3 && i < sortable.length; i++) {
    let perc = (sortable[i][1] / record.thirty * 100).toFixed(1);
    let channel = server.guild.channels.get(sortable[i][0]);
    if (!channel) continue;
    topChans += '**#' + channel.name + '** : ' + perc + '%\n';
  }

  // Most active day in the last 4 weeks, excluding today.
  let d = new Date().getUTCDay() - 1; // Sunday = 0, do not count today.
  if (d == -1) d = 6;
  let dayArr = [0, 0, 0, 0, 0, 0, 0]; // Su Mo Tu We Th Fr Sa
  let daySum = 0;
  let count = 0;
  let week = 0;
  for (let i = server.today; i >= server.today - 28; i--) { // 4 weeks
    let chans = record.record[((i % 31) + 31) % 31]; // for under flows
    for (let ch in chans) {
      if (ch == 'jpn' || ch == 'eng' || ch == 'vc') continue;
      if (count < 7) week += chans[ch];
      if (count == 0) continue;
      dayArr[d] += chans[ch];
      daySum += chans[ch];
    }
    count++;
    d = ((d - 1) % 7 + 7) % 7;
  }
  let maxDayNum = 0;
  let maxDay = 0;
  for (let j = 0; j < 7; j++) {
    if (dayArr[j] > maxDayNum) {
      maxDayNum = dayArr[j];
      maxDay = j;
    }
  }

  let hours = Math.floor(record.vc / 60);
  let vcTime = `${hours ? hours + 'hr '  : ''}${record.vc % 60}min`;

  let embed = new Discord.RichEmbed();
  if (user) {
    let fire = member.roles.has('384286851260743680');
    embed.setAuthor(`${fire ? '🔥' : ''}Stats for ${user.tag}${member.nickname ? ' aka ' + member.nickname : ''}` , user.avatarURL);
    embed.color = fire ? Number('0xFF5500') : Number('0x3A8EDB');
    embed.setFooter('Joined this server');
    embed.timestamp = member.joinedAt;
  } else { // user left
    embed.setAuthor(`Stats for <@${content}>`);
    embed.color = Number('0x3A8EDB');
  }
  embed.description = 'For the last 30 days (UTC time)';
  let chanPercent = (maxDayNum / daySum * 100).toFixed(1);
  let jpnPercent = (record.jp / (record.jp + record.en) * 100).toFixed(2);
  embed.addField('Messages sent\n M | W', `${record.thirty} | ${week}`, true);
  embed.addField('Most active channels', topChans ? topChans : 'none', true);
  if (maxDayNum != 0) embed.addField('Most active day', days[maxDay] + `\n(${chanPercent}%)`, true);
  //embed.addField('Emojis used', , true);
  //embed.addField('Reacted', record.reactions, true);
  embed.addField('Japanese usage', jpnPercent + '%', true);
  if (message.author.id == bot.owner_ID) embed.addField('Time Spent in VC', vcTime , true);

  message.channel.send({embed});
};
<commit_msg>log join date<commit_after>module.exports.name = 'user';

module.exports.alias = [
  'user',
  'u'
];
module.exports.isAllowed = () => {
  return true;
};

module.exports.help = '`,u [name, @mention]` Defaults to the invoked user. Note that the name search only works if the user has said something in the past 30 days. Else, @mention them.';

const Discord = require('discord.js');
const Util = require('../classes/Util.js');
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

module.exports.command = async (message, content, bot, server) => {
  let user = content == '' ? message.author : Util.searchUser(message, content, server);
  let record;
  let member;
  if (!user) {
    if (!(record = server.users[content])) {
      message.react('❓');
      return;
    }
  } else {
    record = server.users[user.id];
    member = await server.guild.fetchMember(user.id);

    if (record == undefined) { // the user hasn't sent anything in the past 30 days
      let embed = new Discord.RichEmbed();
      embed.title = `Stats for ${user.tag}`;
      embed.description = 'Hasn\'t said anything in the past 30 days';
      embed.color = Number('0x3A8EDB');
      if (member) { // ban check
        embed.setFooter('Joined ');
        embed.timestamp = member.joinedAt;
      }
      message.channel.send({embed});
      return;
    }
  }

  let chans = record.chans;
  let ignoreHidden = !server.hiddenChannels.includes(message.channel.id);

  // Most active channels
  let topCHannels = {};
  for (let ch in chans) {
    if (server.hiddenChannels.includes(ch) && ignoreHidden) continue;
    if (topCHannels[ch]) {
      topCHannels[ch] += chans[ch];
    } else {
      topCHannels[ch] = chans[ch];
    }
  }

  // Sorts the active channels
  let sortable = [];
  for (let c in topCHannels) {
    sortable.push([c, topCHannels[c]]);
  }
  sortable.sort(function(a, b) {
    return b[1] - a[1];
  });
  let topChans = '';
  for (let i = 0; i < 3 && i < sortable.length; i++) {
    let perc = (sortable[i][1] / record.thirty * 100).toFixed(1);
    let channel = server.guild.channels.get(sortable[i][0]);
    if (!channel) continue;
    topChans += '**#' + channel.name + '** : ' + perc + '%\n';
  }

  // Most active day in the last 4 weeks, excluding today.
  let d = new Date().getUTCDay() - 1; // Sunday = 0, do not count today.
  if (d == -1) d = 6;
  let dayArr = [0, 0, 0, 0, 0, 0, 0]; // Su Mo Tu We Th Fr Sa
  let daySum = 0;
  let count = 0;
  let week = 0;
  for (let i = server.today; i >= server.today - 28; i--) { // 4 weeks
    let chans = record.record[((i % 31) + 31) % 31]; // for under flows
    for (let ch in chans) {
      if (ch == 'jpn' || ch == 'eng' || ch == 'vc') continue;
      if (count < 7) week += chans[ch];
      if (count == 0) continue;
      dayArr[d] += chans[ch];
      daySum += chans[ch];
    }
    count++;
    d = ((d - 1) % 7 + 7) % 7;
  }
  let maxDayNum = 0;
  let maxDay = 0;
  for (let j = 0; j < 7; j++) {
    if (dayArr[j] > maxDayNum) {
      maxDayNum = dayArr[j];
      maxDay = j;
    }
  }

  let hours = Math.floor(record.vc / 60);
  let vcTime = `${hours ? hours + 'hr '  : ''}${record.vc % 60}min`;

  let embed = new Discord.RichEmbed();
  if (user) {
    let fire = member.roles.has('384286851260743680');
    embed.setAuthor(`${fire ? '🔥' : ''}Stats for ${user.tag}${member.nickname ? ' aka ' + member.nickname : ''}` , user.avatarURL);
    embed.color = fire ? Number('0xFF5500') : Number('0x3A8EDB');
    embed.setFooter('Joined this server');
    embed.timestamp = member.joinedAt;
    console.log(member.joinedAt);
  } else { // user left
    embed.setAuthor(`Stats for <@${content}>`);
    embed.color = Number('0x3A8EDB');
  }
  embed.description = 'For the last 30 days (UTC time)';
  let chanPercent = (maxDayNum / daySum * 100).toFixed(1);
  let jpnPercent = (record.jp / (record.jp + record.en) * 100).toFixed(2);
  embed.addField('Messages sent\n M | W', `${record.thirty} | ${week}`, true);
  embed.addField('Most active channels', topChans ? topChans : 'none', true);
  if (maxDayNum != 0) embed.addField('Most active day', days[maxDay] + `\n(${chanPercent}%)`, true);
  //embed.addField('Emojis used', , true);
  //embed.addField('Reacted', record.reactions, true);
  embed.addField('Japanese usage', jpnPercent + '%', true);
  if (message.author.id == bot.owner_ID) embed.addField('Time Spent in VC', vcTime , true);

  message.channel.send({embed});
};
<|endoftext|>