<commit_before>'use strict';
// Log class

var config    = require('./config');
var plugins;
var connection;
var outbound;
var constants = require('./constants');
var util      = require('util');
var tty       = require('tty');

var logger = exports;

logger.levels = {
    DATA:     9,
    PROTOCOL: 8,
    DEBUG:    7,
    INFO:     6,
    NOTICE:   5,
    WARN:     4,
    ERROR:    3,
    CRIT:     2,
    ALERT:    1,
    EMERG:    0,
};

for (var level in logger.levels) {
    logger['LOG' + level] = logger.levels[level];
}

logger.loglevel     = logger.LOGWARN;
logger.deferred_logs = [];

logger.colors = {
    "DATA" : "green",
    "PROTOCOL" : "green",
    "DEBUG" : "grey",
    "INFO" : "cyan",
    "NOTICE" : "blue",
    "WARN" : "red",
    "ERROR" : "red",
    "CRIT" : "red",
    "ALERT" : "red",
    "EMERG" : "red",
};

var stdout_is_tty = tty.isatty(process.stdout.fd);

logger.colorize = function (color, str) {
    if (!util.inspect.colors) { return str; }  // node util before Nov 2013
    if (!util.inspect.colors[color]) { return str; }  // unknown color
    return '\u001b[' + util.inspect.colors[color][0] + 'm' + str +
           '\u001b[' + util.inspect.colors[color][1] + 'm';
};

var loglevel = logger.LOGWARN;

var deferred_logs = [];

logger.dump_logs = function (exit) {
    while (logger.deferred_logs.length > 0) {
        var log_item = logger.deferred_logs.shift();
        var color = logger.colors[log_item.level];
        if (color && stdout_is_tty) {
            console.log(logger.colorize(color,log_item.data));
        }
        else {
            console.log(log_item.data);
        }
    }
    if (exit) {
        process.exit(1);
    }
    return true;
};

logger.log = function (level, data) {
    if (level === 'PROTOCOL') {
        data = data.replace(/\n/g, '\\n\n');
    }
    data = data.replace(/\r/g, '\\r')
               .replace(/\n$/, '');

    var item = { 'level' : level, 'data'  : data };

    // buffer until plugins are loaded
    if (!plugins || (Array.isArray(plugins.plugin_list) &&
                     !plugins.plugin_list.length)
    {
        logger.deferred_logs.push(item);
        return true;
    }

    // process buffered logs
    while (logger.deferred_logs.length > 0) {
        var log_item = logger.deferred_logs.shift();
        plugins.run_hooks('log', logger, log_item);
    }

    plugins.run_hooks('log', logger, item );
    return true;
};

logger.log_respond = function (retval, msg, data) {
    // any other return code is irrelevant
    if (retval !== constants.cont) { return false; }

    var color = logger.colors[data.level];
    if (color && stdout_is_tty) {
        console.log(logger.colorize(color,data.data));
        return true;
    }

    console.log(data.data);
    return true;
};

logger._init_loglevel = function () {
    var self = this;
    var _loglevel = config.get('loglevel', 'value', function () {
        self._init_loglevel();
    });
    if (_loglevel) {
        var loglevel_num = parseInt(_loglevel);
        if (!loglevel_num || isNaN(loglevel_num)) {
            this.log('INFO', 'loglevel: ' + _loglevel.toUpperCase());
            logger.loglevel = logger[_loglevel.toUpperCase()];
        }
        else {
            logger.loglevel = loglevel_num;
        }
        if (!logger.loglevel) {
            logger.loglevel = logger.LOGWARN;
        }
    }
};

logger.would_log = function (level) {
    if (logger.loglevel < level) { return false; }
    return true;
};

var original_console_log = console.log;

logger._init_timestamps = function () {
    var self = this;
    var _timestamps = config.get('log_timestamps', 'value', function () {
        self._init_timestamps();
    });

    if (_timestamps) {
        console.log = function() {
            var new_arguments = [new Date().toISOString()];
            for (var key in arguments) {
                new_arguments.push(arguments[key]);
            }
            original_console_log.apply(console, new_arguments);
        };
    }
    else {
        console.log = original_console_log;
    }
};

logger._init_loglevel();
logger._init_timestamps();

logger.log_if_level = function (level, key, plugin) {
    return function() {
        if (logger.loglevel < logger[key]) { return; }
        var levelstr = '[' + level + ']';
        var str = '';
        var uuidstr = '[-]';
        var pluginstr = '[' + (plugin || 'core') + ']';
        for (var i=0; i < arguments.length; i++) {
            var data = arguments[i];
            if (typeof(data) !== 'object') {
                str += data;
                continue;
            }

            // if the object is a connection, add the connection id
            if (data instanceof connection.Connection) {
                uuidstr = '[' + data.uuid;
                if (data.tran_count > 0) {
                    uuidstr += "." + data.tran_count;
                }
                uuidstr += ']';
            }
            else if (data instanceof plugins.Plugin) {
                pluginstr = '[' + data.name + ']';
            }
            else if (data instanceof outbound.HMailItem) {
                pluginstr = '[outbound]';
                if (data.todo && data.todo.uuid) {
                    uuidstr = '[' + data.todo.uuid + ']';
                }
            }
            else {
                str += util.inspect(data);
            }
        }
        logger.log(level, [levelstr, uuidstr, pluginstr, str].join(' '));
        return true;
    };
};

logger.add_log_methods = function (object, plugin) {
    if (!object) return;
    if (typeof(object) !== 'object') return;
    for (var level in logger.levels) {
        var fname = 'log' + level.toLowerCase();
        if (object[fname]) continue;  // already added
        object[fname] = logger.log_if_level(level, 'LOG'+level, plugin);
    }
};

logger.add_log_methods(logger);

// load these down here so it sees all the logger methods compiled above
plugins = require('./plugins');
connection = require('./connection');
outbound = require('./outbound');
<commit_msg>Fix test failures (again)<commit_after>'use strict';
// Log class

var config    = require('./config');
var plugins;
var connection;
var outbound;
var constants = require('./constants');
var util      = require('util');
var tty       = require('tty');

var logger = exports;

logger.levels = {
    DATA:     9,
    PROTOCOL: 8,
    DEBUG:    7,
    INFO:     6,
    NOTICE:   5,
    WARN:     4,
    ERROR:    3,
    CRIT:     2,
    ALERT:    1,
    EMERG:    0,
};

for (var level in logger.levels) {
    logger['LOG' + level] = logger.levels[level];
}

logger.loglevel     = logger.LOGWARN;
logger.deferred_logs = [];

logger.colors = {
    "DATA" : "green",
    "PROTOCOL" : "green",
    "DEBUG" : "grey",
    "INFO" : "cyan",
    "NOTICE" : "blue",
    "WARN" : "red",
    "ERROR" : "red",
    "CRIT" : "red",
    "ALERT" : "red",
    "EMERG" : "red",
};

var stdout_is_tty = tty.isatty(process.stdout.fd);

logger.colorize = function (color, str) {
    if (!util.inspect.colors) { return str; }  // node util before Nov 2013
    if (!util.inspect.colors[color]) { return str; }  // unknown color
    return '\u001b[' + util.inspect.colors[color][0] + 'm' + str +
           '\u001b[' + util.inspect.colors[color][1] + 'm';
};

var loglevel = logger.LOGWARN;

var deferred_logs = [];

logger.dump_logs = function (exit) {
    while (logger.deferred_logs.length > 0) {
        var log_item = logger.deferred_logs.shift();
        var color = logger.colors[log_item.level];
        if (color && stdout_is_tty) {
            console.log(logger.colorize(color,log_item.data));
        }
        else {
            console.log(log_item.data);
        }
    }
    if (exit) {
        process.exit(1);
    }
    return true;
};

logger.log = function (level, data) {
    if (level === 'PROTOCOL') {
        data = data.replace(/\n/g, '\\n\n');
    }
    data = data.replace(/\r/g, '\\r')
               .replace(/\n$/, '');

    var item = { 'level' : level, 'data'  : data };

    // buffer until plugins are loaded
    if (!plugins || (Array.isArray(plugins.plugin_list) &&
                     !plugins.plugin_list.length))
    {
        logger.deferred_logs.push(item);
        return true;
    }

    // process buffered logs
    while (logger.deferred_logs.length > 0) {
        var log_item = logger.deferred_logs.shift();
        plugins.run_hooks('log', logger, log_item);
    }

    plugins.run_hooks('log', logger, item );
    return true;
};

logger.log_respond = function (retval, msg, data) {
    // any other return code is irrelevant
    if (retval !== constants.cont) { return false; }

    var color = logger.colors[data.level];
    if (color && stdout_is_tty) {
        console.log(logger.colorize(color,data.data));
        return true;
    }

    console.log(data.data);
    return true;
};

logger._init_loglevel = function () {
    var self = this;
    var _loglevel = config.get('loglevel', 'value', function () {
        self._init_loglevel();
    });
    if (_loglevel) {
        var loglevel_num = parseInt(_loglevel);
        if (!loglevel_num || isNaN(loglevel_num)) {
            this.log('INFO', 'loglevel: ' + _loglevel.toUpperCase());
            logger.loglevel = logger[_loglevel.toUpperCase()];
        }
        else {
            logger.loglevel = loglevel_num;
        }
        if (!logger.loglevel) {
            logger.loglevel = logger.LOGWARN;
        }
    }
};

logger.would_log = function (level) {
    if (logger.loglevel < level) { return false; }
    return true;
};

var original_console_log = console.log;

logger._init_timestamps = function () {
    var self = this;
    var _timestamps = config.get('log_timestamps', 'value', function () {
        self._init_timestamps();
    });

    if (_timestamps) {
        console.log = function() {
            var new_arguments = [new Date().toISOString()];
            for (var key in arguments) {
                new_arguments.push(arguments[key]);
            }
            original_console_log.apply(console, new_arguments);
        };
    }
    else {
        console.log = original_console_log;
    }
};

logger._init_loglevel();
logger._init_timestamps();

logger.log_if_level = function (level, key, plugin) {
    return function() {
        if (logger.loglevel < logger[key]) { return; }
        var levelstr = '[' + level + ']';
        var str = '';
        var uuidstr = '[-]';
        var pluginstr = '[' + (plugin || 'core') + ']';
        for (var i=0; i < arguments.length; i++) {
            var data = arguments[i];
            if (typeof(data) !== 'object') {
                str += data;
                continue;
            }

            // if the object is a connection, add the connection id
            if (data instanceof connection.Connection) {
                uuidstr = '[' + data.uuid;
                if (data.tran_count > 0) {
                    uuidstr += "." + data.tran_count;
                }
                uuidstr += ']';
            }
            else if (data instanceof plugins.Plugin) {
                pluginstr = '[' + data.name + ']';
            }
            else if (data instanceof outbound.HMailItem) {
                pluginstr = '[outbound]';
                if (data.todo && data.todo.uuid) {
                    uuidstr = '[' + data.todo.uuid + ']';
                }
            }
            else {
                str += util.inspect(data);
            }
        }
        logger.log(level, [levelstr, uuidstr, pluginstr, str].join(' '));
        return true;
    };
};

logger.add_log_methods = function (object, plugin) {
    if (!object) return;
    if (typeof(object) !== 'object') return;
    for (var level in logger.levels) {
        var fname = 'log' + level.toLowerCase();
        if (object[fname]) continue;  // already added
        object[fname] = logger.log_if_level(level, 'LOG'+level, plugin);
    }
};

logger.add_log_methods(logger);

// load these down here so it sees all the logger methods compiled above
plugins = require('./plugins');
connection = require('./connection');
outbound = require('./outbound');
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var tape = require( 'tape' );
var objectKeys = require( '@stdlib/utils/keys' );
var defineProperty = require( '@stdlib/utils/define-property' );
var propertyDescriptor = require( '@stdlib/utils/property-descriptor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var setConfigurableReadWriteAccessor = require( './../lib' ); // eslint-disable-line id-length

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof setConfigurableReadWriteAccessor, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function sets a property on a provided object', function test( t ) {
	var obj = {};
	var val = 0;

	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );
	t.equal( obj.foo, val, 'returns expected value' );

	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});

