<commit_before>const path          = require('path')
const Discord       = require('discord.js-commando')
const request       = require('request-promise')
const config        = require('./data/client.json')
const DiscordServer = require('./DiscordServer')

module.exports =
// The main Discord bot class, only one per shard.
class DiscordBot {
    constructor() {
        this.initialize();
        this.servers = {};
    }

    // Initialize the bot, hook up events, and log in.
    initialize() {
        this.bot = new Discord.Client({
            shardId: parseInt(process.env.SHARD_ID, 10),
            shardCount: parseInt(process.env.SHARD_COUNT, 10),
            apiRequestMethod: config.apiRequestMethod || 'sequential',
            disabledEvents: ['TYPING_START', 'VOICE_STATE_UPDATE', 'PRESENCE_UPDATE', 'MESSAGE_DELETE', 'MESSAGE_UPDATE'],
            owner: config.owner || '0',
            commandPrefix: config.commandPrefix || '!',
            unknownCommandResponse: false
        });

        // Set a reference to this instance inside of the client
        // for use in Commando modules. Is this bad? Probably.
        this.bot.discordBot = this;

        // Events

        // We use .bind(this) so that the context remains within
        // the class and not the event.
        this.bot.on("ready", this.ready.bind(this));
        this.bot.on("guildMemberAdd", this.guildMemberAdd.bind(this));
        if (config.loud) this.bot.on("error", (message) => console.log(message));

        // Only hook up typingStart if lockNicknames mode is enabled.
        if (config.lockNicknames) {
            this.bot.on("message", this.typingStart.bind(this));
        }

        // Register commands
        this.bot.registry
            .registerGroup('rover', 'RoVer')
            .registerDefaultTypes()
            .registerDefaultGroups()
            .registerDefaultCommands({
                ping: false,
                commandState: false,
                prefix: false,
                help: false
            })
            .registerCommandsIn(path.join(__dirname, 'commands'));

        // Login.
        this.bot.login(process.env.CLIENT_TOKEN);
    }

    // Called when the bot is ready and has logged in.
    ready() {
        console.log(`Shard ${process.env.SHARD_ID} is ready, serving ${this.bot.guilds.array().length} guilds.`);
        this.bot.user.setGame("http://eryn.io/RoVer");
    }

    // This method is called when a user starts typing, but it's used
    // for setting their nickname back to what it should be if they've
    // changed it. Only active if lockNicknames is true in config.
    async typingStart(channel, user) {
        // Don't want to do anything if this is a DM.
        if (channel.type !== "text") {
            return;
        }

        // We call verifyMember but we want to retain the cache and we
        // don't want it to post any announcements.
        await this.getServer(channel.guild.id).verifyMember(user.id, {
            announce: false,
            clearBindingsCache: false
        });
    }

    // This is called when a user joins any Discord server.
    async guildMemberAdd(member) {
        let server = await this.getServer(member.guild.id);
        let action = await server.verifyMember(member.id);

        if (action.status) {
            member.send(server.getWelcomeMessage(action));
        } else {
            member.send("Welcome! Visit the following link to verify your Roblox account: https://verify.eryn.io");
        }
    }

    // This is used to get the DiscordServer instance associated
    // with the specific guild id.
    async getServer(id) {
        if (!this.servers[id]) {
            this.servers[id] = new DiscordServer(this, id);
            await this.servers[id].loadSettings();
        }
        return this.servers[id];
    }

    // This is called by the update server when a user verifies
    // online. It updates the member in every DiscordServer they
    // are in.
    async globallyUpdateMember(id) {
        // Start off by clearing their global cache.
        DiscordServer.clearMemberCache(id);

        let firstRun = true;

        // Iterate through all of the guilds the bot is in.
        for (let guild of this.bot.guilds.array()) {
            let server = await this.getServer(guild.id);

            if (firstRun) {
                // This only runs on the first iteration. We do this so that
                // we have time to cache the user information, so it only
                // sends out the request once.

                let action = await server.verifyMember(id, {
                    // We want to clear the group rank bindings cache because
                    // this is the first iteration.
                    clearBindingsCache: true,
                    announce: false
                });

                if (!action.status && !action.nonFatal) {
                    // If there's a fatal error, don't continue with the rest.
                    break;
                } else if (server.hasCustomWelcomeMessage()) {
                    // It worked, checking if there's a custom welcome message.
                    await this.bot.fetchUser(id);

                    let member = await this.bot.guilds.get(guild.id).fetchMember(id);
                    member.send(server.getWelcomeMessage(action));
                }
            } else {
                // This is for all bit the first iteration.

                // We define an inline function and call it with the current
                // context so that we can run these commands synchronously
                // but still execute the requests all at the same time.
                (async function(){
                    let action = await server.verifyMember(id, {
                        clearBindingsCache: false,
                        announce: false
                    });

                    if (action.status && server.hasCustomWelcomeMessage()) {
                        await this.bot.fetchUser(id);

                        let member = await this.bot.guilds.get(guild.id).fetchMember(id);
                        member.send(server.getWelcomeMessage(action));
                    }
                }).apply(this);
            }
            firstRun = false;
        }
    }
}<commit_msg>Fix method calls<commit_after>const path          = require('path')
const Discord       = require('discord.js-commando')
const request       = require('request-promise')
const config        = require('./data/client.json')
const DiscordServer = require('./DiscordServer')

module.exports =
// The main Discord bot class, only one per shard.
class DiscordBot {
    constructor() {
        this.initialize();
        this.servers = {};
    }

    // Initialize the bot, hook up events, and log in.
    initialize() {
        this.bot = new Discord.Client({
            shardId: parseInt(process.env.SHARD_ID, 10),
            shardCount: parseInt(process.env.SHARD_COUNT, 10),
            apiRequestMethod: config.apiRequestMethod || 'sequential',
            disabledEvents: ['TYPING_START', 'VOICE_STATE_UPDATE', 'PRESENCE_UPDATE', 'MESSAGE_DELETE', 'MESSAGE_UPDATE'],
            owner: config.owner || '0',
            commandPrefix: config.commandPrefix || '!',
            unknownCommandResponse: false
        });

        // Set a reference to this instance inside of the client
        // for use in Commando modules. Is this bad? Probably.
        this.bot.discordBot = this;

        // Events

        // We use .bind(this) so that the context remains within
        // the class and not the event.
        this.bot.on("ready", this.ready.bind(this));
        this.bot.on("guildMemberAdd", this.guildMemberAdd.bind(this));
        if (config.loud) this.bot.on("error", (message) => console.log(message));

        // Only hook up typingStart if lockNicknames mode is enabled.
        if (config.lockNicknames) {
            this.bot.on("message", this.typingStart.bind(this));
        }

        // Register commands
        this.bot.registry
            .registerGroup('rover', 'RoVer')
            .registerDefaultTypes()
            .registerDefaultGroups()
            .registerDefaultCommands({
                ping: false,
                commandState: false,
                prefix: false,
                help: false
            })
            .registerCommandsIn(path.join(__dirname, 'commands'));

        // Login.
        this.bot.login(process.env.CLIENT_TOKEN);
    }

    // Called when the bot is ready and has logged in.
    ready() {
        console.log(`Shard ${process.env.SHARD_ID} is ready, serving ${this.bot.guilds.array().length} guilds.`);
        this.bot.user.setGame("http://eryn.io/RoVer");
    }

    // This method is called when a user starts typing, but it's used
    // for setting their nickname back to what it should be if they've
    // changed it. Only active if lockNicknames is true in config.
    async typingStart(channel, user) {
        // Don't want to do anything if this is a DM.
        if (channel.type !== "text") {
            return;
        }

        // We call verifyMember but we want to retain the cache and we
        // don't want it to post any announcements.
        let server = await this.getServer(channel.guild.id);
        let member = await this.getMember(user.id);
        await member.verify({
            announce: false,
            clearBindingsCache: false
        });
    }

    // This is called when a user joins any Discord server.
    async guildMemberAdd(member) {
        let server = await this.getServer(member.guild.id);
        let action = await (await server.getMember(member.id)).verify();

        if (action.status) {
            member.send(server.getWelcomeMessage(action));
        } else {
            member.send("Welcome! Visit the following link to verify your Roblox account: https://verify.eryn.io");
        }
    }

    // This is used to get the DiscordServer instance associated
    // with the specific guild id.
    async getServer(id) {
        if (!this.servers[id]) {
            this.servers[id] = new DiscordServer(this, id);
            await this.servers[id].loadSettings();
        }
        return this.servers[id];
    }

    // This is called by the update server when a user verifies
    // online. It updates the member in every DiscordServer they
    // are in.
    async globallyUpdateMember(id) {
        // Start off by clearing their global cache.
        DiscordServer.clearMemberCache(id);

        let firstRun = true;

        // Iterate through all of the guilds the bot is in.
        for (let guild of this.bot.guilds.array()) {
            let server = await this.getServer(guild.id);

            if (firstRun) {
                // This only runs on the first iteration. We do this so that
                // we have time to cache the user information, so it only
                // sends out the request once.

                let action = await server.verifyMember(id, {
                    // We want to clear the group rank bindings cache because
                    // this is the first iteration.
                    clearBindingsCache: true,
                    announce: false
                });

                if (!action.status && !action.nonFatal) {
                    // If there's a fatal error, don't continue with the rest.
                    break;
                } else if (server.hasCustomWelcomeMessage()) {
                    // It worked, checking if there's a custom welcome message.
                    await this.bot.fetchUser(id);

                    let member = await this.bot.guilds.get(guild.id).fetchMember(id);
                    member.send(server.getWelcomeMessage(action));
                }
            } else {
                // This is for all bit the first iteration.

                // We define an inline function and call it with the current
                // context so that we can run these commands synchronously
                // but still execute the requests all at the same time.
                (async function(){
                    let action = await (await server.getMember(id)).verify({
                        clearBindingsCache: false,
                        announce: false
                    });

                    if (action.status && server.hasCustomWelcomeMessage()) {
                        await this.bot.fetchUser(id);

                        let member = await this.bot.guilds.get(guild.id).fetchMember(id);
                        member.send(server.getWelcomeMessage(action));
                    }
                }).apply(this);
            }
            firstRun = false;
        }
    }
}<|endoftext|>