tape( 'the read-write property is writable', function test( t ) {
	var obj = {};
	var val = 0;

	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );
	t.equal( obj.foo, 0, 'returns expected value' );

	obj.foo = 1;
	t.equal( obj.foo, 1, 'returns expected value' );

	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});

tape( 'the read-write property is configurable', function test( t ) {
	var desc;
	var obj;
	var val;

	val = 0;

	obj = {};
	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );
	setConfigurableReadWriteAccessor( obj, 'beep', getter, setter );

	desc = {
		'configurable': true,
		'enumerable': false,
		'get': getter,
		'set': setter
	};
	defineProperty( obj, 'foo', desc );
	t.deepEqual( propertyDescriptor( obj, 'foo' ), desc, 'property can be reconfigured' );

	t.equal( obj.beep, 'bar', 'returns expected value' );
	t.equal( hasOwnProp( obj, 'beep' ), true, 'has property' );

	// Configurable properties can be deleted...
	delete obj.beep;
	t.equal( obj.beep, void 0, 'returns expected value' );
	t.equal( hasOwnProp( obj, 'beep' ), false, 'does not have property' );
	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});

tape( 'the read-write property is enumerable', function test( t ) {
	var obj = {};
	var val = 0;

	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );

	t.deepEqual( objectKeys( obj ), [ 'foo' ], 'property is enumerable' );
	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});
<commit_msg>Fix expected value<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var tape = require( 'tape' );
var objectKeys = require( '@stdlib/utils/keys' );
var defineProperty = require( '@stdlib/utils/define-property' );
var propertyDescriptor = require( '@stdlib/utils/property-descriptor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var setConfigurableReadWriteAccessor = require( './../lib' ); // eslint-disable-line id-length

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof setConfigurableReadWriteAccessor, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function sets a property on a provided object', function test( t ) {
	var obj = {};
	var val = 0;

	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );
	t.equal( obj.foo, val, 'returns expected value' );

	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});

tape( 'the read-write property is writable', function test( t ) {
	var obj = {};
	var val = 0;

	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );
	t.equal( obj.foo, 0, 'returns expected value' );

	obj.foo = 1;
	t.equal( obj.foo, 1, 'returns expected value' );

	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});

tape( 'the read-write property is configurable', function test( t ) {
	var desc;
	var obj;
	var val;

	val = 0;

	obj = {};
	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );
	setConfigurableReadWriteAccessor( obj, 'beep', getter, setter );

	desc = {
		'configurable': true,
		'enumerable': false,
		'get': getter,
		'set': setter
	};
	defineProperty( obj, 'foo', desc );
	t.deepEqual( propertyDescriptor( obj, 'foo' ), desc, 'property can be reconfigured' );

	t.equal( obj.beep, 0, 'returns expected value' );
	t.equal( hasOwnProp( obj, 'beep' ), true, 'has property' );

	// Configurable properties can be deleted...
	delete obj.beep;
	t.equal( obj.beep, void 0, 'returns expected value' );
	t.equal( hasOwnProp( obj, 'beep' ), false, 'does not have property' );
	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});

tape( 'the read-write property is enumerable', function test( t ) {
	var obj = {};
	var val = 0;

	setConfigurableReadWriteAccessor( obj, 'foo', getter, setter );

	t.deepEqual( objectKeys( obj ), [ 'foo' ], 'property is enumerable' );
	t.end();

	function getter() {
		return val;
	}

	function setter( v ) {
		val = v;
	}
});
<|endoftext|>


<commit_before>import { Session } from 'meteor/session';

import { globalObj } from '/lib/global';
import { Contracts } from '/imports/api/contracts/Contracts';
import { createContract } from '/imports/startup/both/modules/Contract';
import { checkDuplicate, convertToSlug } from '/lib/utils';

/**
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballot - ballot object
******/
const _setVote = (contractId, ballot) => {
  let candidateBallot = [];

  // see candidate ballots
  if (Session.get('candidateBallot') !== undefined) {
    candidateBallot = Session.get('candidateBallot');
  }
  const multipleChoice = Session.get('contract').multipleChoice;

  //fate
  if (ballot.tick == undefined) { ballot.tick = true } else { ballot.tick = !ballot.tick };

  //add or update ballot in memory
  var update = false;
  for (i in candidateBallot) {
    if (!multipleChoice) {
      candidateBallot[i].ballot.tick = false;
    }
    if (candidateBallot[i].contractId == contractId) {
      if (candidateBallot[i].ballot._id == ballot._id) {
        candidateBallot[i].ballot = ballot
        update = true;
      }
    }
  }
  if (!update) {
    candidateBallot.push({
      contractId: contractId,
      ballot: ballot
    })
  }

  //save to session var
  Session.set('candidateBallot', candidateBallot);
  return ballot.tick;
}

/*****
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballotId - ballotId to check
******/
let _getVote = (contractId, ballotId) => {
  if (Session.get('rightToVote') == false && Session.get('contract').stage != 'DRAFT') {
    //check if user already voted
    var ledger = Session.get('contract').wallet.ledger
    for (i in ledger) {
      if (ledger[i].entityId == Meteor.user()._id) {
        ballot = ledger[i].ballot;
        for (k in ballot) {
          if (ballot[k]._id == ballotId) {
            return true;
          }
        }
      }
    }
    return false;
  } else {
    //check user current vote
    var votes = Session.get('candidateBallot');
    for (i in votes) {
      if (votes[i].contractId == contractId && votes[i].ballot._id == ballotId) {
        return votes[i].ballot.tick;
      }
    }
  }
}

/****
* checks if at least one item from ballot has been checked for voting
****/
let _ballotReady = () => {
  var votes = Session.get('candidateBallot');
  for (i in votes) {
    if (votes[i].ballot.tick == true) {
      return true;
    }
  }
  return false;
}

/****
* keeps only boolean true values in ballot
* @param {object} ballot - ballot object
* @return {object} options - array with only ticked true ballot options
****/
let _purgeBallot = (options) => {
  var finalBallot = new Array();
  for (i in options) {
    if (options[i].ballot.tick == true) {
      finalBallot.push(options[i].ballot);
    }
  }
  return finalBallot;
}

/******
* shows the results of the current poll
* @param {object} contract - contract to check results on
* @return {array} results - array with a statistical object for every item in the ballot
*******/
let _showResults = (contract) => {
  var results = new Array();
  var ledger = contract.wallet.ledger;
  var ballot = contract.ballot;

  //add votes
  for (i in ledger) {
    if (ledger[i].ballot != undefined && ledger[i].ballot.length > 0) {
      quantity = (ledger[i].quantity / ledger[i].ballot.length);
      for (k in ledger[i].ballot) {
        results = _countVotes(results, ledger[i].ballot[k], quantity);
      }
    }
  }

  //get stats
  var totalvotes = 0;
  for (i in results) {
    totalvotes += results[i].votes;
  }

  //set percentage
  for (i in results) {
    const ballotcount = results[i];
    ballotcount['percentage'] = ((ballotcount.votes * 100) / totalvotes);
    results[i] = ballotcount;
  }

  return results;
}

/******
* updates contract execution status based on final results
* @param {object} contract - contract to check results on
* @param {object} results - object with poll results
*********/
let _updateExecutionStatus = (contract, results) => {
  //check result
  var topvotes = 0;
  for (i in results) {
    if (results[i].votes > topvotes) {
      topvotes = results[i].votes;
      winner = results[i].mode;
    }
  }
  if (topvotes == 0) {
    winner = 'NONE';
  }
  if (contract.stage == 'LIVE') {
    var contractId = contract._id;
    switch (winner) {
      case 'AUTHORIZE':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'APPROVED', stage: 'FINISH' } });
        break;
      case 'REJECT':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'REJECTED', stage: 'FINISH' } });
        break;
      case 'FORK':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'ALTERNATIVE', stage: 'FINISH' } });
        break;
      default:
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'VOID', stage: 'FINISH' } });
    }
  }
}

/******
* counts the votes in a given ballot
* @param {array} scoreboard - array with all ballots to do counting on
* @param {ballot} ballot - ballot to which compare existence in scoreboard
* @param {number} quantity - amount of votes to add
* @return {array} scoreboard - result board
*******/
let _countVotes = (scoreboard, ballot, quantity) => {
  for (i in scoreboard) {
    if (scoreboard[i]._id == ballot._id) {
      //add votes to exsting item
      scoreboard[i].votes += quantity;
      return scoreboard;
    }
  }
  //new item in ballot
  ballot['votes'] = quantity;
  scoreboard.push(ballot);
  return scoreboard;
}

/******
* generates a new contract that automatically goes as option in the ballot
*******/
let _forkContract = () => {
  if (Session.get('proposalURLStatus') == 'AVAILABLE') {
    var contract = createContract(convertToSlug(Session.get('newProposal')), Session.get('newProposal'))[0];
    if (contract) {
      if (_addChoiceToBallot(Session.get('contract')._id, contract._id)) {
        var contract = Contracts.findOne( { _id: Session.get('contract')._id }, {reactive: false});
        Session.set('dbContractBallot', contract.ballot );
        globalObj.ProposalSearch.search('');
        document.getElementById("searchInput").innerHTML = '';
        Session.set('proposalURLStatus', 'UNAVAILABLE');
        Session.set('createProposal', false);
        Session.set('emptyBallot', false);
        _verifyDraftFork(contract.ballot);
      }
    } else {
      Session.set('duplicateFork', true)
    }
  }
}

let _quickContract = (keyword) => {
  console.log('[createContract] new contract with keyword: ' + keyword);
  //Adds a new contract to db, returns created insert
  if (keyword != undefined || keyword != '') {
    var slug = convertToSlug(keyword);
  } else {
    var slug = convertToSlug('draft-' + Meteor.userId());
  }

  var creationDate = new Date;
  creationDate.setDate(creationDate.getDate() + 1);
  console.log('[createContract] new contract by user: ' + Meteor.userId());

  if (keyword != '') {
    //Creates new contract:
    console.log('[createContract] contract being created...');
    return Contracts.insert({ title: keyword });

  }
}

/**
* verifies if there's an option in the ballot that is still a draft
* @param {object} ballot - ballot to check
*******/
let _verifyDraftFork = (ballot) => {
  var draftFork = false;
  for (var i in ballot) {
    const choice = Contracts.findOne( { _id: ballot[i]._id });
    if (choice.stage == 'DRAFT') {
      draftFork = true;
      break;
    }
  }
  Session.set('draftOptions', draftFork);
}

/******
* updates the ranking of an option in a ballot
* @param {string} contractId - contract
* @param {array} sortedBallotIDs - available options in this ballot
*******/
let _updateBallotRank = (contractId, sortedBallotIDs) => {
  var contract = Contracts.findOne({ _id: contractId });
  var ballot = contract.ballot;
  for (var i in sortedBallotIDs) {
    for (k in ballot) {
      if (ballot[k]._id == sortedBallotIDs[i]) {
        ballot[k].rank = parseInt(i) + 1;
        break;
      }
    }
  }
  contract.ballot = ballot;
  _verifyDraftFork(ballot);
  Contracts.update({ _id: contractId }, { $set: { ballot: contract.ballot } });
}

/******
* removes an option froim a ballot
* @param {string} contractId - contract
* @param {string} forkId - choice id
*******/
let _removeFork = (contractId, forkId) => {
  Contracts.update({ _id: contractId}, { $pull: {
    ballot:
      { _id: forkId}
  }})
};

/******
* adds a choice to the ballot from an existing proposal
* @param {string} contractId - contract
* @param {string} forkId - choice id
* @return {boolean} value - succesfull add
*******/
let _addChoiceToBallot = (contractId, forkId) => {
  var dbContract = Contracts.findOne({ _id: forkId });
  if (dbContract != undefined) {
    if(checkDuplicate(Contracts.findOne(contractId, { ballot: { _id: dbContract._id } }).ballot, dbContract._id) == false) {
      var rankVal = parseInt(Contracts.findOne({ _id: contractId }).ballot.length) + 1;
      Contracts.update(contractId, { $push: {
        ballot:
          {
            _id: dbContract._id,
            mode: 'FORK',
            url: dbContract.url,
            label: dbContract.title,
            rank: rankVal
          }
      }});
      Session.set('duplicateFork', false);
      if (Contracts.findOne({ _id: dbContract._id }).stage == 'DRAFT') {
        Session.set('draftOptions', true);
      }
      Session.set('dbContractBallot', Contracts.findOne( { _id: contractId }, {reactive: false}).ballot );
      return true;
    } else {
      Session.set('duplicateFork', true);
      return false;
    }
  }
}

export const addChoiceToBallot = _addChoiceToBallot;
export const verifyDraftFork = _verifyDraftFork;
export const removeFork = _removeFork;
export const updateBallotRank = _updateBallotRank;
export const updateExecutionStatus = _updateExecutionStatus;
export const showResults = _showResults;
export const purgeBallot = _purgeBallot;
export const ballotReady = _ballotReady;
export const forkContract = _forkContract;
export const setVote = _setVote;
export const getVote = _getVote;
<commit_msg>Changes to _showResults in order to fix issue #73.<commit_after>import { Session } from 'meteor/session';

import { globalObj } from '/lib/global';
import { Contracts } from '/imports/api/contracts/Contracts';
import { Transactions } from '/imports/api/transactions/Transactions';
import { createContract } from '/imports/startup/both/modules/Contract';
import { checkDuplicate, convertToSlug } from '/lib/utils';

/**
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballot - ballot object
******/
const _setVote = (contractId, ballot) => {
  let candidateBallot = [];

  // see candidate ballots
  if (Session.get('candidateBallot') !== undefined) {
    candidateBallot = Session.get('candidateBallot');
  }
  const multipleChoice = Session.get('contract').multipleChoice;

  //fate
  if (ballot.tick == undefined) { ballot.tick = true } else { ballot.tick = !ballot.tick };

  //add or update ballot in memory
  var update = false;
  for (i in candidateBallot) {
    if (!multipleChoice) {
      candidateBallot[i].ballot.tick = false;
    }
    if (candidateBallot[i].contractId == contractId) {
      if (candidateBallot[i].ballot._id == ballot._id) {
        candidateBallot[i].ballot = ballot
        update = true;
      }
    }
  }
  if (!update) {
    candidateBallot.push({
      contractId: contractId,
      ballot: ballot
    })
  }

  //save to session var
  Session.set('candidateBallot', candidateBallot);
  return ballot.tick;
}

/*****
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballotId - ballotId to check
******/
let _getVote = (contractId, ballotId) => {
  if (Session.get('rightToVote') == false && Session.get('contract').stage != 'DRAFT') {
    //check if user already voted
    var ledger = Session.get('contract').wallet.ledger
    for (i in ledger) {
      if (ledger[i].entityId == Meteor.user()._id) {
        ballot = ledger[i].ballot;
        for (k in ballot) {
          if (ballot[k]._id == ballotId) {
            return true;
          }
        }
      }
    }
    return false;
  } else {
    //check user current vote
    var votes = Session.get('candidateBallot');
    for (i in votes) {
      if (votes[i].contractId == contractId && votes[i].ballot._id == ballotId) {
        return votes[i].ballot.tick;
      }
    }
  }
}

/****
* checks if at least one item from ballot has been checked for voting
****/
let _ballotReady = () => {
  var votes = Session.get('candidateBallot');
  for (i in votes) {
    if (votes[i].ballot.tick == true) {
      return true;
    }
  }
  return false;
}

/****
* keeps only boolean true values in ballot
* @param {object} ballot - ballot object
* @return {object} options - array with only ticked true ballot options
****/
let _purgeBallot = (options) => {
  var finalBallot = new Array();
  for (i in options) {
    if (options[i].ballot.tick == true) {
      finalBallot.push(options[i].ballot);
    }
  }
  return finalBallot;
}

/******
* counts the votes in a given ballot
* @param {array} scoreboard - array with all ballots to do counting on
* @param {ballot} ballot - ballot to which compare existence in scoreboard
* @param {number} quantity - amount of votes to add
* @return {array} scoreboard - result board
*******/
let _countVotes = (scoreboard, ballot, quantity) => {
  for (i in scoreboard) {
    if (scoreboard[i]._id == ballot._id) {
      //add votes to exsting item
      scoreboard[i].votes += quantity;
      return scoreboard;
    }
  }
  //new item in ballot
  ballot['votes'] = quantity;
  scoreboard.push(ballot);
  return scoreboard;
}

/******
* shows the results of the current poll
* @param {object} contract - contract to check results on
* @return {array} results - array with a statistical object for every item in the ballot
*******/
const _showResults = (contract) => {
  let results = [];
  const ledger = contract.wallet.ledger;
  const ledgerIds = ledger.map(x => x.txId);

  // add votes
  Transactions.find({ _id: { $in: ledgerIds } }).forEach((transaction) => {
    const ballots = transaction.condition.ballot;
    if (ballots !== undefined && ballots.length > 0) {
      const quantity = (transaction.output.quantity / ballots.length);
      ballots.forEach((ballot) => {
        results = _countVotes(results, ballot, quantity);
      });
    }
  });

  // get stats
  let totalvotes = 0;
  results.forEach(result => (totalvotes += result.votes));

  // set percentage
  for (const result of results) {
    result.percentage = ((result.votes * 100) / totalvotes);
  }

  return results;
};

/******
* updates contract execution status based on final results
* @param {object} contract - contract to check results on
* @param {object} results - object with poll results
*********/
let _updateExecutionStatus = (contract, results) => {
  //check result
  var topvotes = 0;
  for (i in results) {
    if (results[i].votes > topvotes) {
      topvotes = results[i].votes;
      winner = results[i].mode;
    }
  }
  if (topvotes == 0) {
    winner = 'NONE';
  }
  if (contract.stage == 'LIVE') {
    var contractId = contract._id;
    switch (winner) {
      case 'AUTHORIZE':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'APPROVED', stage: 'FINISH' } });
        break;
      case 'REJECT':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'REJECTED', stage: 'FINISH' } });
        break;
      case 'FORK':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'ALTERNATIVE', stage: 'FINISH' } });
        break;
      default:
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'VOID', stage: 'FINISH' } });
    }
  }
}

/******
* generates a new contract that automatically goes as option in the ballot
*******/
let _forkContract = () => {
  if (Session.get('proposalURLStatus') == 'AVAILABLE') {
    var contract = createContract(convertToSlug(Session.get('newProposal')), Session.get('newProposal'))[0];
    if (contract) {
      if (_addChoiceToBallot(Session.get('contract')._id, contract._id)) {
        var contract = Contracts.findOne( { _id: Session.get('contract')._id }, {reactive: false});
        Session.set('dbContractBallot', contract.ballot );
        globalObj.ProposalSearch.search('');
        document.getElementById("searchInput").innerHTML = '';
        Session.set('proposalURLStatus', 'UNAVAILABLE');
        Session.set('createProposal', false);
        Session.set('emptyBallot', false);
        _verifyDraftFork(contract.ballot);
      }
    } else {
      Session.set('duplicateFork', true)
    }
  }
}

let _quickContract = (keyword) => {
  console.log('[createContract] new contract with keyword: ' + keyword);
  //Adds a new contract to db, returns created insert
  if (keyword != undefined || keyword != '') {
    var slug = convertToSlug(keyword);
  } else {
    var slug = convertToSlug('draft-' + Meteor.userId());
  }

  var creationDate = new Date;
  creationDate.setDate(creationDate.getDate() + 1);
  console.log('[createContract] new contract by user: ' + Meteor.userId());

  if (keyword != '') {
    //Creates new contract:
    console.log('[createContract] contract being created...');
    return Contracts.insert({ title: keyword });

  }
}

/**
* verifies if there's an option in the ballot that is still a draft
* @param {object} ballot - ballot to check
*******/
let _verifyDraftFork = (ballot) => {
  var draftFork = false;
  for (var i in ballot) {
    const choice = Contracts.findOne( { _id: ballot[i]._id });
    if (choice.stage == 'DRAFT') {
      draftFork = true;
      break;
    }
  }
  Session.set('draftOptions', draftFork);
}

/******
* updates the ranking of an option in a ballot
* @param {string} contractId - contract
* @param {array} sortedBallotIDs - available options in this ballot
*******/
let _updateBallotRank = (contractId, sortedBallotIDs) => {
  var contract = Contracts.findOne({ _id: contractId });
  var ballot = contract.ballot;
  for (var i in sortedBallotIDs) {
    for (k in ballot) {
      if (ballot[k]._id == sortedBallotIDs[i]) {
        ballot[k].rank = parseInt(i) + 1;
        break;
      }
    }
  }
  contract.ballot = ballot;
  _verifyDraftFork(ballot);
  Contracts.update({ _id: contractId }, { $set: { ballot: contract.ballot } });
}

/******
* removes an option froim a ballot
* @param {string} contractId - contract
* @param {string} forkId - choice id
*******/
let _removeFork = (contractId, forkId) => {
  Contracts.update({ _id: contractId}, { $pull: {
    ballot:
      { _id: forkId}
  }})
};

/******
* adds a choice to the ballot from an existing proposal
* @param {string} contractId - contract
* @param {string} forkId - choice id
* @return {boolean} value - succesfull add
*******/
let _addChoiceToBallot = (contractId, forkId) => {
  var dbContract = Contracts.findOne({ _id: forkId });
  if (dbContract != undefined) {
    if(checkDuplicate(Contracts.findOne(contractId, { ballot: { _id: dbContract._id } }).ballot, dbContract._id) == false) {
      var rankVal = parseInt(Contracts.findOne({ _id: contractId }).ballot.length) + 1;
      Contracts.update(contractId, { $push: {
        ballot:
          {
            _id: dbContract._id,
            mode: 'FORK',
            url: dbContract.url,
            label: dbContract.title,
            rank: rankVal
          }
      }});
      Session.set('duplicateFork', false);
      if (Contracts.findOne({ _id: dbContract._id }).stage == 'DRAFT') {
        Session.set('draftOptions', true);
      }
      Session.set('dbContractBallot', Contracts.findOne( { _id: contractId }, {reactive: false}).ballot );
      return true;
    } else {
      Session.set('duplicateFork', true);
      return false;
    }
  }
}

export const addChoiceToBallot = _addChoiceToBallot;
export const verifyDraftFork = _verifyDraftFork;
export const removeFork = _removeFork;
export const updateBallotRank = _updateBallotRank;
export const updateExecutionStatus = _updateExecutionStatus;
export const showResults = _showResults;
export const purgeBallot = _purgeBallot;
export const ballotReady = _ballotReady;
export const forkContract = _forkContract;
export const setVote = _setVote;
export const getVote = _getVote;
<|endoftext|>


<commit_before>import { compare } from '../util/comparator';

// Operators are used to plan the query; User written JSONs are converted to
// JSON with these operators.
// The operator is a plot on a single axis - it performs a boolean operation on
// the single axis.
//
// Thus, it's stored in a sorted array, and the database system reads it from
// the first, quickly 'winds' the entire database while looking at the pattern.
// it can read the operators from the reverse, too.
//
// Each operator has many instructions, telling that what range/value should be
// accepted or not.
//
// There are these types of instructions: <, >, <=, >=, ==, !=.
// It's pretty self explainary. < and > continues until they meet corresponding
// > or <. != ignores the specific value in the range. You can see it as a very
// specific < and >.
//
// [ > 1, < 3 ] means 1 < n < 3.
// [ < 3 ] means -Infinity < n < 3.
//
// However, != requires that the range is already 'triggered'. For this
// purpose, special instruction '*' is used to mark that all range is
// qualified.