<commit_before>/*eslint no-console: 0 */
// @flow
import {exec as shellJSExec} from 'shelljs'
import chalk from 'chalk'

export default function exec(command: string, options?: Object = {}): Object {

    const dryRun = !!process.env.DRY_RUN

    options.silent = true

    console.log(chalk.green(`${dryRun ? '[DRY RUN]': 'executing'} "${command}"`))

    if (dryRun) {
        return {command, stdout: '[DRY RUN]', stderr: '[DRY RUN]'}
    }
    else {
        return shellJSExec(command, options)
    }
}
<commit_msg>modify exec() print format<commit_after>/*eslint no-console: 0 */
// @flow
import {exec as shellJSExec} from 'shelljs'
import chalk from 'chalk'

export default function exec(command: string, options?: Object = {}): Object {

    const dryRun = !!process.env.DRY_RUN

    options.silent = true

    console.log(chalk.green(`${dryRun ? '[DRY RUN]': 'executing'} ${command}`))

    if (dryRun) {
        return {command, stdout: '[DRY RUN]', stderr: '[DRY RUN]'}
    }
    else {
        return shellJSExec(command, options)
    }
}
<|endoftext|>


<commit_before>var satuan = ["nol", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan"];
var belasan = ["sepuluh", "sebelas", "dua belas", "tiga belas", "empat belas", "lima belas", "enam belas", "tujuh belas", "delapan belas", "sembilan belas"];
var puluhan = ["", "", "dua puluh", "tiga puluh", "empat puluh", "lima puluh", "enam puluh", "tujuh puluh", "delapan puluh", "sembilan puluh"];
var ribuan = ["", "ribu", "juta", "milyar", "triliyun", "kuadrilyun", "kuintiliun", "sekstiliun", "septiliun", "oktiliun", "noniliun", "desiliun"];

function terbilang(d, f) {
    var strHasil = "";
    var frac = d.toString().includes(".") ? Number(d.toString().substr(d.toString().indexOf(".") + 1)) : 0;

    if (frac != 0)
        strHasil = terbilang(frac, "koma");

    var nDigit = 0;
    var nPosisi = 0;

    var strTemp = Math.trunc(d).toString();
    for (var i = strTemp.length; i > 0; i--) {
        var tmpBuff = "";
        if (strTemp[i] !== "-") {
            nDigit = parseInt(strTemp.substr(i - 1, 1), 10);
            nPosisi = (strTemp.length - i) + 1;
            switch (nPosisi % 3) {
                case 1:
                    var bAllZeros = false;
                    if (i == 1)
                        tmpBuff = satuan[nDigit] + " ";
                    else if (strTemp.substr(i - 2, 1) == "1")
                        tmpBuff = belasan[nDigit] + " ";
                    else if (nDigit > 0)
                        tmpBuff = satuan[nDigit] + " ";
                    else {
                        bAllZeros = true;
                        if (i > 1)
                            if (strTemp.substr(i - 2, 1) != "0")
                                bAllZeros = false;
                        if (i > 2)
                            if (strTemp.substr(i - 3, 1) != "0")
                                bAllZeros = false;
                        tmpBuff = "";
                    }

                    if ((!bAllZeros) && (nPosisi > 1))
                        if ((strTemp.length == 4) && (strTemp.substr(0, 1) == "1"))
                            tmpBuff = "se" + ribuan[Math.round(nPosisi / 3)] + " ";
                        else
                            tmpBuff = tmpBuff + ribuan[Math.round(nPosisi / 3)] + " ";
                    strHasil = tmpBuff + strHasil;
                    break;
                case 2:
                    if (nDigit > 0)
                        strHasil = (puluhan[nDigit] + " " + strHasil).trim();
                    break;
                case 0:
                    if (nDigit > 0)
                        if (nDigit == 1)
                            strHasil = "seratus " + strHasil;
                        else
                            strHasil = satuan[nDigit] + " ratus " + strHasil;
                    break;
            }
        }
    }
    if (f === "koma") {
        strHasil = `${f} ${strHasil}`.trim();
    } else {
        strHasil = ` ${strHasil} ${f ? f : "rupiah"}`.trim();
    }
    if(strTemp.length>0){
        if(strTemp[0]==="-")
        {
            strHasil = `minus ${strHasil}`;
        }
    }

    strHasil = strHasil.trim().toLowerCase();
    if (strHasil.length > 0) {
        strHasil = strHasil.substr(0, 1).toUpperCase() +
            strHasil.substr(1, strHasil.length - 1);
    }

    return strHasil;
}

module.exports = terbilang;<commit_msg>update method say<commit_after>var satuan = ["nol", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan"];
var belasan = ["sepuluh", "sebelas", "dua belas", "tiga belas", "empat belas", "lima belas", "enam belas", "tujuh belas", "delapan belas", "sembilan belas"];
var puluhan = ["", "", "dua puluh", "tiga puluh", "empat puluh", "lima puluh", "enam puluh", "tujuh puluh", "delapan puluh", "sembilan puluh"];
var ribuan = ["", "ribu", "juta", "milyar", "triliyun", "kuadrilyun", "kuintiliun", "sekstiliun", "septiliun", "oktiliun", "noniliun", "desiliun"];

function terbilang(d, f) {
    var strHasil = "";
    var isNegative = Number(d) < 0;
    if (isNegative) {
        d = d * -1;
    }

    if (d.toString().indexOf(".") !== -1) {
        var a = Number(d.toFixed(4).toString().substr(d.toFixed(4).toString().indexOf(".") + 1));
        if (a !== 0) {
            strHasil = terbilangKoma(d);
        }
        d = Number(d.toFixed(4).toString().slice(0, d.toFixed(4).toString().indexOf(".")));
    }

    var nDigit = 0;
    var nPosisi = 0;

    var strTemp = Math.trunc(d).toString();
    for (var i = strTemp.length; i > 0; i--) {
        var tmpBuff = "";
        nDigit = parseInt(strTemp.substr(i - 1, 1), 10);
        nPosisi = (strTemp.length - i) + 1;
        switch (nPosisi % 3) {
            case 1:
                var bAllZeros = false;
                if (i == 1)
                    tmpBuff = satuan[nDigit] + " ";
                else if (strTemp.substr(i - 2, 1) == "1")
                    tmpBuff = belasan[nDigit] + " ";
                else if (nDigit > 0)
                    tmpBuff = satuan[nDigit] + " ";
                else {
                    bAllZeros = true;
                    if (i > 1)
                        if (strTemp.substr(i - 2, 1) != "0")
                            bAllZeros = false;
                    if (i > 2)
                        if (strTemp.substr(i - 3, 1) != "0")
                            bAllZeros = false;
                    tmpBuff = "";
                }

                if ((!bAllZeros) && (nPosisi > 1))
                    if ((strTemp.length == 4) && (strTemp.substr(0, 1) == "1"))
                        tmpBuff = "se" + ribuan[Math.round(nPosisi / 3)] + " ";
                    else
                        tmpBuff = tmpBuff + ribuan[Math.round(nPosisi / 3)] + " ";
                strHasil = tmpBuff + strHasil;
                break;
            case 2:
                if (nDigit > 0)
                    strHasil = (puluhan[nDigit] + " " + strHasil).trim();
                break;
            case 0:
                if (nDigit > 0)
                    if (nDigit == 1)
                        strHasil = "seratus " + strHasil;
                    else
                        strHasil = satuan[nDigit] + " ratus " + strHasil;
                break;
        }

    }
    if (f === "koma") {
        strHasil = `${f} ${strHasil}`.trim();
    } else {
        strHasil = ` ${strHasil} ${f ? f : "rupiah"}`.trim();
    }
    if (strTemp.length > 0) {
        if (isNegative) {
            strHasil = `minus ${strHasil}`;
        }
    }

    strHasil = strHasil.trim().toLowerCase();
    if (strHasil.length > 0) {
        strHasil = strHasil.substr(0, 1).toUpperCase() +
            strHasil.substr(1, strHasil.length - 1);
    }

    return strHasil;
}

function terbilangKoma(frac) {
    var a = frac.toString().substr(frac.toString().indexOf(".") + 1);
    var fixNumber = "";
    if (a.length > 4) {
        fixNumber = (frac.toFixed(4)).toString().substr((frac.toFixed(4)).toString().indexOf(".") + 1);
    } else {
        fixNumber = a;
    }
    var strHasil = "koma";
    for (var i = 0; i < fixNumber.length; i++) {
        var temp = Number(fixNumber[i]);
        strHasil = strHasil + " " + satuan[temp];
    }
    return strHasil;
}

module.exports = terbilang;
<|endoftext|>


<commit_before>var React = require('react');
var classNames = require('classnames');

var FilterItem = React.createClass({
    propTypes: {
        selected:  React.PropTypes.bool,
        href:      React.PropTypes.string,
        className: React.PropTypes.string,
        count:     React.PropTypes.number,
        onClick:   React.PropTypes.func
    },

    getDefaultProps: function() {
        return {
            selected: false,
            href:   '#'
        };
    },

    onClick: function(e) {
        if (!this.props.onClick) {
            return;
        }

        e.preventDefault();
        this.props.onClick();
    },

    render: function() {
        var className = classNames('filter-item', this.props.className, {
            selected: this.props.selected
        });
        var count = this.props.count;
        var inner = '';

        if (typeof count !== 'undefined') {
            inner = {count};
        }

        return (

                    {inner}
                    {this.props.children}

        );
    }
});

var FilterList = React.createClass({
    render: function() {
        return (

                {this.props.children}

        );
    }
});

module.exports = FilterList;
module.exports.Item = FilterItem;
<commit_msg>Fix href for filter lists items<commit_after>var React = require('react');
var classNames = require('classnames');

var FilterItem = React.createClass({
    propTypes: {
        selected:  React.PropTypes.bool,
        href:      React.PropTypes.string,
        className: React.PropTypes.string,
        count:     React.PropTypes.number,
        onClick:   React.PropTypes.func
    },

    getDefaultProps: function() {
        return {
            selected: false,
            href:   '#'
        };
    },

    onClick: function(e) {
        if (!this.props.onClick) {
            return;
        }

        e.preventDefault();
        this.props.onClick();
    },

    render: function() {
        var className = classNames('filter-item', this.props.className, {
            selected: this.props.selected
        });
        var count = this.props.count;
        var href  = this.props.href;
        var inner = '';

        if (typeof count !== 'undefined') {
            inner = {count};
        }

        return (

                    {inner}
                    {this.props.children}

        );
    }
});

var FilterList = React.createClass({
    render: function() {
        return (

                {this.props.children}

        );
    }
});

module.exports = FilterList;
module.exports.Item = FilterItem;
<|endoftext|>


<commit_before>// Sample Testacular configuration file, that contain pretty much all the available options
// It's used for running client tests on Travis (http://travis-ci.org/#!/vojtajina/testacular)
// Most of the options can be overriden by cli arguments (see testacular --help)

// base path, that will be used to resolve files and exclude
basePath = '..';

// list of files / patterns to load in the browser
files = [
  JASMINE,
  JASMINE_ADAPTER,
  'test/lib/jquery/jquery-1.7.2.js',
  'test/lib/jquery/jquery-ui-1.8.18.js',
  'test/lib/angular-1.0.1/angular.js',
  'test/lib/angular-1.0.1/angular-mocks.js',
  'test/lib/codemirror/codemirror.js',
  'test/lib/tinymce/tiny_mce.js',
  'test/lib/tinymce/jquery.tinymce.js',
  'test/lib/googlemaps/googlemaps.js',
  'test/lib/bootstrap/bootstrap-modal.js',
  'test/lib/select2/select2.js',
  'test/lib/maskedinput/jquery.maskedinput-1.3.js',
  'test/lib/calendar/calendar.js.min',
  'common/module.js',
  'modules/*/*/*.js',
  'modules/*/*/test/*.js',
  'templates/*.js',
  'templates/test/*.js'
];

// list of files to exclude
exclude = [];

// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots' || 'progress'
reporter = 'dots';

// these are default values, just to show available options

// web server port
port = 8080;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_DEBUG;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;

// polling interval in ms (ignored on OS that support inotify)
autoWatchInterval = 0;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers = [];<commit_msg>Forgot to remove inputmask plugin from test-config<commit_after>// Sample Testacular configuration file, that contain pretty much all the available options
// It's used for running client tests on Travis (http://travis-ci.org/#!/vojtajina/testacular)
// Most of the options can be overriden by cli arguments (see testacular --help)

// base path, that will be used to resolve files and exclude
basePath = '..';

// list of files / patterns to load in the browser
files = [
  JASMINE,
  JASMINE_ADAPTER,
  'test/lib/jquery/jquery-1.7.2.js',
  'test/lib/jquery/jquery-ui-1.8.18.js',
  'test/lib/angular-1.0.1/angular.js',
  'test/lib/angular-1.0.1/angular-mocks.js',
  'test/lib/codemirror/codemirror.js',
  'test/lib/tinymce/tiny_mce.js',
  'test/lib/tinymce/jquery.tinymce.js',
  'test/lib/googlemaps/googlemaps.js',
  'test/lib/bootstrap/bootstrap-modal.js',
  'test/lib/select2/select2.js',
  'test/lib/calendar/calendar.js.min',
  'common/module.js',
  'modules/*/*/*.js',
  'modules/*/*/test/*.js',
  'templates/*.js',
  'templates/test/*.js'
];

// list of files to exclude
exclude = [];

// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots' || 'progress'
reporter = 'dots';

// these are default values, just to show available options

// web server port
port = 8080;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_DEBUG;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;

// polling interval in ms (ignored on OS that support inotify)
autoWatchInterval = 0;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers = [];<|endoftext|>


<commit_before>/**
 * Created by austin on 3/31/15.
 */

"use strict";

var _ = require("lodash")

  , formatter = require("../formatter")
  , components = require("../componentDeclarations/components")
  , methods = require("../componentDeclarations/componentCompilerMethods")[components.query];

var component = components.query;

module.exports = {
  insert: function () {
    return this._wrapMethod(component, "insert", _getInsert(), arguments);
  },
  select: function () {
    return this._wrapMethod(component, "select", _getSelect(), arguments);
  },
  update: function () {
    return this._wrapMethod(component, "update", _getUpdate(), arguments);
  },
  delete: function () {
    return this._wrapMethod(component, "delete", _getDelete(), arguments);
  }
};

function _getInsert() {
  return function (values) {

    var compileOptions = {};
    if (values) {
      compileOptions.identifiers = [];
      compileOptions.values = [];
      _.each(values, function (v, k) {
        compileOptions.identifiers.push(formatter.wrapQuotes(k));
        compileOptions.values.push(v);
      });
    }
    var compiling = this.getCompiling("insert", compileOptions);

    var source = _getSource(this)
      , insertStatement = "INSERT INTO " + source + " (" + _.toArray(compiling.value.identifiers).join(",") + ") VALUES "
      , cql = insertStatement;

    cql += "(" + formatter.parameterize(compiling.value.values, this) + ")";
    if (_.has(this._single, "ifNotExists")) {
      cql += " IF NOT EXISTS";
    }
    if (_.has(this._grouped, "using")) {
      cql += " " + _compileUsing(this, this._grouped.using);
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getSelect() {
  return function () {

    var columns = []
      , argArray = _.toArray(arguments)
      , hasAggregates = _.has(this._grouped, "aggregate");
    if (!argArray.length && !hasAggregates) {
      columns.push("*");
    }
    else if (_.isArray(argArray[0])) {
      columns = argArray[0];
    }
    else {
      columns = argArray;
    }

    var compiling = this.getCompiling("select", {columns: columns});
    if (hasAggregates && compiling.value.columns.length === 1 && compiling.value.columns[0] === "*") {
      // retroactively remove "*"
      compiling.value.columns.length = 0;
    }
    var columnStatements = _.map(compiling.value.columns, function (column) {
        if (_.isObject(column)) {
          var key = Object.keys(column)[0];
          return formatter.wrapQuotes(key) + " AS " + formatter.wrapQuotes(column[key]);
        }
        else {
          if (column !== "*") {
            return formatter.wrapQuotes(column);
          }
          else {
            return column;
          }
        }
      })
      , source = _getSource(this);

    var cql = "SELECT " + columnStatements.join(",");

    if (_.has(this._grouped, "aggregate")) {
      _.each(this._grouped.aggregate, function (aggregate) {
        // TODO add.. more.. aggregates
        switch (aggregate.type) {
          case "ttl":
            var key, val;
            if (_.isObject(aggregate.val)) {
              key = Object.keys(aggregate.val)[0];
              val = aggregate.val[key];
            }
            else {
              key = aggregate.val;
            }
            cql += (columnStatements.length ? ", " : "") +
              "ttl(" + formatter.wrapQuotes(key) + ")" +
              (val ? " AS " + formatter.wrapQuotes(val) : "");
            break;
          case "writetime":
            var key, val;
            if (_.isObject(aggregate.val)) {
                key = Object.keys(aggregate.val)[0];
                val = aggregate.val[key];
            }
            else {
                key = aggregate.val;
            }
            cql += (columnStatements.length ? ", " : "") +
                "writetime(" + formatter.wrapQuotes(key) + ")" +
                (val ? " AS " + formatter.wrapQuotes(val) : "");
            break;
          case "count":
            var key, val;
            if (_.isObject(aggregate.val)) {
              key = Object.keys(aggregate.val)[0];
              val = aggregate.val[key];
            }
            else {
              key = aggregate.val;
            }
            cql += (columnStatements.length ? ", " : "") +
              "COUNT(" + (key === "*" ? "*" : formatter.wrapQuotes(key)) + ")" +
              (val ? " AS " + formatter.wrapQuotes(val) : "");
            break;
        }
      });
    }
    cql += " FROM " + source;

    if (_.has(this._grouped, "where")) {
      cql += " WHERE " + _compileWhere(this, this._grouped.where);
    }
    if (_.has(this._grouped, "orderBy")) {
      cql += " ORDER BY " + _compileOrder(this, this._grouped.orderBy);
    }
    if (_.has(this._single, "limit") && this._single.limit.type === "limit") {
      cql += " LIMIT " + formatter.parameterize(this._single.limit.limit, this);
    }
    if (_.has(this._single, "limit") && this._single.limit.type === "limitPerPartition") {
      cql += " PER PARTITION LIMIT " + formatter.parameterize(this._single.limit.limit, this);
    }
    if (_.has(this._single, "allowFiltering") && this._single.allowFiltering.allow) {
      cql += " ALLOW FILTERING";
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getUpdate() {
  return function (columnFamily) {

    var compiling = this.getCompiling("update", {
      columnFamily: columnFamily
    });

    if (compiling.value.columnFamily) {
      this._setColumnFamily(compiling.value.columnFamily);
    }

    var source = _getSource(this)
      , insertStatement = "UPDATE " + source
      , cql = insertStatement;

    if (_.has(this._grouped, "using")) {
      cql += " " + _compileUsing(this, this._grouped.using);
    }
    if (_.has(this._grouped, "set")) {
      cql += " SET " + _compileSet(this, this._grouped.set);
    }
    if (_.has(this._grouped, "where")) {
      cql += " WHERE " + _compileWhere(this, this._grouped.where);
    }
    if (_.has(this._grouped, "if")) {
      cql += " IF " + _compileIf(this, this._grouped.if);
    }
    if (_.has(this._single, "ifExists")) {
      cql += " IF EXISTS";
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getDelete() {
  return function () {

    var compiling = this.getCompiling("delete", {
      columns: _.flatten(_.toArray(arguments))
    });

    var source = _getSource(this)
      , deleteStatement = "DELETE " + _.map(compiling.value.columns, function (col) {
          return formatter.wrapQuotes(col);
        }).join(",") + " FROM " + source
      , cql = deleteStatement;

    if (_.has(this._grouped, "where")) {
      cql += " WHERE " + _compileWhere(this, this._grouped.where);
    }
    if (_.has(this._grouped, "if")) {
      cql += " IF " + _compileIf(this, this._grouped.if);
    }
    if (_.has(this._single, "ifExists")) {
      cql += " IF EXISTS";
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getSource(client) {
  return (
    client._keyspace && client._columnFamily ? [formatter.wrapQuotes(client._keyspace), formatter.wrapQuotes(client._columnFamily)].join(".") :
      (client._columnFamily ? formatter.wrapQuotes(client._columnFamily) : "")
  )
}

// helper compilers

function _compileWhere(client, whereStatements) {

  var groupedWhere = _.groupBy(whereStatements, "type");
  var cql = ""
    , relationsStart = true;
  _.each(Object.keys(groupedWhere), function (type) {
    var relations = [];
    relations.length = 0;
    _.each(groupedWhere[type], function (statement) {
      var key = statement.key;
      var value = statement.val;
      var tokenizeKey = function (value) { return 'TOKEN("' + value + '")'; };
      var tokenizeCompositeKey = function (values) { return 'TOKEN("' + values.join('", "') + '")'; };
      var tokenizeParameters = function (values) { return 'TOKEN(' + values + ')'; };
      if (type === "tokenWhere") {
        if (Array.isArray(key)) {
          key = tokenizeCompositeKey(key);
          value = tokenizeParameters(formatter.parameterize(value, client));
        } else {
          key = tokenizeKey(key);
          value = tokenizeParameters(formatter.parameterize(value, client));
        }
      }
      else if ((/\[.*\]$/).test(key)) { // test for nested columns
        var keyParts = [key.replace(/\[.*/g, ""), key.replace(/.+?(?=\[)/, "")];

        if (type !== "tokenWhere") {
            keyParts[0] = formatter.wrapQuotes(keyParts[0]);
        }

        key = keyParts.join('');
        value = formatter.parameterize(value, client);
      }
      else if (type !== "tokenWhere") {
        key = formatter.wrapQuotes(key);
        value = formatter.parameterize(value, client);
      }
      switch (statement.op.toLowerCase()) {
        case "in":
          relations.push([key, statement.op, "(" + value + ")"].join(" "));
          break;
        default:
          relations.push([key, statement.op, value].join(" "));
      }
    });

    var joinClause = " AND ";
    if (type === "orWhere")
      joinClause = " OR ";
    if (type === "whereRaw")
      joinClause = " ";

    cql += (!relationsStart ? joinClause : "") + relations.join(joinClause);
    relationsStart = false;
  });

  return cql;
}

function _compileIf(client, whereStatements) {

  var groupedIf = _.groupBy(whereStatements, "type");
  var cql = ""
    , relationsStart = true;
  _.each(Object.keys(groupedIf), function (type) {
    var relations = [];
    relations.length = 0;
    _.each(groupedIf[type], function (statement) {
      var key = statement.key;
      // test for nested columns
      if ((/\[.*\]$/).test(key)) {
        key = formatter.wrapQuotes(key.replace(/\[.*/g, "")) + key.replace(/.+?(?=\[)/, "");
      }
      else {
        key = formatter.wrapQuotes(key);
      }
      switch (statement.op.toLowerCase()) {
        case "in":
          relations.push([key, statement.op, "(" + formatter.parameterize(statement.val, client) + ")"].join(" "));
          break;
        default:
          relations.push([key, statement.op, formatter.parameterize(statement.val, client)].join(" "));
      }
    });

    var joinClause = " AND ";

    cql += (!relationsStart ? joinClause : "") + relations.join(joinClause);
    relationsStart = false;
  });

  return cql;
}

function _compileSet(client, setStatements) {

  var cql = ""
    , assignments = [];

  _.each(setStatements, function (statement) {
    var key = formatter.wrapQuotes(statement.key);
    switch (statement.type) {
      case "set":
        if (!_.isArray(statement.val)) {
          assignments.push(key + " = " + formatter.parameterize(statement.val, client));
        }
        else {
          assignments.push(key + " = " + formatter.parameterizeArray(statement.val, client));
        }
        break;
      case "add":
        assignments.push(key + " = " + key + (statement.type === "add" ? " + " : " - ") + formatter.parameterize(statement.val, client));
        break;
      case "remove":
        assignments.push(key + " = " + key + (statement.type === "add" ? " + " : " - ") + formatter.parameterizeArray(statement.val, client));
        break;
      case "increment":
      case "decrement":
        assignments.push(key + " = " + key + (statement.type === "increment" ? " + " : " - ") + formatter.parameterize(statement.val, client));
        break;
    }
  });
  cql += assignments.join(",");

  return cql;
}

function _compileUsing(client, usingStatements) {

  var cql = ""
    , using = [];

  _.each(usingStatements, function (statement) {
    var statementString = "USING ";
    if (statement.type === "usingTTL")
      statementString += "TTL ";
    if (statement.type === "usingTimestamp")
      statementString += "TIMESTAMP ";

    using.push(statementString + formatter.parameterize(statement.val, client));
  });

  cql += using.join(" AND ");

  return cql;
}

function _compileOrder(client, orderByStatements) {

  var cql = ""
    , orderBy = [];

  _.each(_.map(orderByStatements, "orderBy"), function (statement) {
    orderBy.push(formatter.wrapQuotes(statement.column) + " " + statement.order);
  });

  cql += orderBy.join(" ");

  return cql;
}<commit_msg>Code refactoring<commit_after>/**
 * Created by austin on 3/31/15.
 */

"use strict";

var _ = require("lodash")

  , formatter = require("../formatter")
  , components = require("../componentDeclarations/components")
  , methods = require("../componentDeclarations/componentCompilerMethods")[components.query];

var component = components.query;

module.exports = {
  insert: function () {
    return this._wrapMethod(component, "insert", _getInsert(), arguments);
  },
  select: function () {
    return this._wrapMethod(component, "select", _getSelect(), arguments);
  },
  update: function () {
    return this._wrapMethod(component, "update", _getUpdate(), arguments);
  },
  delete: function () {
    return this._wrapMethod(component, "delete", _getDelete(), arguments);
  }
};

function _getInsert() {
  return function (values) {

    var compileOptions = {};
    if (values) {
      compileOptions.identifiers = [];
      compileOptions.values = [];
      _.each(values, function (v, k) {
        compileOptions.identifiers.push(formatter.wrapQuotes(k));
        compileOptions.values.push(v);
      });
    }
    var compiling = this.getCompiling("insert", compileOptions);

    var source = _getSource(this)
      , insertStatement = "INSERT INTO " + source + " (" + _.toArray(compiling.value.identifiers).join(",") + ") VALUES "
      , cql = insertStatement;

    cql += "(" + formatter.parameterize(compiling.value.values, this) + ")";
    if (_.has(this._single, "ifNotExists")) {
      cql += " IF NOT EXISTS";
    }
    if (_.has(this._grouped, "using")) {
      cql += " " + _compileUsing(this, this._grouped.using);
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getSelect() {
  return function () {

    var columns = []
      , argArray = _.toArray(arguments)
      , hasAggregates = _.has(this._grouped, "aggregate");
    if (!argArray.length && !hasAggregates) {
      columns.push("*");
    }
    else if (_.isArray(argArray[0])) {
      columns = argArray[0];
    }
    else {
      columns = argArray;
    }

    var compiling = this.getCompiling("select", {columns: columns});
    if (hasAggregates && compiling.value.columns.length === 1 && compiling.value.columns[0] === "*") {
      // retroactively remove "*"
      compiling.value.columns.length = 0;
    }
    var columnStatements = _.map(compiling.value.columns, function (column) {
        if (_.isObject(column)) {
          var key = Object.keys(column)[0];
          return formatter.wrapQuotes(key) + " AS " + formatter.wrapQuotes(column[key]);
        }
        else {
          if (column !== "*") {
            return formatter.wrapQuotes(column);
          }
          else {
            return column;
          }
        }
      })
      , source = _getSource(this);

    var cql = "SELECT " + columnStatements.join(",");

    if (_.has(this._grouped, "aggregate")) {
      _.each(this._grouped.aggregate, function (aggregate) {
        // TODO add.. more.. aggregates
        switch (aggregate.type) {
          case "writetime":
          case "ttl":
            var key, val;
            if (_.isObject(aggregate.val)) {
              key = Object.keys(aggregate.val)[0];
              val = aggregate.val[key];
            }
            else {
              key = aggregate.val;
            }
            cql += (columnStatements.length ? ", " : "") +
              aggregate.type + "(" + formatter.wrapQuotes(key) + ")" +
              (val ? " AS " + formatter.wrapQuotes(val) : "");
            break;
          case "count":
            var key, val;
            if (_.isObject(aggregate.val)) {
              key = Object.keys(aggregate.val)[0];
              val = aggregate.val[key];
            }
            else {
              key = aggregate.val;
            }
            cql += (columnStatements.length ? ", " : "") +
              "COUNT(" + (key === "*" ? "*" : formatter.wrapQuotes(key)) + ")" +
              (val ? " AS " + formatter.wrapQuotes(val) : "");
            break;
        }
      });
    }
    cql += " FROM " + source;

    if (_.has(this._grouped, "where")) {
      cql += " WHERE " + _compileWhere(this, this._grouped.where);
    }
    if (_.has(this._grouped, "orderBy")) {
      cql += " ORDER BY " + _compileOrder(this, this._grouped.orderBy);
    }
    if (_.has(this._single, "limit") && this._single.limit.type === "limit") {
      cql += " LIMIT " + formatter.parameterize(this._single.limit.limit, this);
    }
    if (_.has(this._single, "limit") && this._single.limit.type === "limitPerPartition") {
      cql += " PER PARTITION LIMIT " + formatter.parameterize(this._single.limit.limit, this);
    }
    if (_.has(this._single, "allowFiltering") && this._single.allowFiltering.allow) {
      cql += " ALLOW FILTERING";
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getUpdate() {
  return function (columnFamily) {

    var compiling = this.getCompiling("update", {
      columnFamily: columnFamily
    });

    if (compiling.value.columnFamily) {
      this._setColumnFamily(compiling.value.columnFamily);
    }

    var source = _getSource(this)
      , insertStatement = "UPDATE " + source
      , cql = insertStatement;

    if (_.has(this._grouped, "using")) {
      cql += " " + _compileUsing(this, this._grouped.using);
    }
    if (_.has(this._grouped, "set")) {
      cql += " SET " + _compileSet(this, this._grouped.set);
    }
    if (_.has(this._grouped, "where")) {
      cql += " WHERE " + _compileWhere(this, this._grouped.where);
    }
    if (_.has(this._grouped, "if")) {
      cql += " IF " + _compileIf(this, this._grouped.if);
    }
    if (_.has(this._single, "ifExists")) {
      cql += " IF EXISTS";
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getDelete() {
  return function () {

    var compiling = this.getCompiling("delete", {
      columns: _.flatten(_.toArray(arguments))
    });

    var source = _getSource(this)
      , deleteStatement = "DELETE " + _.map(compiling.value.columns, function (col) {
          return formatter.wrapQuotes(col);
        }).join(",") + " FROM " + source
      , cql = deleteStatement;

    if (_.has(this._grouped, "where")) {
      cql += " WHERE " + _compileWhere(this, this._grouped.where);
    }
    if (_.has(this._grouped, "if")) {
      cql += " IF " + _compileIf(this, this._grouped.if);
    }
    if (_.has(this._single, "ifExists")) {
      cql += " IF EXISTS";
    }

    this.query({
      cql: cql + ";"
    });

    return this;
  };
}

function _getSource(client) {
  return (
    client._keyspace && client._columnFamily ? [formatter.wrapQuotes(client._keyspace), formatter.wrapQuotes(client._columnFamily)].join(".") :
      (client._columnFamily ? formatter.wrapQuotes(client._columnFamily) : "")
  )
}

// helper compilers

function _compileWhere(client, whereStatements) {

  var groupedWhere = _.groupBy(whereStatements, "type");
  var cql = ""
    , relationsStart = true;
  _.each(Object.keys(groupedWhere), function (type) {
    var relations = [];
    relations.length = 0;
    _.each(groupedWhere[type], function (statement) {
      var key = statement.key;
      var value = statement.val;
      var tokenizeKey = function (value) { return 'TOKEN("' + value + '")'; };
      var tokenizeCompositeKey = function (values) { return 'TOKEN("' + values.join('", "') + '")'; };
      var tokenizeParameters = function (values) { return 'TOKEN(' + values + ')'; };
      if (type === "tokenWhere") {
        if (Array.isArray(key)) {
          key = tokenizeCompositeKey(key);
          value = tokenizeParameters(formatter.parameterize(value, client));
        } else {
          key = tokenizeKey(key);
          value = tokenizeParameters(formatter.parameterize(value, client));
        }
      }
      else if ((/\[.*\]$/).test(key)) { // test for nested columns
        var keyParts = [key.replace(/\[.*/g, ""), key.replace(/.+?(?=\[)/, "")];

        if (type !== "tokenWhere") {
            keyParts[0] = formatter.wrapQuotes(keyParts[0]);
        }

        key = keyParts.join('');
        value = formatter.parameterize(value, client);
      }
      else if (type !== "tokenWhere") {
        key = formatter.wrapQuotes(key);
        value = formatter.parameterize(value, client);
      }
      switch (statement.op.toLowerCase()) {
        case "in":
          relations.push([key, statement.op, "(" + value + ")"].join(" "));
          break;
        default:
          relations.push([key, statement.op, value].join(" "));
      }
    });

    var joinClause = " AND ";
    if (type === "orWhere")
      joinClause = " OR ";
    if (type === "whereRaw")
      joinClause = " ";

    cql += (!relationsStart ? joinClause : "") + relations.join(joinClause);
    relationsStart = false;
  });

  return cql;
}

function _compileIf(client, whereStatements) {

  var groupedIf = _.groupBy(whereStatements, "type");
  var cql = ""
    , relationsStart = true;
  _.each(Object.keys(groupedIf), function (type) {
    var relations = [];
    relations.length = 0;
    _.each(groupedIf[type], function (statement) {
      var key = statement.key;
      // test for nested columns
      if ((/\[.*\]$/).test(key)) {
        key = formatter.wrapQuotes(key.replace(/\[.*/g, "")) + key.replace(/.+?(?=\[)/, "");
      }
      else {
        key = formatter.wrapQuotes(key);
      }
      switch (statement.op.toLowerCase()) {
        case "in":
          relations.push([key, statement.op, "(" + formatter.parameterize(statement.val, client) + ")"].join(" "));
          break;
        default:
          relations.push([key, statement.op, formatter.parameterize(statement.val, client)].join(" "));
      }
    });

    var joinClause = " AND ";

    cql += (!relationsStart ? joinClause : "") + relations.join(joinClause);
    relationsStart = false;
  });

  return cql;
}

function _compileSet(client, setStatements) {

  var cql = ""
    , assignments = [];

  _.each(setStatements, function (statement) {
    var key = formatter.wrapQuotes(statement.key);
    switch (statement.type) {
      case "set":
        if (!_.isArray(statement.val)) {
          assignments.push(key + " = " + formatter.parameterize(statement.val, client));
        }
        else {
          assignments.push(key + " = " + formatter.parameterizeArray(statement.val, client));
        }
        break;
      case "add":
        assignments.push(key + " = " + key + (statement.type === "add" ? " + " : " - ") + formatter.parameterize(statement.val, client));
        break;
      case "remove":
        assignments.push(key + " = " + key + (statement.type === "add" ? " + " : " - ") + formatter.parameterizeArray(statement.val, client));
        break;
      case "increment":
      case "decrement":
        assignments.push(key + " = " + key + (statement.type === "increment" ? " + " : " - ") + formatter.parameterize(statement.val, client));
        break;
    }
  });
  cql += assignments.join(",");

  return cql;
}

function _compileUsing(client, usingStatements) {

  var cql = ""
    , using = [];

  _.each(usingStatements, function (statement) {
    var statementString = "USING ";
    if (statement.type === "usingTTL")
      statementString += "TTL ";
    if (statement.type === "usingTimestamp")
      statementString += "TIMESTAMP ";

    using.push(statementString + formatter.parameterize(statement.val, client));
  });

  cql += using.join(" AND ");

  return cql;
}

function _compileOrder(client, orderByStatements) {

  var cql = ""
    , orderBy = [];

  _.each(_.map(orderByStatements, "orderBy"), function (statement) {
    orderBy.push(formatter.wrapQuotes(statement.column) + " " + statement.order);
  });

  cql += orderBy.join(" ");

  return cql;
}<|endoftext|>


<commit_before>/* global describe,it */

var getSlug = require('../lib/speakingurl');

describe('getSlug create', function () {
    'use strict';

    it('with symbols', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            lang: 'en',
            uric: true,
            uricNoSlash: true,
            mark: true
        });

        getSlug('Foo (♥) ; Baz=Bar')
            .should.eql('foo-(love)-;-baz=bar');

        done();
    });

    it('without options', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug();

        getSlug('Foo Bar Baz')
            .should.eql('foo-bar-baz');

        done();
    });

    it('with empty options', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({});

        getSlug('Foo Bar Baz')
            .should.eql('foo-bar-baz');

        done();
    });

    it('with maintainCase', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            maintainCase: true
        });

        getSlug('Foo Bar Baz')
            .should.eql('Foo-Bar-Baz');

        done();
    });

    it('with uric', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            uric: true
        });

        getSlug(' :80:/Foo/Bar/Baz:Foo')
            .should.eql(':80:/foo/bar/baz:foo');

        done();
    });

    it('with uricNoSlash', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            uricNoSlash: true
        });

        getSlug('Foo/ Bar= Baz')
            .should.eql('foo-bar=-baz');

        done();
    });

    it('with mark', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            mark: true
        });

        getSlug('Foo* Bar Baz')
            .should.eql('foo*-bar-baz');

        done();
    });

    it('with truncate', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            truncate: 15
        });

        getSlug('Foo* Foobar FooBarBaz')
            .should.eql('foo-foobar');

        done();
    });

    it('with separator', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            separator: '_'
        });

        getSlug('Foo* Foobar FooBarBaz')
            .should.eql('foo_foobar_foobarbaz');

        done();
    });

    it('with mark and maintainCase', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            mark: true,
            maintainCase: true
        });

        getSlug('Foo* Bar Baz')
            .should.eql('Foo*-Bar-Baz');

        done();
    });

    it('with custom chars replacement', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                '*': 'o'
            }
        });

        getSlug('xyl*ph*n')
            .should.eql('xylophon');

        done();
    });

    it('with custom chars leet replacement', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                'a': '4',
                'b': '8',
                'e': '3',
                'g': '6',
                'l': '1',
                'o': '0',
                's': '5',
                't': '7'
            },
            lang: false
        });

        getSlug('apbpepgplpopspt')
            .should.eql('4p8p3p6p1p0p5p7');
        getSlug('papbpepgplpopsptp')
            .should.eql('p4p8p3p6p1p0p5p7p');
        getSlug('qabqegqloqst')
            .should.eql('q48q36q10q57');
        getSlug('abeglost')
            .should.eql('48361057');

        done();
    });

    it('with custom chars replacement with not allowed target char', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                'o': '*'
            }
        });

        getSlug('xylophon')
            .should.eql('xyl-ph-n');

        done();
    });

    it('with custom chars replacement with allowed target char, option mark', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                'o': '*'
            },
            mark: true
        });

        getSlug('xylophon')
            .should.eql('xyl*ph*n');

        done();
    });

    it('with custom chars replacement with option mark', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                '*': 'o'
            },
            mark: true
        });

        getSlug('xyl*ph*n')
            .should.eql('xylophon');

        done();
    });

    it('with custom char to string replacement', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                '*': 'STAR',
                'q': 'qqq',
                'and': '',
                'or': ''
            }
        });

        getSlug('xyl*ph*n')
            .should.eql('xylstarphstarn');
        getSlug('quack')
            .should.eql('qqquack');
        getSlug('Foo and Bar or Baz')
            .should.eql('foo-bar-baz');

        done();
    });

    it('with custom string replacement', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                'and': 'und',
                'or': 'oder',
                '*': ' and '
            }
        });

        getSlug('bus and train')
            .should.eql('bus-und-train');
        getSlug('bus or train')
            .should.eql('bus-oder-train');
        getSlug('busandtrain')
            .should.eql('busandtrain');
        getSlug('busortrain')
            .should.eql('busortrain');
        getSlug('bus*train')
            .should.eql('bus-and-train');

        getSlug('bus and train bus and train')
            .should.eql('bus-und-train-bus-und-train');
        getSlug('bus or train bus or train')
            .should.eql('bus-oder-train-bus-oder-train');
        getSlug('busandtrain busandtrain')
            .should.eql('busandtrain-busandtrain');
        getSlug('busortrain busortrain')
            .should.eql('busortrain-busortrain');

        done();
    });

    it('with custom string replacement with option mark', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                '*': 'STAR',
                'q': 'qqq',
                'z': ''
            },
            mark: true
        });

        getSlug('xyl*ph*n')
            .should.eql('xylstarphstarn');
        getSlug('qxxx')
            .should.eql('qqqxxx');
        getSlug('xxxqxxx')
            .should.eql('xxxqqqxxx');
        getSlug('qqq')
            .should.eql('qqqqqqqqq');
        getSlug('*q*')
            .should.eql('starqqqstar');
        getSlug('zoo')
            .should.eql('oo');
        getSlug('zooz')
            .should.eql('oo');

        done();
    });

    it('with custom string replacement with option maintainCase', function (done) {

        var getSlug = require('../lib/speakingurl')

        .createSlug({
            custom: {
                '*': 'STAR',
                'q': 'qqq',
            },
            maintainCase: true
        });

        getSlug('xyl*ph*n')
            .should.eql('xylSTARphSTARn');
        getSlug('qXXX')
            .should.eql('qqqXXX');
        getSlug('qqq')
            .should.eql('qqqqqqqqq');
        getSlug('*q*')
            .should.eql('STARqqqSTAR');

        done();
    });
});
<commit_msg>beautify code after find&replace foobar<commit_after>/* global describe,it */