export function gt(value, equal = false) {
  return [
    { type: '>', value, equal },
  ];
}

export function lt(value, equal = false) {
  return [
    { type: '<', value, equal },
  ];
}

export function range(gt, lt, gte = false, lte = false) {
  return [
    { type: '>', value: gt, equal: gte },
    { type: '<', value: lt, equal: lte },
  ];
}

// This assumes that the values array is sorted.
// TODO Check if the array is sorted, and sort them if required
export function eq(values) {
  return values.map(v => ({ type: '=', value: v }));
}

export function neq(values) {
  return [{ type: '*' }].concat(
    values.map(v => ({ type: '=', value: v })));
}

export function not(query) {
  // [ > 1, < 3 ] should be converted to 1 <= n or n >= 3.
  // Simply put, this should be run like this:
  // - > and < should be inverted, along with 'equal'.
  // - If = is met outside, set '*' flag. If > and < is not met until the end,
  //   insert '*' operator at the first. Then, convert it to !=.
  // - If * is met, remove it.
  // - If != is met inside, change it to =.

  // Special case: empty array
  if (query.length === 0) return [{ type: '*' }];
  let hasSign = false;
  let hasEqual = false;
  let output = query.map(op => {
    switch (op.type) {
      case '*':
        return null;
      case '>':
        hasSign = true;
        return { type: '<', equal: !op.equal, value: op.value };
      case '<':
        return { type: '>', equal: !op.equal, value: op.value };
      case '=':
        hasEqual = true;
        return { type: '!=', value: op.value };
      case '!=':
        return { type: '=', value: op.value };
    }
  }).filter(v => v != null);
  if (!hasSign && hasEqual) return [{ type: '*' }].concat(output);
  return output;
}

const OPERATOR_TABLE = {
  '<': { enter: false, exit: true },
  '>': { enter: true, exit: false },
  '*': { enter: true, exit: false },
  '=': { enter: false, exit: false },
  '!=': { enter: false, exit: false },
};

export function or(a, b) {
  // Check each query's 'inside' state. Make 'inside' state large as possible.
  // This can be achieved by doing:
  // Check initial state of the queries.
  //   <, *, != means inside, and >, = means outside.
  // Compare each values of the queries, progress smaller one.
  // If both are outside and the operator enters 'inside' state,
  //   insert that to the output and set 'inside' state.
  // if only the query is inside and the operator leaves 'inside' state,
  //   insert that to the output and clear 'inside' state.
  if (a.length === 0) return b;
  if (b.length === 0) return a;
  let aInside = ['<', '*', '!='].includes(a[0].type);
  let bInside = ['<', '*', '!='].includes(b[0].type);
  let aCount = 0;
  let bCount = 0;
  let output = [];
  while (aCount < a.length && bCount < b.length) {
    // Compare both values and advance smaller one.
    // TODO Handle special case '*', or equal...
    let compared = compare(a[aCount].value, b[bCount].value);
    if (compared < 0) {
      let op = a[aCount];
      let { enter, exit } = OPERATOR_TABLE[op.type];
      aInside = (aInside || enter) && (!exit);
      if (enter && !aInside && !bInside) output.push(op);
      if (exit && aInside && !bInside) output.push(op);
      aCount += 1;
    } else if (compared > 0) {
      let op = b[bCount];
      let { enter, exit } = OPERATOR_TABLE[op.type];
      bInside = (bInside || enter) && (!exit);
      if (enter && !aInside && !bInside) output.push(op);
      if (exit && !aInside && bInside) output.push(op);
      bCount += 1;
    } else {
      // Both are same - this is a special case.
      aCount += 1;
      bCount += 1;
    }
  }
  // Digest remaining data.
  return output;
}
<commit_msg>Add compareOp function<commit_after>import { compare } from '../util/comparator';

// Operators are used to plan the query; User written JSONs are converted to
// JSON with these operators.
// The operator is a plot on a single axis - it performs a boolean operation on
// the single axis.
//
// Thus, it's stored in a sorted array, and the database system reads it from
// the first, quickly 'winds' the entire database while looking at the pattern.
// it can read the operators from the reverse, too.
//
// Each operator has many instructions, telling that what range/value should be
// accepted or not.
//
// There are these types of instructions: <, >, <=, >=, ==, !=.
// It's pretty self explainary. < and > continues until they meet corresponding
// > or <. != ignores the specific value in the range. You can see it as a very
// specific < and >.
//
// [ > 1, < 3 ] means 1 < n < 3.
// [ < 3 ] means -Infinity < n < 3.
//
// However, != requires that the range is already 'triggered'. For this
// purpose, special instruction '*' is used to mark that all range is
// qualified.

export function gt(value, equal = false) {
  return [
    { type: '>', value, equal },
  ];
}

export function lt(value, equal = false) {
  return [
    { type: '<', value, equal },
  ];
}

export function range(gt, lt, gte = false, lte = false) {
  return [
    { type: '>', value: gt, equal: gte },
    { type: '<', value: lt, equal: lte },
  ];
}

// This assumes that the values array is sorted.
// TODO Check if the array is sorted, and sort them if required
export function eq(values) {
  return values.map(v => ({ type: '=', value: v }));
}

export function neq(values) {
  return [{ type: '*' }].concat(
    values.map(v => ({ type: '=', value: v })));
}

export function not(query) {
  // [ > 1, < 3 ] should be converted to 1 <= n or n >= 3.
  // Simply put, this should be run like this:
  // - > and < should be inverted, along with 'equal'.
  // - If = is met outside, set '*' flag. If > and < is not met until the end,
  //   insert '*' operator at the first. Then, convert it to !=.
  // - If * is met, remove it.
  // - If != is met inside, change it to =.

  // Special case: empty array
  if (query.length === 0) return [{ type: '*' }];
  let hasSign = false;
  let hasEqual = false;
  let output = query.map(op => {
    switch (op.type) {
      case '*':
        return null;
      case '>':
        hasSign = true;
        return { type: '<', equal: !op.equal, value: op.value };
      case '<':
        return { type: '>', equal: !op.equal, value: op.value };
      case '=':
        hasEqual = true;
        return { type: '!=', value: op.value };
      case '!=':
        return { type: '=', value: op.value };
    }
  }).filter(v => v != null);
  if (!hasSign && hasEqual) return [{ type: '*' }].concat(output);
  return output;
}

const OPERATOR_TABLE = {
  '<': { enter: false, exit: true },
  '>': { enter: true, exit: false },
  '*': { enter: true, exit: false },
  '=': { enter: false, exit: false },
  '!=': { enter: false, exit: false },
};

function compareOp(a, b) {
  // 1. Compare type. * is always smallest.
  // 2. Compare value.
  // 3. Compare equal.
}

export function or(a, b) {
  // Check each query's 'inside' state. Make 'inside' state large as possible.
  // This can be achieved by doing:
  // Check initial state of the queries.
  //   <, *, != means inside, and >, = means outside.
  // Compare each values of the queries, progress smaller one.
  // If both are outside and the operator enters 'inside' state,
  //   insert that to the output and set 'inside' state.
  // if only the query is inside and the operator leaves 'inside' state,
  //   insert that to the output and clear 'inside' state.
  if (a.length === 0) return b;
  if (b.length === 0) return a;
  let aInside = ['<', '*', '!='].includes(a[0].type);
  let bInside = ['<', '*', '!='].includes(b[0].type);
  let aCount = 0;
  let bCount = 0;
  let output = [];
  while (aCount < a.length && bCount < b.length) {
    // Compare both values and advance smaller one.
    // TODO Handle special case '*', or equal...
    let compared = compare(a[aCount].value, b[bCount].value);
    if (compared < 0) {
      let op = a[aCount];
      let { enter, exit } = OPERATOR_TABLE[op.type];
      aInside = (aInside || enter) && (!exit);
      if (enter && !aInside && !bInside) output.push(op);
      if (exit && aInside && !bInside) output.push(op);
      aCount += 1;
    } else if (compared > 0) {
      let op = b[bCount];
      let { enter, exit } = OPERATOR_TABLE[op.type];
      bInside = (bInside || enter) && (!exit);
      if (enter && !aInside && !bInside) output.push(op);
      if (exit && !aInside && bInside) output.push(op);
      bCount += 1;
    } else {
      // Both are same - this is a special case.
      aCount += 1;
      bCount += 1;
    }
  }
  // Digest remaining data.
  return output;
}
<|endoftext|>


<commit_before>'use strict'

const footballDb = require('./../db/footballDb')

module.exports = {
    leagues_id_table, // binds to /leagues/:id/table
    leagues,          // binds to /leagues
    index             // binds to /
}

/**
 * Every action parameter (e.g. id) taking part of method's name (e.g. _id_)
 * is bound to the corresponding argument of req.params (e.g. req.params.id).
 * In this case this function is useless and we could simply bound
 * property 'leagues_id_table' to method footballDb.leagueTable.
 */
function leagues_id_table(id){
    return footballDb.leagueTable(id)
}

/**
 * Every action parameter (e.g. name) that is NOT part of the method's name
 * will be searched on req.query, req.body, req, res.locals and req.app.locals.
 */
function leagues(name) {
    if(name) name = name.toLowerCase()
    return footballDb
        .leagues()
        .then(leagues => leagues
            .filter(l => !name || l.caption.toLowerCase().indexOf(name) >= 0)
            .map(addLeaguePath))

    function addLeaguePath(league) {
        league.leagueHref = "/football/leagues/" + league.id + "/table"
        return league
    }
}

/**
 * Whenever an action receives the `res` parameter, the connect-controller
 * gets out of the way and delegates on that action the responsibility of
 * sending the response.
 * So whenever you want to do something different from the default behavior
 * you just have to append res to your parameters.
 */
function index() {
    return '/football/leagues'
}<commit_msg>Update web app example with a new endpoint that redirects through the returned string path.<commit_after>'use strict'

const footballDb = require('./../db/footballDb')

module.exports = {
    leagues_id_table, // binds to /leagues/:id/table
    leagues,          // binds to /leagues
    index,            // binds to /
    index_id          // binds to /:id
}

/**
 * Every action parameter (e.g. id) taking part of method's name (e.g. _id_)
 * is bound to the corresponding argument of req.params (e.g. req.params.id).
 * In this case this function is useless and we could simply bound
 * property 'leagues_id_table' to method footballDb.leagueTable.
 */
function leagues_id_table(id){
    return footballDb.leagueTable(id)
}

/**
 * Every action parameter (e.g. name) that is NOT part of the method's name
 * will be searched on req.query, req.body, req, res.locals and req.app.locals.
 */
function leagues(name) {
    if(name) name = name.toLowerCase()
    return footballDb
        .leagues()
        .then(leagues => leagues
            .filter(l => !name || l.caption.toLowerCase().indexOf(name) >= 0)
            .map(addLeaguePath))

    function addLeaguePath(league) {
        league.leagueHref = '/football/leagues/' + league.id + '/table'
        return league
    }
}

/**
 * Whenever an action receives the `res` parameter, the connect-controller
 * gets out of the way and delegates on that action the responsibility of
 * sending the response.
 * So whenever you want to do something different from the default behavior
 * you just have to append `res` to your parameters.
 */
function index(res) {
    /**
     * If this controller is loaded with an options object set with
     * the property `redirectOnStringResult` then this is equivalent
     * to removing the `res` parameter and just return the destination
     * string path '/football/leagues'.
     */
    res.redirect('/football/leagues')
}