var getSlug = require('../lib/speakingurl');

describe('getSlug create', function () {
    'use strict';

    it('with symbols', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                lang: 'en',
                uric: true,
                uricNoSlash: true,
                mark: true
            });

        getSlug('Foo (♥) ; Baz=Bar')
            .should.eql('foo-(love)-;-baz=bar');

        done();
    });

    it('without options', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug();

        getSlug('Foo Bar Baz')
            .should.eql('foo-bar-baz');

        done();
    });

    it('with empty options', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({});

        getSlug('Foo Bar Baz')
            .should.eql('foo-bar-baz');

        done();
    });

    it('with maintainCase', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                maintainCase: true
            });

        getSlug('Foo Bar Baz')
            .should.eql('Foo-Bar-Baz');

        done();
    });

    it('with uric', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                uric: true
            });

        getSlug(' :80:/Foo/Bar/Baz:Foo')
            .should.eql(':80:/foo/bar/baz:foo');

        done();
    });

    it('with uricNoSlash', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                uricNoSlash: true
            });

        getSlug('Foo/ Bar= Baz')
            .should.eql('foo-bar=-baz');

        done();
    });

    it('with mark', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                mark: true
            });

        getSlug('Foo* Bar Baz')
            .should.eql('foo*-bar-baz');

        done();
    });

    it('with truncate', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                truncate: 15
            });

        getSlug('Foo* Foobar FooBarBaz')
            .should.eql('foo-foobar');

        done();
    });

    it('with separator', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                separator: '_'
            });

        getSlug('Foo* Foobar FooBarBaz')
            .should.eql('foo_foobar_foobarbaz');

        done();
    });

    it('with mark and maintainCase', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                mark: true,
                maintainCase: true
            });

        getSlug('Foo* Bar Baz')
            .should.eql('Foo*-Bar-Baz');

        done();
    });

    it('with custom chars replacement', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    '*': 'o'
                }
            });

        getSlug('xyl*ph*n')
            .should.eql('xylophon');

        done();
    });

    it('with custom chars leet replacement', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    'a': '4',
                    'b': '8',
                    'e': '3',
                    'g': '6',
                    'l': '1',
                    'o': '0',
                    's': '5',
                    't': '7'
                },
                lang: false
            });

        getSlug('apbpepgplpopspt')
            .should.eql('4p8p3p6p1p0p5p7');
        getSlug('papbpepgplpopsptp')
            .should.eql('p4p8p3p6p1p0p5p7p');
        getSlug('qabqegqloqst')
            .should.eql('q48q36q10q57');
        getSlug('abeglost')
            .should.eql('48361057');

        done();
    });

    it('with custom chars replacement with not allowed target char', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    'o': '*'
                }
            });

        getSlug('xylophon')
            .should.eql('xyl-ph-n');

        done();
    });

    it('with custom chars replacement with allowed target char, option mark', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    'o': '*'
                },
                mark: true
            });

        getSlug('xylophon')
            .should.eql('xyl*ph*n');

        done();
    });

    it('with custom chars replacement with option mark', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    '*': 'o'
                },
                mark: true
            });

        getSlug('xyl*ph*n')
            .should.eql('xylophon');

        done();
    });

    it('with custom char to string replacement', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    '*': 'STAR',
                    'q': 'qqq',
                    'and': '',
                    'or': ''
                }
            });

        getSlug('xyl*ph*n')
            .should.eql('xylstarphstarn');
        getSlug('quack')
            .should.eql('qqquack');
        getSlug('Foo and Bar or Baz')
            .should.eql('foo-bar-baz');

        done();
    });

    it('with custom string replacement', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    'and': 'und',
                    'or': 'oder',
                    '*': ' and '
                }
            });

        getSlug('bus and train')
            .should.eql('bus-und-train');
        getSlug('bus or train')
            .should.eql('bus-oder-train');
        getSlug('busandtrain')
            .should.eql('busandtrain');
        getSlug('busortrain')
            .should.eql('busortrain');
        getSlug('bus*train')
            .should.eql('bus-and-train');

        getSlug('bus and train bus and train')
            .should.eql('bus-und-train-bus-und-train');
        getSlug('bus or train bus or train')
            .should.eql('bus-oder-train-bus-oder-train');
        getSlug('busandtrain busandtrain')
            .should.eql('busandtrain-busandtrain');
        getSlug('busortrain busortrain')
            .should.eql('busortrain-busortrain');

        done();
    });

    it('with custom string replacement with option mark', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    '*': 'STAR',
                    'q': 'qqq',
                    'z': ''
                },
                mark: true
            });

        getSlug('xyl*ph*n')
            .should.eql('xylstarphstarn');
        getSlug('qxxx')
            .should.eql('qqqxxx');
        getSlug('xxxqxxx')
            .should.eql('xxxqqqxxx');
        getSlug('qqq')
            .should.eql('qqqqqqqqq');
        getSlug('*q*')
            .should.eql('starqqqstar');
        getSlug('zoo')
            .should.eql('oo');
        getSlug('zooz')
            .should.eql('oo');

        done();
    });

    it('with custom string replacement with option maintainCase', function (done) {

        var getSlug = require('../lib/speakingurl')
            .createSlug({
                custom: {
                    '*': 'STAR',
                    'q': 'qqq',
                },
                maintainCase: true
            });

        getSlug('xyl*ph*n')
            .should.eql('xylSTARphSTARn');
        getSlug('qXXX')
            .should.eql('qqqXXX');
        getSlug('qqq')
            .should.eql('qqqqqqqqq');
        getSlug('*q*')
            .should.eql('STARqqqSTAR');

        done();
    });
});
<|endoftext|>


<commit_before>require.paths.unshift(__dirname + '/../lib/');

Client = require('client');
EventEmitter = require('events').EventEmitter;

sys = require('sys');
assert = require('assert');
BufferList = require(__dirname+'/buffer-list')
buffers = require(__dirname + '/test-buffers');
Connection = require('connection');
var args = require(__dirname + '/cli');

process.on('uncaughtException', function(d) {
  if ('stack' in d && 'message' in d) {
    console.log("Message: " + d.message);
    console.log(d.stack);
  } else {
    console.log(d);
  }
});

assert.same = function(actual, expected) {
  for(var key in expected) {
    assert.equal(actual[key], expected[key]);
  }
};

assert.emits = function(item, eventName, callback) {
  var called = false;
  var id = setTimeout(function() {
    test("Should have called " + eventName, function() {
      assert.ok(called, "Expected '" + eventName + "' to be called.")
    });
  },20000);

  item.once(eventName, function() {
    called = true;
    clearTimeout(id);
    assert.ok(true);
    if(callback) {
      callback.apply(item, arguments);
    }
  });
};

assert.UTCDate = function(actual, year, month, day, hours, min, sec, milisecond) {
  var actualYear = actual.getUTCFullYear();
  assert.equal(actualYear, year, "expected year " + year + " but got " + actualYear);

  var actualDate = actual.getUTCDate();
  assert.equal(actualDate, day, "expected day " + day + " but got " + actualDate);

  var actualHours = actual.getUTCHours();
  assert.equal(actualHours, hours, "expected hours " + hours + " but got " + actualHours);

  var actualMin = actual.getUTCMinutes();
  assert.equal(actualMin, min, "expected min " + min + " but got " + actualMin);

  var actualSec = actual.getUTCSeconds();
  assert.equal(actualSec, sec, "expected sec " + sec + " but got " + actualSec);

  var actualMili = actual.getUTCMilliseconds();
  assert.equal(actualMili, milisecond, "expected milisecond " + milisecond + " but got " + actualMili);
};