/**
 * If this controller is loaded with an options object set with the property
 * `redirectOnStringResult` then this action method redirects to
 * `/football/leagues/:id/table`.
 */
function index_id(id) {
    return '/football/leagues/' + id + '/table'
}
<|endoftext|>


<commit_before>var http = require('http');

(function() {
	var League = {};

	if (typeof exports !== 'undefined') {
		if (typeof module !== 'undefined' && module.exports) {
              exports = module.exports = League;
        }
		exports.LeagueAPI = League;
	}

	var _authKey;
	var _baseurl = 'http://prod.api.pvp.net/api/lol/';
	var _region = 'na';
	var _version = '1.1';
	var _championUrl = '/champion';

	function _craftUrl(urlType) {
		return _baseurl + _region + '/v' + _version + urlType + '?api_key=' + _authKey;
	}

	function _getRequest(path, callback) {
		var response;

		http.get(path, function(response) {
			response.on('data', function(chunk) {
				response += chunk;
			});

			response.on('error', function(error) {
				callback(error, null);
			});

			response.on('end', function() {
				callback(null, response);
			});
		});
	}

	League.init = function(key, region, version) {
		_authKey = key;
	}

	League.Champions = function(callback) {
		var url = _craftUrl(_championUrl);

		_getRequest(url, function(err, champs) {
			if(err) {
				callback(new Error('Error getting champions: ') + err);
			} else {
				callback(null, champs);
			}
		});
	};

}).call(this);<commit_msg>added querystring module<commit_after>var http = require('http');
var querystring = require('querystring');

(function() {
	var League = {};

	if (typeof exports !== 'undefined') {
		if (typeof module !== 'undefined' && module.exports) {
              exports = module.exports = League;
        }
		exports.LeagueAPI = League;
	}

	var _authKey;
	var _baseurl = 'http://prod.api.pvp.net/api/lol/';
	var _region = 'na';
	var _version = '1.1';
	var _championUrl = '/champion';

	function _craftUrl(urlType) {
		return _baseurl + _region + '/v' + _version + urlType + '?api_key=' + _authKey;
	}

	function _getRequest(path, callback) {
		var response;

		http.get(path, function(response) {
			response.on('data', function(chunk) {
				response += chunk;
			});

			response.on('error', function(error) {
				callback(error, null);
			});

			response.on('end', function() {
				callback(null, response);
			});
		});
	}

	League.init = function(key, region, version) {
		_authKey = key;
	}

	League.Champions = function(callback) {
		var url = _craftUrl(_championUrl);

		_getRequest(url, function(err, champs) {
			if(err) {
				callback(new Error('Error getting champions: ') + err);
			} else {
				callback(null, champs);
			}
		});
	};

}).call(this);<|endoftext|>


<commit_before>import React from 'react';
import Board from '@/modules/core/client/components/Board.js';
import { useTranslation } from 'react-i18next';

export default function Volunteering() {
  const { t } = useTranslation('pages');

  return (
    <>
      <Board
        className="volunteer-header board-happyhippies"
        names="happyhippies"
      >

{t('Volunteering')}

      </Board>

              {t(
                'Help us build Trustroots! Nobody can do everything, but everyone can do something…',
              )}

              {t(
                'Trustroots needs developers, designers, people handling support queue, copywriting and much more.',
              )}

              {t(
                'Please head over to our Team Guide to learn how to get started.',
              )}

                  {t('Team Guide')}

                  {t('Meet the team')}

    </>
  );
}

Volunteering.propTypes = {};
<commit_msg>Point volunteers directly to the volunteering page (#2378)<commit_after>import React from 'react';
import Board from '@/modules/core/client/components/Board.js';
import { useTranslation } from 'react-i18next';

export default function Volunteering() {
  const { t } = useTranslation('pages');

  return (
    <>
      <Board
        className="volunteer-header board-happyhippies"
        names="happyhippies"
      >

{t('Volunteering')}

      </Board>

              {t(
                'Help us build Trustroots! Nobody can do everything, but everyone can do something…',
              )}

              {t(
                'Trustroots needs developers, designers, people handling support queue, copywriting and much more.',
              )}

              {t(
                'Please head over to our Team Guide to learn how to get started.',
              )}

                  {t('Team Guide')}

                  {t('Meet the team')}

    </>
  );
}

Volunteering.propTypes = {};
<|endoftext|>


<commit_before>import * as Rx from 'rxjs';

export const FETCH_USER_PENDING = 'FETCH_USER_PENDING';
export const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
export const FETCH_USER_ABORTED = 'FETCH_USER_ABORTED';

export const fetchUser = () => (
  (actions, store) => Rx.Observable.of({ id: 1, name: 'Bilbo Baggins', timestamp: new Date() })
    // Delaying to emulate an async request, like Rx.Observable.ajax('/api/path')
    .delay(1000)
    // When our request comes back, we transform it into an action
    // that is then automatically dispatched by the middleware
    .map(
      payload => ({ type: FETCH_USER_FULFILLED, payload })
    )
    // Abort fetching the user if someone dispatches an abort action
    .takeUntil(
      actions.ofType(FETCH_USER_ABORTED)
    )
    // Let's us immediately update the user's state so we can display
    // loading messages to the user, etc.
    .startWith({ type: FETCH_USER_PENDING })
);

// Plain old action
export const abortFetchUser = () => ({ type: FETCH_USER_ABORTED });
<commit_msg>docs(README): Reduce confusion about when middleware dispatches emitted actions<commit_after>import * as Rx from 'rxjs';

export const FETCH_USER_PENDING = 'FETCH_USER_PENDING';
export const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
export const FETCH_USER_ABORTED = 'FETCH_USER_ABORTED';

export const fetchUser = () => (
  (actions, store) => Rx.Observable.of({ id: 1, name: 'Bilbo Baggins', timestamp: new Date() })
    // Delaying to emulate an async request, like Rx.Observable.ajax('/api/path')
    .delay(1000)
    // When our request comes back, we transform it into an action
    // which the redux-observable middleware will then dispatch
    .map(
      payload => ({ type: FETCH_USER_FULFILLED, payload })
    )
    // Abort fetching the user if someone dispatches an abort action
    .takeUntil(
      actions.ofType(FETCH_USER_ABORTED)
    )
    // Let's us immediately update the user's state so we can display
    // loading messages to the user, etc.
    .startWith({ type: FETCH_USER_PENDING })
);

// Plain old action
export const abortFetchUser = () => ({ type: FETCH_USER_ABORTED });
<|endoftext|>


<commit_before>var Operator = new function() {
	var operators = {
		add: '+', subtract: '-', multiply: '*', divide: '/', equals: '==',
		modulo: '%'
	};
	var operatorNames = {
		add: 'Addition', subtract: 'Subtraction', multiply: 'Multiplication',
		divide: 'Division', equals: 'Comparison', modulo: 'Modulo'
	};

	var operatorClasses = {
		Point: true,
		Size: true
	};

	return {
		isOperator: function(symbol) {
			// As a convention, only add non static bean properties to
			// the documentation. static properties are all supposed to
			// be uppercae and constants.
			if (symbol.operator == 'none')
				print(!(symbol.operator && symbol.operator != 'none'));
			return symbol.params.length == 1 && !symbol.isStatic && (
					/^(add|subtract|multiply|divide|modulo)(\^[0-9])*$/.test(symbol.name)
					&& (symbol.operator != 'none')
				) || ( // equals
					symbol.name == 'equals'
					&& symbol.returns.length && symbol.returns[0].type == 'boolean'
				);
		},

		getOperator: function(symbol) {
			return operators[symbol.name.replace(/\^[0-9]$/,'')];
		}
	}
}

var Helpers = {
	getSymbolId: function(symbol) {
		var id = [symbol.name.toLowerCase().replace(/[\^][0-9]/g, '')];
		if (symbol.params) {
			for (var i = 0, l = symbol.params.length; i < l; i++) {
				var param = symbol.params[i];
				if (!param.isOptional)
					id.push(param.name);
			}
		}
		return id.join('-');
	}
};

var templates;
/** Called automatically by JsDoc Toolkit. */
function publish(symbolSet) {
	publish.conf = {  // trailing slash expected for dirs
		ext:		 ".html",
		outDir:	  JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
		templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
		symbolsDir:  "symbols/",
		srcDir:	  "symbols/src/"
	};

	templates = {
		_class: new JSDOC.JsPlate(publish.conf.templatesDir + "class.tmpl"),
		method: new JSDOC.JsPlate(publish.conf.templatesDir + "method.tmpl"),
		property: new JSDOC.JsPlate(publish.conf.templatesDir + "property.tmpl"),
		parameters: new JSDOC.JsPlate(publish.conf.templatesDir + "parameters.tmpl"),
		operators: new JSDOC.JsPlate(publish.conf.templatesDir + "operators.tmpl"),
		examples: new JSDOC.JsPlate(publish.conf.templatesDir + "examples.tmpl")
	};

	// is source output is suppressed, just display the links to the source file
	if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
		Link.prototype._makeSrcLink = function(srcFilePath) {
			return "<"+srcFilePath+">";
		}
	}

	// Copy over the static files
	copyDirectory(
		new java.io.File(publish.conf.templatesDir + 'resources/'),
		new java.io.File(publish.conf.outDir + 'resources/')
	);

	// used to allow Link to check the details of things being linked to
	Link.symbolSet = symbolSet;

	// create the required templates
	try {
		var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
		var classesTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
	}
	catch(e) {
		print("Couldn't create the required templates: "+e);
		quit();
	}

	// some ustility filters
	function hasNoParent($) {return ($.memberOf == "")}
	function isaFile($) {return ($.is("FILE"))}
	function isaClass($) {return ($.is("CONSTRUCTOR") || $.isNamespace)}

	// get an array version of the symbolset, useful for filtering
	var symbols = symbolSet.toArray();

	// create the hilited source code files
	var files = JSDOC.opt.srcFiles;
	 	for (var i = 0, l = files.length; i < l; i++) {
	 		var file = files[i];
	 		var srcDir = publish.conf.outDir + "symbols/src/";
		makeSrcFile(file, srcDir);
	 	}

 	// get a list of all the classes in the symbolset
 	var classes = symbols.filter(isaClass).sort(makeSortby("alias"));

	// create a filemap in which outfiles must be to be named uniquely, ignoring case
	if (JSDOC.opt.u) {
		var filemapCounts = {};
		Link.filemap = {};
		for (var i = 0, l = classes.length; i < l; i++) {
			var lcAlias = classes[i].alias.toLowerCase();

			if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
			else filemapCounts[lcAlias]++;

			Link.filemap[classes[i].alias] =
				(filemapCounts[lcAlias] > 1)?
				lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
		}
	}

	// create a class index, displayed in the left-hand column of every class page
	Link.base = "../";
 	publish.classesIndex = classesTemplate.process(classes); // kept in memory

	// create each of the class pages
	for (var i = 0, l = classes.length; i < l; i++) {
		var symbol = classes[i];

		symbol.events = symbol.getEvents();   // 1 order matters
		symbol.methods = symbol.getMethods(); // 2
		for (var j = 0; j < symbol.methods.length; j++) {
			var method = symbol.methods[j];
			method.isOperator = Operator.isOperator(method);
		}

		Link.currentSymbol= symbol;
		var output = "";
		output = classTemplate.process(symbol);

		IO.saveFile(publish.conf.outDir+"symbols/", ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
	}

	// regenerate the index with different relative links, used in the index pages
	Link.base = "";
	publish.classesIndex = classesTemplate.process(classes);

	// create the class index page
	try {
		var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"index.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var classesIndex = classesindexTemplate.process(classes);
	IO.saveFile(publish.conf.outDir, "index"+publish.conf.ext, classesIndex);
	classesindexTemplate = classesIndex = classes = null;

	// create the file index page
	try {
		var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
	var allFiles = []; // not all files have file-level docs, but we need to list every one

	for (var i = 0; i < files.length; i++) {
		allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
	}

	for (var i = 0; i < documentedFiles.length; i++) {
		var offset = files.indexOf(documentedFiles[i].alias);
		allFiles[offset] = documentedFiles[i];
	}

	allFiles = allFiles.sort(makeSortby("name"));

	// output the file index page
	var filesIndex = fileindexTemplate.process(allFiles);
	IO.saveFile(publish.conf.outDir, "files"+publish.conf.ext, filesIndex);
	fileindexTemplate = filesIndex = files = null;
}

/** Just the first sentence (up to a full stop). Should not break on dotted variable names. */
function summarize(desc) {
	if (typeof desc != "undefined")
		return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
}

/** Make a symbol sorter by some attribute. */
function makeSortby(attribute) {
	return function(a, b) {
		if (a[attribute] != undefined && b[attribute] != undefined) {
			a = a[attribute].toLowerCase();
			b = b[attribute].toLowerCase();
			if (a  b) return 1;
			return 0;
		}
	}
}

/** Pull in the contents of an external file at the given path. */
function include(path) {
	var path = publish.conf.templatesDir+path;
	return IO.readFile(path);
}

/** Turn a raw source file into a code-hilited page in the docs. */
function makeSrcFile(path, srcDir, name) {
	if (JSDOC.opt.s) return;

	if (!name) {
		name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
		name = name.replace(/\:/g, "_");
	}

	var src = {path: path, name:name, charset: IO.encoding, hilited: ""};

	if (defined(JSDOC.PluginManager)) {
		JSDOC.PluginManager.run("onPublishSrc", src);
	}

	if (src.hilited) {
		IO.saveFile(srcDir, name+publish.conf.ext, src.hilited);
	}
}

/** Build output for displaying function parameters. */
function makeSignature(params) {
	if (!params) return "()";
	var postString = '';
	var first = true;
	params = params.filter(
		function($) {
			return $.name.indexOf(".") == -1; // don't show config params in signature
		}
	);
	var signature = '';
	var postSignature = '';
	for (var i = 0, l = params.length; i < l; i++) {
		var param = params[i];
		if (param.isOptional) {
			signature += '[';
			postSignature += ']';
		}
		if (i > 0)
			signature += ', ';
		signature += param.name;
	}
	return '(' + signature + postSignature + ')';
}

function processGroupTitle(str, symbol) {
	// if (/grouptitle/.test(str))
	// 	print('yeah');
	// print(str);
	var groupTitle = str.match(/\{@grouptitle ([^}]+)\}/);
	if (groupTitle) {
		symbol.groupTitle = groupTitle[1];
		str = str.replace(/\{@grouptitle ([^}]+)\}/, '');
	}
	return str;
}

function processInlineTags(str, param) {
	if (!param)
		param = {};
	// .. ->
..

	str = str.replace(/<(\/)*(code)>/g, '<$1pre>');

	// {@link ...} -> html links
	str = str.replace(/\{@link ([^} ]+) ?\}/gi,
		function(match, symbolName) {
			return new Link().toSymbol(symbolName.replace(/[\^]/g, '-'));
		}
	);
	// {@code ...} -> code blocks
	str = str.replace(/\{@code[\s]([^}]+)\}/gi,
		function(match, code) {
			return '<tt>' + code + '</tt>';
		}
	);

	// {@true ...} -> true if.. false otherwise..
	str = str.replace(/\{@true[\s]([^}]+)\}/gi,
		function(match, text) {
			return '<tt>true</tt> ' + text + ', <tt>false</tt> otherwise';
		}
	);

	var lineBreak = java.lang.System.getProperty('line.separator');

	// Convert any type of lineBreak to the one we're using now:
	str = str.replace(/(\r\n|\n|\r)/g, function(match, lineBreak) {
		return lineBreak;
	});

	// Replace inline  with <tt></tt>
	str = str.replace(/[ \t]*([^\n\r]*?)[ \t]*<\/code>/g, function(match, content) {
		return '<tt>' + content + '</tt>';
	});

	// Put code and pre tags on the same line as the content, as white-space: pre is set:
	str = str.replace(/(<(?:code|pre)>)\s*([\u0000-\uffff]*?)\s*(<\/(?:code|pre)>)/g, function(match, open, content, close) {
		// Filter out the first white space at the beginning of each line, since
		// that stems from the space after the * in the comment and replace
		// with
, to fix a IE problem where lighter.js does not receive
		// linebreaks from code tags weven when white-space: pre is set.
		return '
' + content.replace(/(\r\n|\n|\r) /mg, function(match, lineBreak) {
			return lineBreak;
		}) + '