var spit = function(actual, expected) {
  console.log("");
  console.log("actual " + sys.inspect(actual));
  console.log("expect " + sys.inspect(expected));
  console.log("");
}

assert.equalBuffers = function(actual, expected) {
  if(actual.length != expected.length) {
    spit(actual, expected)
    assert.equal(actual.length, expected.length);
  }
  for(var i = 0; i < actual.length; i++) {
    if(actual[i] != expected[i]) {
      spit(actual, expected)
    }
    assert.equal(actual[i],expected[i]);
  }
};

assert.empty = function(actual) {
  assert.length(actual, 0);
};

assert.success = function(callback) {
  return assert.calls(function(err, arg) {
    assert.isNull(err);
    callback(arg);
  })
}

assert.length = function(actual, expectedLength) {
  assert.equal(actual.length, expectedLength);
};

var expect = function(callback, timeout) {
  var executed = false;
  var id = setTimeout(function() {
    assert.ok(executed, "Expected execution of funtion to be fired");
  }, timeout || 2000)

  return function(err, queryResult) {
    clearTimeout(id);
    assert.ok(true);
    callback.apply(this, arguments)
  }
}
assert.calls = expect;

assert.isNull = function(item, message) {
  message = message || "expected " + item + " to be null";
  assert.ok(item === null, message);
};

test = function(name, action) {
  test.testCount ++;
  if(args.verbose) {
    console.log(name);
  }
  var result = action();
  if(result === false) {
    test.ignored.push(name);
    if(!args.verbose) {
      process.stdout.write('?');
    }
  }else{
    if(!args.verbose) {
      process.stdout.write('.');
    }
  }
};

//print out the filename
process.stdout.write(require('path').basename(process.argv[1]));
//print a new line since we'll be printing test names
if(args.verbose) {
  console.log();
}
test.testCount = test.testCount || 0;
test.ignored = test.ignored || [];
test.errors = test.errors || [];

process.on('exit', function() {
  console.log('');
  if(test.ignored.length || test.errors.length) {
    test.ignored.forEach(function(name) {
      console.log("Ignored: " + name);
    });
    test.errors.forEach(function(error) {
      console.log("Error: " + error.name);
    });
    console.log('');
  }
  test.errors.forEach(function(error) {
    throw error.e;
  });
});

process.on('uncaughtException', function(err) {
  console.error("\n %s", err.stack || err.toString())
  //causes xargs to abort right away
  process.exit(255);
});

var count = 0;

var Sink = function(expected, timeout, callback) {
  var defaultTimeout = 1000;
  if(typeof timeout == 'function') {
    callback = timeout;
    timeout = defaultTimeout;
  }
  timeout = timeout || defaultTimeout;
  var internalCount = 0;
  var kill = function() {
    assert.ok(false, "Did not reach expected " + expected + " with an idle timeout of " + timeout);
  }
  var killTimeout = setTimeout(kill, timeout);
  return {
    add: function(count) {
      count = count || 1;
      internalCount += count;
      clearTimeout(killTimeout)
      if(internalCount < expected) {
        killTimeout = setTimeout(kill, timeout)
      }
      else {
        assert.equal(internalCount, expected);
        callback();
      }
    }
  }
}