';
	});
	// Empty lines -> Paragraphs
	if (!param.stripParagraphs) {
		if (param.wrapInParagraphs === undefined || param.wrapInParagraphs)
			str = '
' + str.trim() + '
';
		str = str.trim().replace(/(\r\n|\n|\r)\s*(\r\n|\n|\r)/g, function(match, lineBreak) {
			return '
' + lineBreak + '
';
		});
		// Automatically put

 at the end of sentences with line breaks.
		// Match following
 and
 tags and swallow them. This happens when
		// the original content contains these.
		str = str.trim().replace(/([.:?!;])\s*(\r\n|\n|\r)(\s*)(<\/p>|
|)/g, function(match, before, lineBreak, whiteSpace, after) {
			// Include following whiteSpace as well, since for code blocks they are relevant (e.g. indentation on new line)
			return before + '
' + lineBreak + whiteSpace + '
';
		});
		// Filter out
 tags within and around  and
 blocks again
		str = str.replace(/((?:
\s*|)<(?:code|pre)[^>]*>[\u0000-\uffff]*<\/(?:code|pre)>(?:\s*<\/p>|))/g, function(match, code) {
			return stripTags(code, 'p');
		});
		// Filter out empty paragraphs
		str = str.replace(/
<\/p>/g, '');
	}

	return str;
}

function stripTags(str, tag) {
	var tag = tag || '.*?'; // Default: all tags
	return str.replace(new RegExp('<' + tag + '>|</' + tag + '>', 'g'), '');
}

function copyStatic(dir) {
	var dir = publish.conf.templatesDir + 'resources/';

}

function copyDirectory(sourceLocation, targetLocation) {
	if (sourceLocation.isDirectory()) {
		if (!targetLocation.exists()) {
			targetLocation.mkdir();
		}

		var children = sourceLocation.list();
		for (var i = 0; i < children.length; i++) {
			copyDirectory(new File(sourceLocation, children[i]),
					new File(targetLocation, children[i]));
		}
	} else {
		// Copy the file with FileChannels:
		targetLocation.createNewFile();
		var src = new java.io.FileInputStream(sourceLocation).getChannel();
		var dst = new java.io.FileOutputStream(targetLocation).getChannel();
		var amount = dst.transferFrom(src, 0, src.size());
		src.close();
		dst.close();
	}
}<commit_msg>jsdoc publish.js: remove debug statement.<commit_after>var Operator = new function() {
	var operators = {
		add: '+', subtract: '-', multiply: '*', divide: '/', equals: '==',
		modulo: '%'
	};
	var operatorNames = {
		add: 'Addition', subtract: 'Subtraction', multiply: 'Multiplication',
		divide: 'Division', equals: 'Comparison', modulo: 'Modulo'
	};

	var operatorClasses = {
		Point: true,
		Size: true
	};

	return {
		isOperator: function(symbol) {
			// As a convention, only add non static bean properties to
			// the documentation. static properties are all supposed to
			// be uppercase and constants.
			return symbol.params.length == 1 && !symbol.isStatic && (
					/^(add|subtract|multiply|divide|modulo)(\^[0-9])*$/.test(symbol.name)
					&& (symbol.operator != 'none')
				) || ( // equals
					symbol.name == 'equals'
					&& symbol.returns.length && symbol.returns[0].type == 'boolean'
				);
		},

		getOperator: function(symbol) {
			return operators[symbol.name.replace(/\^[0-9]$/,'')];
		}
	}
}

var Helpers = {
	getSymbolId: function(symbol) {
		var id = [symbol.name.toLowerCase().replace(/[\^][0-9]/g, '')];
		if (symbol.params) {
			for (var i = 0, l = symbol.params.length; i < l; i++) {
				var param = symbol.params[i];
				if (!param.isOptional)
					id.push(param.name);
			}
		}
		return id.join('-');
	}
};

var templates;
/** Called automatically by JsDoc Toolkit. */
function publish(symbolSet) {
	publish.conf = {  // trailing slash expected for dirs
		ext:		 ".html",
		outDir:	  JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
		templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
		symbolsDir:  "symbols/",
		srcDir:	  "symbols/src/"
	};

	templates = {
		_class: new JSDOC.JsPlate(publish.conf.templatesDir + "class.tmpl"),
		method: new JSDOC.JsPlate(publish.conf.templatesDir + "method.tmpl"),
		property: new JSDOC.JsPlate(publish.conf.templatesDir + "property.tmpl"),
		parameters: new JSDOC.JsPlate(publish.conf.templatesDir + "parameters.tmpl"),
		operators: new JSDOC.JsPlate(publish.conf.templatesDir + "operators.tmpl"),
		examples: new JSDOC.JsPlate(publish.conf.templatesDir + "examples.tmpl")
	};

	// is source output is suppressed, just display the links to the source file
	if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
		Link.prototype._makeSrcLink = function(srcFilePath) {
			return "<"+srcFilePath+">";
		}
	}

	// Copy over the static files
	copyDirectory(
		new java.io.File(publish.conf.templatesDir + 'resources/'),
		new java.io.File(publish.conf.outDir + 'resources/')
	);

	// used to allow Link to check the details of things being linked to
	Link.symbolSet = symbolSet;

	// create the required templates
	try {
		var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
		var classesTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
	}
	catch(e) {
		print("Couldn't create the required templates: "+e);
		quit();
	}

	// some ustility filters
	function hasNoParent($) {return ($.memberOf == "")}
	function isaFile($) {return ($.is("FILE"))}
	function isaClass($) {return ($.is("CONSTRUCTOR") || $.isNamespace)}

	// get an array version of the symbolset, useful for filtering
	var symbols = symbolSet.toArray();

	// create the hilited source code files
	var files = JSDOC.opt.srcFiles;
	 	for (var i = 0, l = files.length; i < l; i++) {
	 		var file = files[i];
	 		var srcDir = publish.conf.outDir + "symbols/src/";
		makeSrcFile(file, srcDir);
	 	}

 	// get a list of all the classes in the symbolset
 	var classes = symbols.filter(isaClass).sort(makeSortby("alias"));

	// create a filemap in which outfiles must be to be named uniquely, ignoring case
	if (JSDOC.opt.u) {
		var filemapCounts = {};
		Link.filemap = {};
		for (var i = 0, l = classes.length; i < l; i++) {
			var lcAlias = classes[i].alias.toLowerCase();

			if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
			else filemapCounts[lcAlias]++;

			Link.filemap[classes[i].alias] =
				(filemapCounts[lcAlias] > 1)?
				lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
		}
	}

	// create a class index, displayed in the left-hand column of every class page
	Link.base = "../";
 	publish.classesIndex = classesTemplate.process(classes); // kept in memory

	// create each of the class pages
	for (var i = 0, l = classes.length; i < l; i++) {
		var symbol = classes[i];

		symbol.events = symbol.getEvents();   // 1 order matters
		symbol.methods = symbol.getMethods(); // 2
		for (var j = 0; j < symbol.methods.length; j++) {
			var method = symbol.methods[j];
			method.isOperator = Operator.isOperator(method);
		}

		Link.currentSymbol= symbol;
		var output = "";
		output = classTemplate.process(symbol);

		IO.saveFile(publish.conf.outDir+"symbols/", ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
	}

	// regenerate the index with different relative links, used in the index pages
	Link.base = "";
	publish.classesIndex = classesTemplate.process(classes);

	// create the class index page
	try {
		var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"index.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var classesIndex = classesindexTemplate.process(classes);
	IO.saveFile(publish.conf.outDir, "index"+publish.conf.ext, classesIndex);
	classesindexTemplate = classesIndex = classes = null;

	// create the file index page
	try {
		var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
	}
	catch(e) { print(e.message); quit(); }

	var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
	var allFiles = []; // not all files have file-level docs, but we need to list every one

	for (var i = 0; i < files.length; i++) {
		allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
	}

	for (var i = 0; i < documentedFiles.length; i++) {
		var offset = files.indexOf(documentedFiles[i].alias);
		allFiles[offset] = documentedFiles[i];
	}

	allFiles = allFiles.sort(makeSortby("name"));

	// output the file index page
	var filesIndex = fileindexTemplate.process(allFiles);
	IO.saveFile(publish.conf.outDir, "files"+publish.conf.ext, filesIndex);
	fileindexTemplate = filesIndex = files = null;
}

/** Just the first sentence (up to a full stop). Should not break on dotted variable names. */
function summarize(desc) {
	if (typeof desc != "undefined")
		return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
}

/** Make a symbol sorter by some attribute. */
function makeSortby(attribute) {
	return function(a, b) {
		if (a[attribute] != undefined && b[attribute] != undefined) {
			a = a[attribute].toLowerCase();
			b = b[attribute].toLowerCase();
			if (a  b) return 1;
			return 0;
		}
	}
}

/** Pull in the contents of an external file at the given path. */
function include(path) {
	var path = publish.conf.templatesDir+path;
	return IO.readFile(path);
}

/** Turn a raw source file into a code-hilited page in the docs. */
function makeSrcFile(path, srcDir, name) {
	if (JSDOC.opt.s) return;

	if (!name) {
		name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
		name = name.replace(/\:/g, "_");
	}

	var src = {path: path, name:name, charset: IO.encoding, hilited: ""};

	if (defined(JSDOC.PluginManager)) {
		JSDOC.PluginManager.run("onPublishSrc", src);
	}

	if (src.hilited) {
		IO.saveFile(srcDir, name+publish.conf.ext, src.hilited);
	}
}

/** Build output for displaying function parameters. */
function makeSignature(params) {
	if (!params) return "()";
	var postString = '';
	var first = true;
	params = params.filter(
		function($) {
			return $.name.indexOf(".") == -1; // don't show config params in signature
		}
	);
	var signature = '';
	var postSignature = '';
	for (var i = 0, l = params.length; i < l; i++) {
		var param = params[i];
		if (param.isOptional) {
			signature += '[';
			postSignature += ']';
		}
		if (i > 0)
			signature += ', ';
		signature += param.name;
	}
	return '(' + signature + postSignature + ')';
}

function processGroupTitle(str, symbol) {
	// if (/grouptitle/.test(str))
	// 	print('yeah');
	// print(str);
	var groupTitle = str.match(/\{@grouptitle ([^}]+)\}/);
	if (groupTitle) {
		symbol.groupTitle = groupTitle[1];
		str = str.replace(/\{@grouptitle ([^}]+)\}/, '');
	}
	return str;
}

function processInlineTags(str, param) {
	if (!param)
		param = {};
	// .. ->
..

	str = str.replace(/<(\/)*(code)>/g, '<$1pre>');

	// {@link ...} -> html links
	str = str.replace(/\{@link ([^} ]+) ?\}/gi,
		function(match, symbolName) {
			return new Link().toSymbol(symbolName.replace(/[\^]/g, '-'));
		}
	);
	// {@code ...} -> code blocks
	str = str.replace(/\{@code[\s]([^}]+)\}/gi,
		function(match, code) {
			return '<tt>' + code + '</tt>';
		}
	);

	// {@true ...} -> true if.. false otherwise..
	str = str.replace(/\{@true[\s]([^}]+)\}/gi,
		function(match, text) {
			return '<tt>true</tt> ' + text + ', <tt>false</tt> otherwise';
		}
	);

	var lineBreak = java.lang.System.getProperty('line.separator');

	// Convert any type of lineBreak to the one we're using now:
	str = str.replace(/(\r\n|\n|\r)/g, function(match, lineBreak) {
		return lineBreak;
	});

	// Replace inline  with <tt></tt>
	str = str.replace(/[ \t]*([^\n\r]*?)[ \t]*<\/code>/g, function(match, content) {
		return '<tt>' + content + '</tt>';
	});

	// Put code and pre tags on the same line as the content, as white-space: pre is set:
	str = str.replace(/(<(?:code|pre)>)\s*([\u0000-\uffff]*?)\s*(<\/(?:code|pre)>)/g, function(match, open, content, close) {
		// Filter out the first white space at the beginning of each line, since
		// that stems from the space after the * in the comment and replace
		// with
, to fix a IE problem where lighter.js does not receive
		// linebreaks from code tags weven when white-space: pre is set.
		return '
' + content.replace(/(\r\n|\n|\r) /mg, function(match, lineBreak) {
			return lineBreak;
		}) + '
';
	});
	// Empty lines -> Paragraphs
	if (!param.stripParagraphs) {
		if (param.wrapInParagraphs === undefined || param.wrapInParagraphs)
			str = '
' + str.trim() + '
';
		str = str.trim().replace(/(\r\n|\n|\r)\s*(\r\n|\n|\r)/g, function(match, lineBreak) {
			return '
' + lineBreak + '
';
		});
		// Automatically put

 at the end of sentences with line breaks.
		// Match following
 and
 tags and swallow them. This happens when
		// the original content contains these.
		str = str.trim().replace(/([.:?!;])\s*(\r\n|\n|\r)(\s*)(<\/p>|
|)/g, function(match, before, lineBreak, whiteSpace, after) {
			// Include following whiteSpace as well, since for code blocks they are relevant (e.g. indentation on new line)
			return before + '
' + lineBreak + whiteSpace + '
';
		});
		// Filter out
 tags within and around  and
 blocks again
		str = str.replace(/((?:
\s*|)<(?:code|pre)[^>]*>[\u0000-\uffff]*<\/(?:code|pre)>(?:\s*<\/p>|))/g, function(match, code) {
			return stripTags(code, 'p');
		});
		// Filter out empty paragraphs
		str = str.replace(/
<\/p>/g, '');
	}

	return str;
}

function stripTags(str, tag) {
	var tag = tag || '.*?'; // Default: all tags
	return str.replace(new RegExp('<' + tag + '>|</' + tag + '>', 'g'), '');
}

function copyStatic(dir) {
	var dir = publish.conf.templatesDir + 'resources/';

}

function copyDirectory(sourceLocation, targetLocation) {
	if (sourceLocation.isDirectory()) {
		if (!targetLocation.exists()) {
			targetLocation.mkdir();
		}

		var children = sourceLocation.list();
		for (var i = 0; i < children.length; i++) {
			copyDirectory(new File(sourceLocation, children[i]),
					new File(targetLocation, children[i]));
		}
	} else {
		// Copy the file with FileChannels:
		targetLocation.createNewFile();
		var src = new java.io.FileInputStream(sourceLocation).getChannel();
		var dst = new java.io.FileOutputStream(targetLocation).getChannel();
		var amount = dst.transferFrom(src, 0, src.size());
		src.close();
		dst.close();
	}
}<|endoftext|>


<commit_before>const nconf = require("nconf");

nconf.env().argv();
const serverType = nconf.get("SERVER_TYPE");
console.log("SERVER_TYPE=" + serverType);
if (!serverType) {
    throw "SERVER_TYPE must be defined and must have a value of 'bot', 'directline', or 'dev'";
}

if (serverType === "bot" || serverType === "dev") {
    const restify = require('restify');
    const Bot = require("./bot");

    const server = restify.createServer();
    server.post('/api/messages', Bot.connector.listen());
    server.listen(nconf.get('port') || 3978, function () {
        console.log('%s listening to %s', server.name, server.url);
    });
}

if (serverType === "directline" || serverType === "dev") {
    const directline = require("./directline_server");
    directline.server.start(3000, "http://localhost:3978/api/messages");
}
<commit_msg>Configure bot host url<commit_after>const nconf = require("nconf");

nconf.env().argv();
const serverType = nconf.get("SERVER_TYPE");
console.log("SERVER_TYPE=" + serverType);
if (!serverType) {
    throw "SERVER_TYPE must be defined and must have a value of 'bot', 'directline', or 'dev'";
}

if (serverType === "bot" || serverType === "dev") {
    const restify = require('restify');
    const Bot = require("./bot");

    const server = restify.createServer();
    server.post('/api/messages', Bot.connector.listen());
    server.listen(nconf.get('port') || 3978, function () {
        console.log('%s listening to %s', server.name, server.url);
    });
}