module.exports = {
  args: args,
  Sink: Sink,
  pg: require('index'),
  connectionString: function() {
    return "pg"+(count++)+"://"+args.user+":"+args.password+"@"+args.host+":"+args.port+"/"+args.database;
  }
};

<commit_msg>decrease emit timeout time<commit_after>require.paths.unshift(__dirname + '/../lib/');

Client = require('client');
EventEmitter = require('events').EventEmitter;

sys = require('sys');
assert = require('assert');
BufferList = require(__dirname+'/buffer-list')
buffers = require(__dirname + '/test-buffers');
Connection = require('connection');
var args = require(__dirname + '/cli');

process.on('uncaughtException', function(d) {
  if ('stack' in d && 'message' in d) {
    console.log("Message: " + d.message);
    console.log(d.stack);
  } else {
    console.log(d);
  }
});

assert.same = function(actual, expected) {
  for(var key in expected) {
    assert.equal(actual[key], expected[key]);
  }
};

assert.emits = function(item, eventName, callback) {
  var called = false;
  var id = setTimeout(function() {
    test("Should have called " + eventName, function() {
      assert.ok(called, "Expected '" + eventName + "' to be called.")
    });
  },2000);

  item.once(eventName, function() {
    called = true;
    clearTimeout(id);
    assert.ok(true);
    if(callback) {
      callback.apply(item, arguments);
    }
  });
};

assert.UTCDate = function(actual, year, month, day, hours, min, sec, milisecond) {
  var actualYear = actual.getUTCFullYear();
  assert.equal(actualYear, year, "expected year " + year + " but got " + actualYear);

  var actualDate = actual.getUTCDate();
  assert.equal(actualDate, day, "expected day " + day + " but got " + actualDate);

  var actualHours = actual.getUTCHours();
  assert.equal(actualHours, hours, "expected hours " + hours + " but got " + actualHours);

  var actualMin = actual.getUTCMinutes();
  assert.equal(actualMin, min, "expected min " + min + " but got " + actualMin);

  var actualSec = actual.getUTCSeconds();
  assert.equal(actualSec, sec, "expected sec " + sec + " but got " + actualSec);

  var actualMili = actual.getUTCMilliseconds();
  assert.equal(actualMili, milisecond, "expected milisecond " + milisecond + " but got " + actualMili);
};

var spit = function(actual, expected) {
  console.log("");
  console.log("actual " + sys.inspect(actual));
  console.log("expect " + sys.inspect(expected));
  console.log("");
}

assert.equalBuffers = function(actual, expected) {
  if(actual.length != expected.length) {
    spit(actual, expected)
    assert.equal(actual.length, expected.length);
  }
  for(var i = 0; i < actual.length; i++) {
    if(actual[i] != expected[i]) {
      spit(actual, expected)
    }
    assert.equal(actual[i],expected[i]);
  }
};

assert.empty = function(actual) {
  assert.length(actual, 0);
};

assert.success = function(callback) {
  return assert.calls(function(err, arg) {
    assert.isNull(err);
    callback(arg);
  })
}

assert.length = function(actual, expectedLength) {
  assert.equal(actual.length, expectedLength);
};

var expect = function(callback, timeout) {
  var executed = false;
  var id = setTimeout(function() {
    assert.ok(executed, "Expected execution of funtion to be fired");
  }, timeout || 2000)

  return function(err, queryResult) {
    clearTimeout(id);
    assert.ok(true);
    callback.apply(this, arguments)
  }
}
assert.calls = expect;

assert.isNull = function(item, message) {
  message = message || "expected " + item + " to be null";
  assert.ok(item === null, message);
};

test = function(name, action) {
  test.testCount ++;
  if(args.verbose) {
    console.log(name);
  }
  var result = action();
  if(result === false) {
    test.ignored.push(name);
    if(!args.verbose) {
      process.stdout.write('?');
    }
  }else{
    if(!args.verbose) {
      process.stdout.write('.');
    }
  }
};

//print out the filename
process.stdout.write(require('path').basename(process.argv[1]));
//print a new line since we'll be printing test names
if(args.verbose) {
  console.log();
}
test.testCount = test.testCount || 0;
test.ignored = test.ignored || [];
test.errors = test.errors || [];

process.on('exit', function() {
  console.log('');
  if(test.ignored.length || test.errors.length) {
    test.ignored.forEach(function(name) {
      console.log("Ignored: " + name);
    });
    test.errors.forEach(function(error) {
      console.log("Error: " + error.name);
    });
    console.log('');
  }
  test.errors.forEach(function(error) {
    throw error.e;
  });
});

process.on('uncaughtException', function(err) {
  console.error("\n %s", err.stack || err.toString())
  //causes xargs to abort right away
  process.exit(255);
});

var count = 0;

var Sink = function(expected, timeout, callback) {
  var defaultTimeout = 1000;
  if(typeof timeout == 'function') {
    callback = timeout;
    timeout = defaultTimeout;
  }
  timeout = timeout || defaultTimeout;
  var internalCount = 0;
  var kill = function() {
    assert.ok(false, "Did not reach expected " + expected + " with an idle timeout of " + timeout);
  }
  var killTimeout = setTimeout(kill, timeout);
  return {
    add: function(count) {
      count = count || 1;
      internalCount += count;
      clearTimeout(killTimeout)
      if(internalCount < expected) {
        killTimeout = setTimeout(kill, timeout)
      }
      else {
        assert.equal(internalCount, expected);
        callback();
      }
    }
  }
}

module.exports = {
  args: args,
  Sink: Sink,
  pg: require('index'),
  connectionString: function() {
    return "pg"+(count++)+"://"+args.user+":"+args.password+"@"+args.host+":"+args.port+"/"+args.database;
  }
};

<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
/*jshint expr: true*/
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');
var fs = require('fs');
var http = require('http');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

var server;
function setupHttpServer(callback) {
    //We need a function which handles requests and send response
    //Create a server
    server = http.createServer(handleHttpRequest);
    //Lets start our server
    server.listen(8080, function() {
        //Callback triggered when server is successfully listening. Hurray!
        console.log("HTTP-Server listening on: http://localhost:%s", 80);
        callback();
    });
}

var responses = [
    {
        'request': 'GET /common/basic_info',
        'response': 'ret=OK,type=aircon,reg=eu,dst=1,ver=2_6_0,pow=0,err=0,location=0,name=%4b%6c%69%6d%61%20%4a%61%6e%61,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,cpv_minor=00,led=0,en_setzone=1,mac=A408EACC91D4,adp_mode=run,en_hol=0,grp_name=%4b%69%6e%64%65%72,en_grp=1'
    },
    {
        'request': 'GET /aircon/get_model_info',
        'response': 'ret=OK,model=NOTSUPPORT,type=N,pv=0,cpv=0,mid=NA,s_fdir=1,en_scdltmr=1'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=23.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    },
    {
        'request': 'GET /aircon/get_sensor_info',
        'response': 'ret=OK,htemp=23.5,hhum=-,otemp=-,err=0,cmpfreq=0'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=25.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    },
    {
        'request': 'GET /aircon/get_sensor_info',
        'response': 'ret=OK,htemp=25.5,hhum=-,otemp=-,err=0,cmpfreq=0'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=26.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    },
    {
        'request': 'GET /aircon/get_sensor_info',
        'response': 'ret=OK,htemp=27.5,hhum=-,otemp=-,err=0,cmpfreq=0'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=27.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    }
];
var requestCount = 0;
var requestError = false;
function handleHttpRequest(request, response){
    console.log('HTTP-Server: Request: ' + request.method + ' ' + request.url);
    if (!requestError) {
        var awaited = responses.shift();
        console.log('CHECK: "' + awaited.request + '" vs. "' + request.method + ' ' + request.url + '"');
        if (awaited.request == request.method + ' ' + request.url) {
            response.end(awaited.response);
        }
        else {
            console.log('ERROR');
            requestError = true;
        }
    }
    if (requestError) {
        response.end('ret=PARAM NG');
    }
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            config.native.daikinIp = '127.0.0.1:8080';
            config.native.pollingInterval = 60;

            setup.setAdapterConfig(config.common, config.native);

            setupHttpServer(function() {
                setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
            });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(80000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    setTimeout(done, 30000);
                });
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<commit_msg>enhance testing<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
/*jshint expr: true*/
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');
var fs = require('fs');
var http = require('http');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

var server;
function setupHttpServer(callback) {
    //We need a function which handles requests and send response
    //Create a server
    server = http.createServer(handleHttpRequest);
    //Lets start our server
    server.listen(8080, function() {
        //Callback triggered when server is successfully listening. Hurray!
        console.log("HTTP-Server listening on: http://localhost:%s", 80);
        callback();
    });
}

var responses = [
    {
        'request': 'GET /common/basic_info',
        'response': 'ret=OK,type=aircon,reg=eu,dst=1,ver=2_6_0,pow=0,err=0,location=0,name=%4b%6c%69%6d%61%20%4a%61%6e%61,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,cpv_minor=00,led=0,en_setzone=1,mac=A408EACC91D4,adp_mode=run,en_hol=0,grp_name=%4b%69%6e%64%65%72,en_grp=1'
    },
    {
        'request': 'GET /aircon/get_model_info',
        'response': 'ret=OK,model=NOTSUPPORT,type=N,pv=0,cpv=0,mid=NA,s_fdir=1,en_scdltmr=1'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=23.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    },
    {
        'request': 'GET /aircon/get_sensor_info',
        'response': 'ret=OK,htemp=23.5,hhum=-,otemp=-,err=0,cmpfreq=0'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=25.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    },
    {
        'request': 'GET /aircon/get_sensor_info',
        'response': 'ret=OK,htemp=25.5,hhum=-,otemp=-,err=0,cmpfreq=0'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=26.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    },
    {
        'request': 'GET /aircon/get_sensor_info',
        'response': 'ret=OK,htemp=27.5,hhum=-,otemp=-,err=0,cmpfreq=0'
    },
    {
        'request': 'GET /aircon/get_control_info',
        'response': 'ret=OK,pow=0,mode=2,adv=,stemp=27.0,shum=0,dt1=25.0,dt2=M,dt3=23.0,dt4=27.0,dt5=27.0,dt7=25.0,dh1=AUTO,dh2=50,dh3=0,dh4=0,dh5=0,dh7=AUTO,dhh=50,b_mode=3,b_stemp=23.0,b_shum=0,alert=255,f_rate=A,f_dir=0,b_f_rate=A,b_f_dir=0,dfr1=5,dfr2=5,dfr3=A,dfr4=5,dfr5=5,dfr6=5,dfr7=5,dfrh=5,dfd1=0,dfd2=0,dfd3=0,dfd4=0,dfd5=0,dfd6=0,dfd7=0,dfdh=0'
    }
];
var requestCount = 0;
var requestError = false;
function handleHttpRequest(request, response){
    console.log('HTTP-Server: Request: ' + request.method + ' ' + request.url);
    if (!requestError) {
        var awaited = responses.shift();
        console.log('CHECK: "' + awaited.request + '" vs. "' + request.method + ' ' + request.url + '"');
        if (awaited.request == request.method + ' ' + request.url) {
            response.end(awaited.response);
        }
        else {
            console.log('ERROR');
            requestError = true;
        }
    }
    if (requestError) {
        response.end('ret=PARAM NG');
    }
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            config.native.daikinIp = '127.0.0.1:8080';
            config.native.pollingInterval = 60;

            setup.setAdapterConfig(config.common, config.native);

            setupHttpServer(function() {
                setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
            });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check values', function (done) {
        this.timeout(80000);
        checkValueOfState('sensorInfo.indoorTemperature', 23.5, function() {
            setTimeout(function() {
                checkValueOfState('sensorInfo.indoorTemperature', 25.5, function() {
                    done();
                });
            }, 70000);
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>


<commit_before>const plistParser = require('plist');
const glob = require('glob');
const xcode = require('xcode');
const path = require('path');
const fs = require('fs');

module.exports = function getProjectMetadata(projectConfig) {
  const project = xcode.project(projectConfig.ios.pbxprojPath).parseSync();

  const plistPath = path.join(
    projectConfig.ios.sourceDir,
    project.getBuildProperty('INFOPLIST_FILE').replace(/"/g, '').replace('$(SRCROOT)', '')
  );

  if (!fs.existsSync(plistPath)) {
    return false;
  }

  const plist = plistParser.parse(
    fs.readFileSync(plistPath, 'utf-8')
  );

  return {
    version: plist.CFBundleVersion,
    shortVersion: plist.CFBundleShortVersionString,
    bundleName: plist.CFBundleName,
  };
};
<commit_msg>Export plistPath as well<commit_after>const plistParser = require('plist');
const glob = require('glob');
const xcode = require('xcode');
const path = require('path');
const fs = require('fs');

module.exports = {};

module.exports.getPlistPath = function(projectConfig) {
  const project = xcode.project(projectConfig.ios.pbxprojPath).parseSync();

  const plistPath = path.join(
    projectConfig.ios.sourceDir,
    project.getBuildProperty('INFOPLIST_FILE').replace(/"/g, '').replace('$(SRCROOT)', '')
  );

  if (!fs.existsSync(plistPath)) {
    return false;
  }

  return plistPath;
};

module.exports.getProjectMetadata = function(projectConfig) {
  const plistPath = module.exports.getPlistPath(projectConfig);

  if (!plistPath) {
    return false;
  }

  const plist = plistParser.parse(
    fs.readFileSync(plistPath, 'utf-8')
  );

  return {
    version: plist.CFBundleVersion,
    shortVersion: plist.CFBundleShortVersionString,
    bundleName: plist.CFBundleName,
  };
};
<|endoftext|>