if (serverType === "directline" || serverType === "dev") {
    const directline = require("./directline_server");

    const botHost = nconf.get("BOT_HOST") || "http://localhost:3978";
    directline.server.start(3000, botHost + "/api/messages");
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved
 *
 * This file will setup the initial package for the JSDUCK documentation
 *
 */

var commander = require('commander'),
	fs = require('fs'),
	os = require('os'),
	wrench = require('wrench'),
	exec = require("child_process").exec,
	browser = "Safari", versionBanner = "",
	path = require('path'), paths = null;

	require('colors');

	commander
		.version(require('./package.json').version)
        .description('titanium-jsduck command line')
        .usage('titanium-jsduck COMMAND');

		commander.command('install'.blue+' <dir>'.white).description('    create a JSDUCK documentation instance in Titanium Mobile Project'.grey);
		commander.command('open'.blue+' [dir]'.white).description('    open the documentation in browser'.grey);
		commander.parse(process.argv);

		//Opening Banner
		console.log('');
		versionBanner = "Titanium-JSDuck Version " + commander.version();
		console.log( versionBanner );

		switch( os.platform() ){
		case 'darwin2':

			if( fs.existsSync("/usr/bin/jsduck") ){

				// Detecting if any commands + arguments where passed
				if( commander.args.length === 0 ){
					runHelp();
				} else {
					switch(commander.args[0]){
					case 'install':
						runInstall();
						break;
					case 'open':

						if( commander.args[1] ){
							browser = commander.args[1];
						}
						runOpenDocumentation(browser);
						break;
					case 'run':
						runGenerator();
						break;
					default:
						console.log('');
						console.log('[ERROR] Invalid Command entered. Please check the usage again.');
						console.log('');
						runHelp();
						break;
					}
				}

			} else {
				console.log('');
				console.log('[ERROR] JSDUCK is not installed. This ruby package is required use this node npm package.'.red);
				console.log('[ALERT] Install JSDUCK by running this command: sudo gem install jsduck');
				console.log('');
			}

			break;
		default:

			console.log('');
			console.log('[WARNING] titanium-jsduck is not currently supported for your current Operating System'.red );
			console.log('');

			break;
		}

		//
		// HELPER METHODS
		//
		function getPaths(){
			var tempPaths = {
				sourceDir: path.join(__dirname)
			}

			tempPaths["sourceTemplates"] = path.join(tempPaths.sourceDir,'templates');
			tempPaths["docTemplates"]    = path.join(tempPaths.sourceDir,'templates','docs');
			tempPaths["cwd"]			 = path.join(process.cwd());
			tempPaths["targetDirectory"] = path.join('.');
			tempPaths["targetDocPath"]	 = path.join(tempPaths.cwd,'docs');
			return tempPaths;

		};

		function copyFile(){
			fs.createReadStream(paths.sourceTemplates + '/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk'));
		};

		//
		// Main Command Methods
		//
		function runHelp(){
			var messageHelp = "Usage: titanium-jsduck [command] [parameters]\n\n";
			messageHelp += "Commands:\n\tinstall \n\t\t- Installs JSDuck inside a Titanium Mobile Project.";
			messageHelp += "\n\topen \n\t\t- Opens Documentation in Safari Browser";
			messageHelp += "\n\topen firefox \n\t\t- Opens Documentation in Firefox Browser";
			messageHelp += "\n\topen chrome  \n\t\t- Opens Documentation in Google Chrome Browser";
			messageHelp += "\n\trun \n\t\t- Runs jsduck to generate Documentation without compiling Mobile Project";

			console.log(messageHelp);
			console.log();
			console.log();
			process.exit();

		}

		function runGenerator(){
			console.log("[INFO] Running JSDuck Documentation Generator");
			console.log();
			exec("jsduck --config=docs/jsduck.json app");
			process.exit();
		}

		function runOpenDocumentation(browserName){

			if( fs.existsSync("docs/documentation/index.html") ){

				switch(browserName){
				case 'Chrome':
				case 'chrome':
					if( !fs.existsSync("/Applications/Google\ Chrome.app") ){
						console.log('[WARNING] Cannot find Chrome Application installed, defaulting to Safari Browser'.orange );
						browserName = "Safari";
					} else {
						browserName = "Google\ Chrome";
					}
					break;
				case 'Firefox':
				case 'firefox':
					if( !fs.existsSync("/Applications/Firefox.app") ){
						console.log('[WARNING] Cannot find Firefox Application installed, defaulting to Safari Browser'.orange );
						browserName = "Safari";
					} else {
						browserName = "Firefox";
					}
					break;
				default:
					browserName = "Safari";
				break;
				}

				var messageSuccess = "[INFO] Opening Project Documentation with the " + browserName + " Browser";
				console.log(messageSuccess);
				console.log();

				exec("open -a \"/Applications/" + browserName + ".app\" docs/documentation/index.html");

			} else {
				var messageFailure = "[ERROR] Documentation Folder does not exist yet.  Have you compiled your project yet? ";
				console.log(messageFailure.red);
				console.log();
			}

			process.exit();
		}

		function runInstall(){
			// Detect if /app folder exists and/or we are at the root of the Titanium Mobile Project
			if (fs.existsSync("tiapp.xml")) { // or fs.existsSync
			    //
				paths = getPaths();
				console.log("[INFO] Detected an Titanium Mobile Project" );

				if( fs.existsSync("app/alloy.jmk") ){
					// Alloy.jmk exists
					//
					console.log('[INFO] Detected an existing Alloy.jmk... Backing up to alloy.jmk.txt');

					// Making a backup of alloy.jmk if already exists
					//fs.createReadStream('app/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk.txt'));
					fs.writeFileSync('app/alloy.jmk.txt', fs.readFileSync('app/alloy.jmk'));

					// Copy over New Alloy.JMK

					if( fs.existsSync(paths.sourceTemplates + '/alloy.jmk') ){
						//fs.createReadStream(paths.sourceTemplates + '/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk'));
						fs.writeFileSync('app/alloy.jmk', fs.readFileSync(paths.sourceTemplates + '/alloy.jmk'));
						console.log('[INFO] Updated alloy.jmk with config for titanium-jsduck');

	                     var docPath = path.join(paths.targetDirectory,'docs');
	                     wrench.mkdirSyncRecursive(docPath, 0755);
	                     wrench.copyDirSyncRecursive(paths.docTemplates,paths.targetDocPath,{preserve:true,forceDelete:true});

					} else {
						console.log('[ERROR] cannot find alloy.jmk in templates '.red );
					}

				} else {
					// Alloy.jmk does not exists
					console.log("Cannot find an alloy.jmk file in your project.");
					console.log("Generating a customized alloy.jmk for you with titanium-jsduck configured to run. ");
					//console.log("Please wait.... ");

					console.log('');
					//fs.createReadStream(paths.sourceTemplates + '/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk'));
					fs.writeFileSync('app/alloy.jmk', fs.readFileSync(paths.sourceTemplates + '/alloy.jmk'));
                    var docPath = path.join(paths.targetDirectory,'docs');
                    wrench.mkdirSyncRecursive(docPath, 0755);
                    wrench.copyDirSyncRecursive(paths.docTemplates,paths.targetDocPath,{preserve:true,forceDelete:true});

					process.exit();
				}

			} else {
				// App does not exists
			    //
				console.log("Cannot detect if an App folder exists. ");
				console.log("Are you sure you are in the root of Titanium Mobile Project? ");
				console.log('');

				process.exit();
			}
		}

<commit_msg>fixing os.platform() error<commit_after>#!/usr/bin/env node
/*
 * Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved
 *
 * This file will setup the initial package for the JSDUCK documentation
 *
 */

var commander = require('commander'),
	fs = require('fs'),
	os = require('os'),
	wrench = require('wrench'),
	exec = require("child_process").exec,
	browser = "Safari", versionBanner = "",
	path = require('path'), paths = null;

	require('colors');

	commander
		.version(require('./package.json').version)
        .description('titanium-jsduck command line')
        .usage('titanium-jsduck COMMAND');

		commander.command('install'.blue+' <dir>'.white).description('    create a JSDUCK documentation instance in Titanium Mobile Project'.grey);
		commander.command('open'.blue+' [dir]'.white).description('    open the documentation in browser'.grey);
		commander.parse(process.argv);

		//Opening Banner
		console.log('');
		versionBanner = "Titanium-JSDuck Version " + commander.version();
		console.log( versionBanner );

		switch( os.platform() ){
		case 'darwin':

			if( fs.existsSync("/usr/bin/jsduck") ){

				// Detecting if any commands + arguments where passed
				if( commander.args.length === 0 ){
					runHelp();
				} else {
					switch(commander.args[0]){
					case 'install':
						runInstall();
						break;
					case 'open':

						if( commander.args[1] ){
							browser = commander.args[1];
						}
						runOpenDocumentation(browser);
						break;
					case 'run':
						runGenerator();
						break;
					default:
						console.log('');
						console.log('[ERROR] Invalid Command entered. Please check the usage again.');
						console.log('');
						runHelp();
						break;
					}
				}

			} else {
				console.log('');
				console.log('[ERROR] JSDUCK is not installed. This ruby package is required use this node npm package.'.red);
				console.log('[ALERT] Install JSDUCK by running this command: sudo gem install jsduck');
				console.log('');
			}

			break;
		default:

			console.log('');
			console.log('[WARNING] titanium-jsduck is not currently supported for your current Operating System'.red );
			console.log('');

			break;
		}

		//
		// HELPER METHODS
		//
		function getPaths(){
			var tempPaths = {
				sourceDir: path.join(__dirname)
			}

			tempPaths["sourceTemplates"] = path.join(tempPaths.sourceDir,'templates');
			tempPaths["docTemplates"]    = path.join(tempPaths.sourceDir,'templates','docs');
			tempPaths["cwd"]			 = path.join(process.cwd());
			tempPaths["targetDirectory"] = path.join('.');
			tempPaths["targetDocPath"]	 = path.join(tempPaths.cwd,'docs');
			return tempPaths;

		};

		function copyFile(){
			fs.createReadStream(paths.sourceTemplates + '/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk'));
		};

		//
		// Main Command Methods
		//
		function runHelp(){
			var messageHelp = "Usage: titanium-jsduck [command] [parameters]\n\n";
			messageHelp += "Commands:\n\tinstall \n\t\t- Installs JSDuck inside a Titanium Mobile Project.";
			messageHelp += "\n\topen \n\t\t- Opens Documentation in Safari Browser";
			messageHelp += "\n\topen firefox \n\t\t- Opens Documentation in Firefox Browser";
			messageHelp += "\n\topen chrome  \n\t\t- Opens Documentation in Google Chrome Browser";
			messageHelp += "\n\trun \n\t\t- Runs jsduck to generate Documentation without compiling Mobile Project";

			console.log(messageHelp);
			console.log();
			console.log();
			process.exit();

		}

		function runGenerator(){
			console.log("[INFO] Running JSDuck Documentation Generator");
			console.log();
			exec("jsduck --config=docs/jsduck.json app");
			process.exit();
		}

		function runOpenDocumentation(browserName){

			if( fs.existsSync("docs/documentation/index.html") ){

				switch(browserName){
				case 'Chrome':
				case 'chrome':
					if( !fs.existsSync("/Applications/Google\ Chrome.app") ){
						console.log('[WARNING] Cannot find Chrome Application installed, defaulting to Safari Browser'.orange );
						browserName = "Safari";
					} else {
						browserName = "Google\ Chrome";
					}
					break;
				case 'Firefox':
				case 'firefox':
					if( !fs.existsSync("/Applications/Firefox.app") ){
						console.log('[WARNING] Cannot find Firefox Application installed, defaulting to Safari Browser'.orange );
						browserName = "Safari";
					} else {
						browserName = "Firefox";
					}
					break;
				default:
					browserName = "Safari";
				break;
				}

				var messageSuccess = "[INFO] Opening Project Documentation with the " + browserName + " Browser";
				console.log(messageSuccess);
				console.log();

				exec("open -a \"/Applications/" + browserName + ".app\" docs/documentation/index.html");

			} else {
				var messageFailure = "[ERROR] Documentation Folder does not exist yet.  Have you compiled your project yet? ";
				console.log(messageFailure.red);
				console.log();
			}

			process.exit();
		}

		function runInstall(){
			// Detect if /app folder exists and/or we are at the root of the Titanium Mobile Project
			if (fs.existsSync("tiapp.xml")) { // or fs.existsSync
			    //
				paths = getPaths();
				console.log("[INFO] Detected an Titanium Mobile Project" );

				if( fs.existsSync("app/alloy.jmk") ){
					// Alloy.jmk exists
					//
					console.log('[INFO] Detected an existing Alloy.jmk... Backing up to alloy.jmk.txt');

					// Making a backup of alloy.jmk if already exists
					//fs.createReadStream('app/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk.txt'));
					fs.writeFileSync('app/alloy.jmk.txt', fs.readFileSync('app/alloy.jmk'));

					// Copy over New Alloy.JMK

					if( fs.existsSync(paths.sourceTemplates + '/alloy.jmk') ){
						//fs.createReadStream(paths.sourceTemplates + '/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk'));
						fs.writeFileSync('app/alloy.jmk', fs.readFileSync(paths.sourceTemplates + '/alloy.jmk'));
						console.log('[INFO] Updated alloy.jmk with config for titanium-jsduck');

	                     var docPath = path.join(paths.targetDirectory,'docs');
	                     wrench.mkdirSyncRecursive(docPath, 0755);
	                     wrench.copyDirSyncRecursive(paths.docTemplates,paths.targetDocPath,{preserve:true,forceDelete:true});

					} else {
						console.log('[ERROR] cannot find alloy.jmk in templates '.red );
					}

				} else {
					// Alloy.jmk does not exists
					console.log("Cannot find an alloy.jmk file in your project.");
					console.log("Generating a customized alloy.jmk for you with titanium-jsduck configured to run. ");
					//console.log("Please wait.... ");

					console.log('');
					//fs.createReadStream(paths.sourceTemplates + '/alloy.jmk').pipe(fs.createWriteStream('app/alloy.jmk'));
					fs.writeFileSync('app/alloy.jmk', fs.readFileSync(paths.sourceTemplates + '/alloy.jmk'));
                    var docPath = path.join(paths.targetDirectory,'docs');
                    wrench.mkdirSyncRecursive(docPath, 0755);
                    wrench.copyDirSyncRecursive(paths.docTemplates,paths.targetDocPath,{preserve:true,forceDelete:true});

					process.exit();
				}

			} else {
				// App does not exists
			    //
				console.log("Cannot detect if an App folder exists. ");
				console.log("Are you sure you are in the root of Titanium Mobile Project? ");
				console.log('');

				process.exit();
			}
		}

<|endoftext|>