<commit_before>/**
 * __          __   _ _   _                  _
 * \ \        / /  (_) | | |                | |
 *  \ \  /\  / / __ _| |_| |__    _ __   ___| |_
 *   \ \/  \/ / '__| | __| '_ \  | '_ \ / _ \ __|
 *    \  /\  /| |  | | |_| | | |_| | | |  __/ |_
 *     \/  \/ |_|  |_|\__|_| |_(_)_| |_|\___|\__|
 *
 * @created     31st March 2012
 * @edited      14th June 2012
 * @package     NodeBot
 *
 * Copyright (C) 2012 Kevin Kragenbrink <kevin@writh.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

var Parser = use('/Lib/Parser');

/**
 * A Shadowrun Dice parser.
 *
 * @todo Document
 *
 * @author      Kevin Kragenbrink <kevin@writh.net>
 * @version     0.1.0
 * @subpackage  Plugin
 * @plugin      Dice
 * @lends       sr
 */
var sr = Parser.extend(function() {
    var Log                             = use('/Lib/Log');
    var Token                           = use('/Lib/Token');
    var Tokenizer                       = use('/Lib/Tokenizer');
    var Util                            = use('/Lib/Util');

    this.constructor = function (configuration) {
        config = Util.extend(config, configuration);

        results = {
            emitToUser : Util.format(messages.emit, config.prefix),
            emitAroundUser : Util.format(messages.oemit, config.prefix, config.name)
        };

        rolls = [];
        stack = [];
        hits = 0;
        stream = [];
        tokenizer = new Tokenizer(types);
    };

    /**
     * Returns the configuration variables for output.
     * @return {String}
     */
    function formatConfig() {
        var message = '';

        if (config.verbose) {
            var configs = [];

            configs.push(Util.format('Target: %d', config.target));

            message = Util.format(' (%s)', configs.join(', '));
        }

        return message;
    }

    /**
     * Returns the rolls and discarded rolls for output.
     * @return {String}
     */
    function formatVerbose() {
        var message = [];

        if (config.verbose) {
            colorize(rolls);
            message.push(Util.format('Rolls: %s', rolls.join(', ')));
        }

        if (message.length > 0) {
            message = Util.format(' (%s)', message.join('; '));
        }

        return message;
    }

    var colorize = function (set) {
        for (var i in set) {
            if (set[i] >= config.target) {
                set[i] = '%ch%cg' + set[i] + '%cn';
            }
            else if (set[i] <= config.glitch) {
                set[i] = '%ch%cr' + set[i] + '%cn';
            }
        }
    };

    /**
     * Parses an individual token.
     * @param token
     * @param callback
     */
    var parse = function (token, callback) {
        var method = Util.format('parse%s', token.type);
        try {
            this[method].call(this, token.value, callback);
        }
        catch (e) {
            Log.warn('sr parser', method, e.message);
        }
    };

    var getFromRandom = function (dice) {
        var results = [];
        for (var i = 0; i < dice; i++) {
            results.push(1 + Math.floor(Math.random() * 6));
        }
        return results;
    };

    this.parseNextToken = function () {
        var token = tokenizer.getNextToken();

        if (token instanceof Token && token.type !== 'EOF') {
            parse.call(this, token, this.parseNextToken.bind(this));
        }
        else {
            var dice = stack.reduce(function (a, b) { return a + b; }, 0);
            var results = getFromRandom(dice);
            parseFromRandom.call(this, results, rolls, respond);
        }
    };

    var respond = function () {
        for (var method in results) {
            results[method] = Util.format(results[method], roll, formatConfig(), hits, formatVerbose());
        }

        if (config.silent) {
            delete results.emitAroundUser;
        }
        else if (config.gm) {
            results.emitAroundUser = Util.format('%s %s rolls some dice behind the GM screen.', config.prefix, config.name);
        }

        callback(results);
    };

    /**
     * Parses the incoming stream and returns the results.
     *
     * @param   {String}    roll        The string to parse.
     * @return  {Object}
     */
    this.parse = function(r, cb) {
        roll = r;
        callback = cb;
        tokenizer.prepare(roll);
        this.parseNextToken();
    };

    /**
     * Runs the parser an additional number of times and appends the results in place.
     */
    this.parseRepeat = function(amount, callback) {
        amount = parseInt(amount) - 1;
        var total = amount;
        var complete = 0;

        while (amount--) {
            var tc = config;
            tc.prefix = config.repeatPrefix;
            var parser = new wod(tc);
            parser.parse(tokenizer.getStream(), function (repeat) {
                results.emitToUser     += Util.format('\n%s', repeat.emitToUser);
                results.emitAroundUser += Util.format('\n%s', repeat.emitAroundUser);

                if (++complete === total) {
                    callback();
                }
            }.bind(this));
        }
    };

    /**
     * Add tokens do nothing, since addition is handled by reduction in the end.
     */
    this.parseAdd = function (empty, callback) { callback(); };

    /**
     * Subtract tokens multiply the next token by -1.
     */
    this.parseSubtract = function(empty, callback) {
        var token = tokenizer.getNextToken();
        parse.call(this, token, function (results) {
            var operand = stack.pop();
            stack.push(operand * -1);
            callback();
        }.bind(this));
    };

    /**
     * Comment strings do nothing, since they are just emitted as part of the results.
     */
    this.parseComment = function(string, callback) { callback(); };

    /**
     * Number tokens get pushed onto the stack.
     */
    this.parseNumber = function(number, callback) {
        stack.push(+number);
        callback();
    };

    var parseFromRandom = function (results, output, callback) {
        var re = 0;

        results.forEach(function (roll) {
            output.push(roll);

            if (roll >= config.target) {
                successes++;
            }
        });
        callback();
    };

    var callback                        = function () {};

    /**
     * The configuration object for the parser.
     * @var     {Object}
     */
    var config = {
        glitch: 1,
        target : 5,
        silent : false,
        verbose : false
    };

    /**
     * The messages to be used in the results object.
     * @var     {Object}
     */
    var messages = {
        emit : '%s You roll %s%s: %ch%d%cn hits.%s',
        oemit : '%s %s rolls %s%s: %ch%d%cn hits.%s'
    };

    /**
     * Final results.
     * @var     {Object}
     */
    var results;

    /**
     * User input
     * @var     {String}
     */
    var roll;

    /**
     * Initial rolls
     * @var     {Integer[]}
     */
    var rolls;

    /**
     * The current stack.
     * @var     (String[]);
     */
    var stack;

    /**
     * The incoming token stream.
     * @var     {Token[]}
     */
    var stream;

    /**
     * The total successes achieved.
     * @var     {Integer}
     */
    var hits;

    var tokenizer;

    /**
     * The types of tokens which might exist.
     * @var     {Object}    A list of named regular expressions.
     */
    var types = {
        'Repeat'                        : /^\s*(\d+x)/i,
        'Subtract'                      : /^\s*(-)/,
        'Add'                           : /^\s*(\+)/,
        'Number'                        : /^\s*(\d+)/,
        'Comment'                       : /^\s*(\(.+?\))/
    };
});

module.exports = sr;<commit_msg>Successes should be hits.<commit_after>/**
 * __          __   _ _   _                  _
 * \ \        / /  (_) | | |                | |
 *  \ \  /\  / / __ _| |_| |__    _ __   ___| |_
 *   \ \/  \/ / '__| | __| '_ \  | '_ \ / _ \ __|
 *    \  /\  /| |  | | |_| | | |_| | | |  __/ |_
 *     \/  \/ |_|  |_|\__|_| |_(_)_| |_|\___|\__|
 *
 * @created     31st March 2012
 * @edited      14th June 2012
 * @package     NodeBot
 *
 * Copyright (C) 2012 Kevin Kragenbrink <kevin@writh.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

var Parser = use('/Lib/Parser');

/**
 * A Shadowrun Dice parser.
 *
 * @todo Document
 *
 * @author      Kevin Kragenbrink <kevin@writh.net>
 * @version     0.1.0
 * @subpackage  Plugin
 * @plugin      Dice
 * @lends       sr
 */
var sr = Parser.extend(function() {
    var Log                             = use('/Lib/Log');
    var Token                           = use('/Lib/Token');
    var Tokenizer                       = use('/Lib/Tokenizer');
    var Util                            = use('/Lib/Util');

    this.constructor = function (configuration) {
        config = Util.extend(config, configuration);

        results = {
            emitToUser : Util.format(messages.emit, config.prefix),
            emitAroundUser : Util.format(messages.oemit, config.prefix, config.name)
        };

        rolls = [];
        stack = [];
        hits = 0;
        stream = [];
        tokenizer = new Tokenizer(types);
    };

    /**
     * Returns the configuration variables for output.
     * @return {String}
     */
    function formatConfig() {
        var message = '';

        if (config.verbose) {
            var configs = [];

            configs.push(Util.format('Target: %d', config.target));

            message = Util.format(' (%s)', configs.join(', '));
        }

        return message;
    }

    /**
     * Returns the rolls and discarded rolls for output.
     * @return {String}
     */
    function formatVerbose() {
        var message = [];

        if (config.verbose) {
            colorize(rolls);
            message.push(Util.format('Rolls: %s', rolls.join(', ')));
        }

        if (message.length > 0) {
            message = Util.format(' (%s)', message.join('; '));
        }

        return message;
    }

    var colorize = function (set) {
        for (var i in set) {
            if (set[i] >= config.target) {
                set[i] = '%ch%cg' + set[i] + '%cn';
            }
            else if (set[i] <= config.glitch) {
                set[i] = '%ch%cr' + set[i] + '%cn';
            }
        }
    };

    /**
     * Parses an individual token.
     * @param token
     * @param callback
     */
    var parse = function (token, callback) {
        var method = Util.format('parse%s', token.type);
        try {
            this[method].call(this, token.value, callback);
        }
        catch (e) {
            Log.warn('sr parser', method, e.message);
        }
    };

    var getFromRandom = function (dice) {
        var results = [];
        for (var i = 0; i < dice; i++) {
            results.push(1 + Math.floor(Math.random() * 6));
        }
        return results;
    };

    this.parseNextToken = function () {
        var token = tokenizer.getNextToken();

        if (token instanceof Token && token.type !== 'EOF') {
            parse.call(this, token, this.parseNextToken.bind(this));
        }
        else {
            var dice = stack.reduce(function (a, b) { return a + b; }, 0);
            var results = getFromRandom(dice);
            parseFromRandom.call(this, results, rolls, respond);
        }
    };

    var respond = function () {
        for (var method in results) {
            results[method] = Util.format(results[method], roll, formatConfig(), hits, formatVerbose());
        }

        if (config.silent) {
            delete results.emitAroundUser;
        }
        else if (config.gm) {
            results.emitAroundUser = Util.format('%s %s rolls some dice behind the GM screen.', config.prefix, config.name);
        }

        callback(results);
    };

    /**
     * Parses the incoming stream and returns the results.
     *
     * @param   {String}    roll        The string to parse.
     * @return  {Object}
     */
    this.parse = function(r, cb) {
        roll = r;
        callback = cb;
        tokenizer.prepare(roll);
        this.parseNextToken();
    };

    /**
     * Runs the parser an additional number of times and appends the results in place.
     */
    this.parseRepeat = function(amount, callback) {
        amount = parseInt(amount) - 1;
        var total = amount;
        var complete = 0;

        while (amount--) {
            var tc = config;
            tc.prefix = config.repeatPrefix;
            var parser = new wod(tc);
            parser.parse(tokenizer.getStream(), function (repeat) {
                results.emitToUser     += Util.format('\n%s', repeat.emitToUser);
                results.emitAroundUser += Util.format('\n%s', repeat.emitAroundUser);

                if (++complete === total) {
                    callback();
                }
            }.bind(this));
        }
    };

    /**
     * Add tokens do nothing, since addition is handled by reduction in the end.
     */
    this.parseAdd = function (empty, callback) { callback(); };

    /**
     * Subtract tokens multiply the next token by -1.
     */
    this.parseSubtract = function(empty, callback) {
        var token = tokenizer.getNextToken();
        parse.call(this, token, function (results) {
            var operand = stack.pop();
            stack.push(operand * -1);
            callback();
        }.bind(this));
    };

    /**
     * Comment strings do nothing, since they are just emitted as part of the results.
     */
    this.parseComment = function(string, callback) { callback(); };

    /**
     * Number tokens get pushed onto the stack.
     */
    this.parseNumber = function(number, callback) {
        stack.push(+number);
        callback();
    };

    var parseFromRandom = function (results, output, callback) {
        var re = 0;

        results.forEach(function (roll) {
            output.push(roll);

            if (roll >= config.target) {
                hits++;
            }
        });
        callback();
    };

    var callback                        = function () {};

    /**
     * The configuration object for the parser.
     * @var     {Object}
     */
    var config = {
        glitch: 1,
        target : 5,
        silent : false,
        verbose : false
    };

    /**
     * The messages to be used in the results object.
     * @var     {Object}
     */
    var messages = {
        emit : '%s You roll %s%s: %ch%d%cn hits.%s',
        oemit : '%s %s rolls %s%s: %ch%d%cn hits.%s'
    };

    /**
     * Final results.
     * @var     {Object}
     */
    var results;

    /**
     * User input
     * @var     {String}
     */
    var roll;

    /**
     * Initial rolls
     * @var     {Integer[]}
     */
    var rolls;

    /**
     * The current stack.
     * @var     (String[]);
     */
    var stack;

    /**
     * The incoming token stream.
     * @var     {Token[]}
     */
    var stream;

    /**
     * The total successes achieved.
     * @var     {Integer}
     */
    var hits;

    var tokenizer;

    /**
     * The types of tokens which might exist.
     * @var     {Object}    A list of named regular expressions.
     */
    var types = {
        'Repeat'                        : /^\s*(\d+x)/i,
        'Subtract'                      : /^\s*(-)/,
        'Add'                           : /^\s*(\+)/,
        'Number'                        : /^\s*(\d+)/,
        'Comment'                       : /^\s*(\(.+?\))/
    };
});

module.exports = sr;<|endoftext|>


<commit_before>var h = require('virtual-dom/h')
  , inherits = require('util').inherits
  , BaseElement = require('./base-element')

module.exports = Staking

function Staking(target) {
  BaseElement.call(this, target)
}

inherits(Staking, BaseElement)

Staking.prototype.render = function(txs) {
  var self = this
  txs = txs.map(tx)
  return [
    h('#staking.bg-light', [
      h('.tab-text.bg-light.lter.b-b.padder.flex.h', [
        h('h3.text-primary.no-padder.inline.m-t-b-a', 'Staking Probability')
      ])
    , h('.wrapper', [
        h('table.table#transaction_table', [
          h('thead', [
            h('tr', [
              h('th')
            , h('th', 'Date')
            , h('th', 'TxID')
            , h('th', 'Address')
            , h('th', 'Age')
            , h('th.text-right', 'Balance')
            , h('th', 'Coin Day')
            , h('th', 'Probability')
            ])
          ])
        , h('tbody', [
            txs
          ])
        ])
      ])
    ])
  ]
}

function tx(item) {
  var color = '#79C597'
    , cl = 'fa fa-check-circle'

  if (item.status === 'mature') {
    color = '#B50A13'
    cl = 'fa fa-times-circle'
  }

  var date = new Date(item.time * 1000)

  return h('tr', [
    h('td', [
      h('i', {
        style: {
          fontSize: '18px'
        , color: color
        }
      , className: cl
      })
    ])
  , h('td', date.toLocaleString())
  , h('td', txid_link(item['input-txid']))
  , h('td', item.address)
  , h('td', item['age-in-day'])
  , h('td', {
      style: {
        textAlign: 'right'
      }
    }, (item.amount / 1000000).toFixed(6))
  , h('td', item['coin-day-weight'])
  , h('td', item['minting-probability-10min'].toFixed(2) + '%')
  ])
}

function txid_link(id) {
  var trimmed = `${id.substr(0, 10)}...`
  return h('td', [
    h('a', {
      target: '_blank'
    , href: `https://chainz.cryptoid.info/xpy/tx.dws?${id}.htm`
    }, trimmed)
  ])
}
<commit_msg>cleanup staking page<commit_after>var h = require('virtual-dom/h')
  , inherits = require('util').inherits
  , BaseElement = require('./base-element')

module.exports = Staking

function Staking(target) {
  BaseElement.call(this, target)
}

inherits(Staking, BaseElement)

Staking.prototype.render = function(txs) {
  var self = this
  txs = txs.map(tx)
  return [
    h('#staking.bg-light', [
      h('.tab-text.bg-light.lter.b-b.padder.flex.h', [
        h('h3.text-primary.no-padder.inline.m-t-b-a', 'Staking Probability')
      ])
    , h('.wrapper', [
        h('table.table#transaction_table', [
          h('thead', [
            h('tr', [
              h('th', 'Date')
            , h('th', 'Address')
            , h('th', 'Age')
            , h('th.text-right', 'Balance')
            , h('th', 'Coin Day')
            , h('th', 'Probability')
            ])
          ])
        , h('tbody', [
            txs
          ])
        ])
      ])
    ])
  ]
}

function tx(item) {
  var color = '#79C597'
    , cl = 'fa fa-check-circle'

  if (item.status === 'mature') {
    color = '#B50A13'
    cl = 'fa fa-times-circle'
  }

  var date = new Date(item.time * 1000)

  return h('tr', [
    h('td', date.toLocaleString())
  , h('td', [
      h('p', [
        txid_link(item['input-txid'])
      , h('span', item.address)
      ])
    ])
  , h('td', item['age-in-day'])
  , h('td', {
      style: {
        textAlign: 'right'
      }
    }, (item.amount / 1000000).toFixed(6))
  , h('td', item['coin-day-weight'])
  , h('td', item['minting-probability-10min'].toFixed(2) + '%')
  ])
}

function txid_link(id) {
  var trimmed = `${id.substr(0, 40)}...`
  return h('td', [
    h('a', {
      target: '_blank'
    , href: `https://chainz.cryptoid.info/xpy/tx.dws?${id}.htm`
    }, trimmed)
  ])
}
<|endoftext|>


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

var adSchema = mongoose.Schema({
  type: String,
  date: Date,
  imgPath:String
});

var Ad = mongoose.model('Ad', adSchema);

module.exports = Ad;
<commit_msg>added status for ads<commit_after>var mongoose = require('mongoose');

var adSchema = mongoose.Schema({
  type: String,
  date: Date,
  imgPath: String,
  status: String
});

var Ad = mongoose.model('Ad', adSchema);

module.exports = Ad;
<|endoftext|>


<commit_before>/*****************************************************************************
			Copyright (c) 2013 by John Oliva - All Rights Reserved
*****************************************************************************
	File:				adaptive_ai.js
	Purpose:			Implementation of Adaptive AI FSM as a Common.JS module.
*****************************************************************************/

var ADAPTAI_DEFAULTCHANCE = 0.001;
var ADAPTAI_DEFAULTRATE = 0.1;

Random = function() {
	return Math.random();
}

// --------------------------------------------------------------------------
//	Gene
// --------------------------------------------------------------------------
Gene = function (gene) {
	if (gene === undefined) {
		this._sequence = [];		// array of float
		this._mutationChance = ADAPTAI_DEFAULTCHANCE;
		this._mutationRate = ADAPTAI_DEFAULTRATE;
		this._sequenceLength = 0;
	} else {
		this.copy(gene);
	}
}

Gene.prototype.getSequence = function() {
	return this._sequence;
}

Gene.prototype.setElement = function(idx, element) {
	if (idx >= 0 && idx < this._sequenceLength) {
		this._sequence[idx] = element;
		return true;
	}

	return false;
}

Gene.prototype.getElement = function(idx) {
	if (idx >= 0 && idx < this._sequenceLength) {
		return this._sequence[idx];
	}

	return 0.0;
}

Gene.prototype.setLength = function(length) {
	this._sequenceLength = length;

	this._sequence=[];

	for (var i=0; i<length; i++) {
		this._sequence[i] = 0.0;
	}

	return true;
}

Gene.prototype.getLength = function() {
	return this._sequenceLength;
}

Gene.prototype.setMutationChance = function(chance) {
	// Crop to [0, 1]
	if (chance < 0.0) {
		chance = 0.0;
	} else if (chance > 1.0) {
		chance = 1.0;
	}

	this._mutationChance = chance;

	return true;
}

Gene.prototype.getMutationChance = function() {
	return this._mutationChance;
}

Gene.prototype.setMutationRate = function(mutationRate) {
	this._mutationRate = mutationRate;
	return true;
}

Gene.prototype.getMutationRate = function() {
	return this._mutationRate;
}

Gene.prototype.mutate = function() {
	if (this._sequenceLength <= 0)
		return false;

	for (var i=0, l=this._sequenceLength; i<l; i++) {
		if (Random() <= this._mutationChance)
			this._sequence[i] = this._sequence[i] + (2.0 * Random() - 1.0) * this._mutationRate;
	}

	return true;
}

Gene.prototype.mutateMutationFactors = function(chance, rate) {
	if (Random() <= chance) {
		this._mutationChance += (Random() * 2.0 - 1.0) * rate;
		this._mutationRate += (Random() * 2.0 - 1.0) * rate;
	}

	return true;
}

Gene.prototype.copy = function(gene) {
	this._sequenceLength = gene._sequenceLength;
	this._mutationChance = gene._mutationChance;
	this._mutationRate = gene._mutationRate;
	this._sequence = gene._sequence.slice();

	return this;
}

Gene.prototype.add = function(gene) {
	var newGene = new Gene();

	if (this._sequenceLength != gene._sequenceLength)
		return newGene;

	newGene.setLength(this._sequenceLength);

	// Arithmetic average of elements:
	for (var i=0, l=this._sequenceLength; i<l; i++) {
		newGene._sequence[i] = (this._sequence[i] + gene._sequence[i]) / 2.0;
	}

	return newGene;
}

Gene.prototype.save = function(fstream) {
}

Gene.prototype.load = function(fstream) {
}

// --------------------------------------------------------------------------
//	Chromosome
// --------------------------------------------------------------------------
Chromosome = function (chromosome) {
	if (chromosome === undefined) {
		this._geneList = [];
		this._geneCount = 0;
		this._crossover = true;
		this._crossoverMutationChance = ADAPTAI_DEFAULTCHANCE;
	} else {
		this.copy(chromosome);
	}
}

Chromosome.prototype.getGeneList = function() {
	return this._geneList;
}

Chromosome.prototype.setGene = function(idx, gene) {
	if (idx < 0 || idx >= this._geneCount) {
		return false;
	}

	this._geneList[idx] = new Gene(gene);

	return true;
}

Chromosome.prototype.getGene = function(idx) {
	if (idx < 0 || idx >= this._geneCount) {
		throw new RangeError('Invalid index into geneList');
	}

	return this._geneList[idx];
}

Chromosome.prototype.setGeneCount = function (length) {
	if (length < 0)
		return false;

	this._geneList = [];
	this._geneCount = length;

	for (var i=0; i<length; i++) {
		this._geneList.push(new Gene());
	}

	return true;
}

Chromosome.prototype.getGeneCount = function() {
	return this._geneCount;
}

Chromosome.prototype.copy = function(chrom) {
	this._geneCount = chrom._geneCount;
	this._crossover = chrom._crossover;
	this._crossoverMutationChance = chrom._crossoverMutationChance;

	this._geneList = [];

	// Copy gene info:
	for (var i=0; i<this._geneCount; i++) {
		this._geneList.push(new Gene(chrom._geneList[i]));
	}

	return this;
}

Chromosome.prototype.add = function(chrom) {
	var Temp = new Chromosome();

	if (this._geneCount != chrom._geneCount)
		return Temp;

	Temp.setGeneCount (this._geneCount);

	if (this._crossover) {
		// 50% chance of inheriting crossover trait & mutation rate from either parent:
		if (Random () < 0.5) {
			Temp._crossover = this._crossover;
			Temp._crossoverMutationChance = this._crossoverMutationChance;
		} else {
			Temp._crossover = chrom._crossover;
			Temp._crossoverMutationChance = chrom._crossoverMutationChance;
		}

		for (var i=0; i<this._geneCount; i++) {
			// 50% chance of inheriting gene from either parent:
			if (Random () < 0.5) {
				Temp._geneList[i] = new Gene(this._geneList[i]);
			} else {
				Temp._geneList[i] = new Gene(chrom._geneList[i]);
			}
		}
	} else {
		// 50% chance of inheriting crossover trait from either parent:
		if (Random () < 0.5) {
			Temp._crossover = this._crossover;
		} else {
			Temp._crossover = chrom._crossover;
		}

		// Mutation chance is numerical average of parents:
		Temp._crossoverMutationChance = (this._crossoverMutationChance + chrom._crossoverMutationChance) / 2.0;

		// Genes are numerical average of parents:
		for (var i=0; i < this._geneCount; i++) {
			Temp._geneList[i] = this._geneList[i].add(chrom._geneList[i]);
		}
	}

	return Temp;
}

Chromosome.prototype.setCrossoverState = function(state) {
	// state is boolean
	this._crossover = state;

	return true;
}

Chromosome.prototype.getCrossoverState = function() {
	return this._crossover;
}

Chromosome.prototype.setCrossoverMutationChance = function(chance) {
	// Clamp mutation chance:
	if (chance < 0.0) {
		chance = 0.0;
	} else if (chance > 1.0) {
		chance = 1.0;
	}

	this._crossoverMutationChance = chance;

	return true;
}

Chromosome.prototype.getCrossoverMutationChance = function() {
	return this._crossoverMutationChance;
}

Chromosome.prototype.mutateChromosome = function() {
	if (Random () <= this._crossoverMutationChance) {
		if (this._crossover) {
			this._crossover = false;
		} else {
			this.crossover = true;
		}
	}

	return true;
}

Chromosome.prototype.mutateGenes = function() {
	for (var i=0; i<this._geneCount; i++)
		this._geneList[i].mutate();

	return true;
}

Chromosome.prototype.mutate = function() {
	return (this.mutateChromosome() && this.mutateGenes());
}

Chromosome.prototype.mutateMutationFactors = function(chance, rate) {
	if (Random () <= chance) {
		this.setCrossoverMutationChance(this._crossoverMutationChance + (Random() * 2.0 - 1.0) * rate);
	}

	for (var i=0; i<this._geneCount; i++) {
		this._geneList[i].mutateMutationFactors(chance, rate);
	}

	return true;
}

Chromosome.prototype.save = function(fstream) {
}

Chromosome.prototype.load = function(fstream) {
}

// --------------------------------------------------------------------------
//	Genome
// --------------------------------------------------------------------------

Genome = function (genome) {
	if (genome === undefined) {
		this._chromosomeList = [];
		this._chromosomeCount = 0;
	} else {
		this.copy(genome);
	}
}

Genome.prototype.setChromosome = function(idx, chrom) {
	if (idx < 0 || idx >= this._chromosomeCount)
		return false;

	this._chromosomeList[idx] = new Chromosome(chrom);

	return true;
}

Genome.prototype.getChromosome = function(idx) {
	if (idx < 0 || idx >= this._chromosomeCount) {
		throw new RangeError('Invalid index into chromosomeList');
	}

	return this._chromosomeList[idx];
}

Genome.prototype.setChromosomeCount = function(count) {
	if (count < 0)
		return false;

	this._chromosomeList = [];
	this._chromosomeCount = count;

	for (var i=0; i<count; i++) {
		this._chromosomeList.push(new Chromosome());
	}

	return true;
}

Genome.prototype.getChromosomeCount = function() {
	return this._chromosomeCount;
}

Genome.prototype.copy = function(genome) {
	this.setChromosomeCount(genome._chromosomeCount);

	this._chromosomeList = [];

	for (var i=0; i<this._chromosomeCount; i++) {
		this._chromosomeList.push(new Chromosome(genome._chromosomeList[i]));
	}

	return this;
}

Genome.prototype.add = function(genome) {
	var Temp = new Genome();

	if (this._chromosomeCount !== genome._chromosomeCount) {
		throw new RangeError('Attempt to add genomes with differing chromosome counts.');
	}

	Temp.setChromosomeCount(this._chromosomeCount);

	for (var i=0; i<this._chromosomeCount; i++) {
		Temp._chromosomeList[i] = this._chromosomeList[i].add(genome._chromosomeList[i]);
	}

	return Temp;
}

Genome.prototype.mutate = function() {
	for (var i=0; i<this._chromosomeCount; i++) {
		this._chromosomeList[i].mutate();
	}

	return true;
}

Genome.prototype.mutateMutationFactors = function(chance, rate) {
	for (var i=0; i<this._chromosomeCount; i++) {
		this._chromosomeList[i].mutateMutationFactors(chance, rate);
	}

	return true;
}

Genome.prototype.save = function(fstream) {
}

Genome.prototype.load = function(fstream) {
}

// --------------------------------------------------------------------------
exports.GA={};
exports.GA.Gene = Gene;
exports.GA.Chromosome = Chromosome;
exports.GA.Genome = Genome;

<commit_msg>Implemented Organism.State class in the Org namespace for module.<commit_after>/*****************************************************************************
			Copyright (c) 2013 by John Oliva - All Rights Reserved
*****************************************************************************
	File:				adaptive_ai.js
	Purpose:			Implementation of Adaptive AI FSM as a Common.JS module.
*****************************************************************************/

var ADAPTAI_DEFAULTCHANCE = 0.001;
var ADAPTAI_DEFAULTRATE = 0.1;

Random = function() {
	return Math.random();
}

// --------------------------------------------------------------------------
//	Genetic Algorithm: Gene
// --------------------------------------------------------------------------
Gene = function (gene) {
	if (gene === undefined) {
		this._sequence = [];		// array of float
		this._mutationChance = ADAPTAI_DEFAULTCHANCE;
		this._mutationRate = ADAPTAI_DEFAULTRATE;
		this._sequenceLength = 0;
	} else {
		this.copy(gene);
	}
}

Gene.prototype.getSequence = function() {
	return this._sequence;
}

Gene.prototype.setElement = function(idx, element) {
	if (idx >= 0 && idx < this._sequenceLength) {
		this._sequence[idx] = element;
		return true;
	}

	return false;
}

Gene.prototype.getElement = function(idx) {
	if (idx >= 0 && idx < this._sequenceLength) {
		return this._sequence[idx];
	}

	return 0.0;
}

Gene.prototype.setLength = function(length) {
	this._sequenceLength = length;

	this._sequence=[];

	for (var i=0; i<length; i++) {
		this._sequence[i] = 0.0;
	}

	return true;
}

Gene.prototype.getLength = function() {
	return this._sequenceLength;
}

Gene.prototype.setMutationChance = function(chance) {
	// Crop to [0, 1]
	if (chance < 0.0) {
		chance = 0.0;
	} else if (chance > 1.0) {
		chance = 1.0;
	}

	this._mutationChance = chance;

	return true;
}

Gene.prototype.getMutationChance = function() {
	return this._mutationChance;
}

Gene.prototype.setMutationRate = function(mutationRate) {
	this._mutationRate = mutationRate;
	return true;
}

Gene.prototype.getMutationRate = function() {
	return this._mutationRate;
}

Gene.prototype.mutate = function() {
	if (this._sequenceLength <= 0)
		return false;

	for (var i=0, l=this._sequenceLength; i<l; i++) {
		if (Random() <= this._mutationChance)
			this._sequence[i] = this._sequence[i] + (2.0 * Random() - 1.0) * this._mutationRate;
	}

	return true;
}

Gene.prototype.mutateMutationFactors = function(chance, rate) {
	if (Random() <= chance) {
		this._mutationChance += (Random() * 2.0 - 1.0) * rate;
		this._mutationRate += (Random() * 2.0 - 1.0) * rate;
	}

	return true;
}

Gene.prototype.copy = function(gene) {
	this._sequenceLength = gene._sequenceLength;
	this._mutationChance = gene._mutationChance;
	this._mutationRate = gene._mutationRate;
	this._sequence = gene._sequence.slice();

	return this;
}

Gene.prototype.add = function(gene) {
	var newGene = new Gene();

	if (this._sequenceLength != gene._sequenceLength)
		return newGene;

	newGene.setLength(this._sequenceLength);

	// Arithmetic average of elements:
	for (var i=0, l=this._sequenceLength; i<l; i++) {
		newGene._sequence[i] = (this._sequence[i] + gene._sequence[i]) / 2.0;
	}

	return newGene;
}

Gene.prototype.save = function(fstream) {
}

Gene.prototype.load = function(fstream) {
}

// --------------------------------------------------------------------------
//	Genetic Algorithm: Chromosome
// --------------------------------------------------------------------------
Chromosome = function (chromosome) {
	if (chromosome === undefined) {
		this._geneList = [];
		this._geneCount = 0;
		this._crossover = true;
		this._crossoverMutationChance = ADAPTAI_DEFAULTCHANCE;
	} else {
		this.copy(chromosome);
	}
}

Chromosome.prototype.getGeneList = function() {
	return this._geneList;
}

Chromosome.prototype.setGene = function(idx, gene) {
	if (idx < 0 || idx >= this._geneCount) {
		return false;
	}

	this._geneList[idx] = new Gene(gene);

	return true;
}

Chromosome.prototype.getGene = function(idx) {
	if (idx < 0 || idx >= this._geneCount) {
		throw new RangeError('Invalid index into geneList');
	}

	return this._geneList[idx];
}

Chromosome.prototype.setGeneCount = function (length) {
	if (length < 0)
		return false;

	this._geneList = [];
	this._geneCount = length;

	for (var i=0; i<length; i++) {
		this._geneList.push(new Gene());
	}

	return true;
}

Chromosome.prototype.getGeneCount = function() {
	return this._geneCount;
}

Chromosome.prototype.copy = function(chrom) {
	this._geneCount = chrom._geneCount;
	this._crossover = chrom._crossover;
	this._crossoverMutationChance = chrom._crossoverMutationChance;

	this._geneList = [];

	// Copy gene info:
	for (var i=0; i<this._geneCount; i++) {
		this._geneList.push(new Gene(chrom._geneList[i]));
	}

	return this;
}

Chromosome.prototype.add = function(chrom) {
	var Temp = new Chromosome();

	if (this._geneCount != chrom._geneCount)
		return Temp;

	Temp.setGeneCount (this._geneCount);

	if (this._crossover) {
		// 50% chance of inheriting crossover trait & mutation rate from either parent:
		if (Random () < 0.5) {
			Temp._crossover = this._crossover;
			Temp._crossoverMutationChance = this._crossoverMutationChance;
		} else {
			Temp._crossover = chrom._crossover;
			Temp._crossoverMutationChance = chrom._crossoverMutationChance;
		}

		for (var i=0; i<this._geneCount; i++) {
			// 50% chance of inheriting gene from either parent:
			if (Random () < 0.5) {
				Temp._geneList[i] = new Gene(this._geneList[i]);
			} else {
				Temp._geneList[i] = new Gene(chrom._geneList[i]);
			}
		}
	} else {
		// 50% chance of inheriting crossover trait from either parent:
		if (Random () < 0.5) {
			Temp._crossover = this._crossover;
		} else {
			Temp._crossover = chrom._crossover;
		}

		// Mutation chance is numerical average of parents:
		Temp._crossoverMutationChance = (this._crossoverMutationChance + chrom._crossoverMutationChance) / 2.0;

		// Genes are numerical average of parents:
		for (var i=0; i < this._geneCount; i++) {
			Temp._geneList[i] = this._geneList[i].add(chrom._geneList[i]);
		}
	}

	return Temp;
}

Chromosome.prototype.setCrossoverState = function(state) {
	// state is boolean
	this._crossover = state;

	return true;
}

Chromosome.prototype.getCrossoverState = function() {
	return this._crossover;
}

Chromosome.prototype.setCrossoverMutationChance = function(chance) {
	// Clamp mutation chance:
	if (chance < 0.0) {
		chance = 0.0;
	} else if (chance > 1.0) {
		chance = 1.0;
	}

	this._crossoverMutationChance = chance;

	return true;
}

Chromosome.prototype.getCrossoverMutationChance = function() {
	return this._crossoverMutationChance;
}

Chromosome.prototype.mutateChromosome = function() {
	if (Random () <= this._crossoverMutationChance) {
		if (this._crossover) {
			this._crossover = false;
		} else {
			this.crossover = true;
		}
	}

	return true;
}

Chromosome.prototype.mutateGenes = function() {
	for (var i=0; i<this._geneCount; i++)
		this._geneList[i].mutate();

	return true;
}

Chromosome.prototype.mutate = function() {
	return (this.mutateChromosome() && this.mutateGenes());
}

Chromosome.prototype.mutateMutationFactors = function(chance, rate) {
	if (Random () <= chance) {
		this.setCrossoverMutationChance(this._crossoverMutationChance + (Random() * 2.0 - 1.0) * rate);
	}

	for (var i=0; i<this._geneCount; i++) {
		this._geneList[i].mutateMutationFactors(chance, rate);
	}

	return true;
}

Chromosome.prototype.save = function(fstream) {
}

Chromosome.prototype.load = function(fstream) {
}

// --------------------------------------------------------------------------
//	Genetic Algorithm: Genome
// --------------------------------------------------------------------------

Genome = function (genome) {
	if (genome === undefined) {
		this._chromosomeList = [];
		this._chromosomeCount = 0;
	} else {
		this.copy(genome);
	}
}

Genome.prototype.setChromosome = function(idx, chrom) {
	if (idx < 0 || idx >= this._chromosomeCount)
		return false;

	this._chromosomeList[idx] = new Chromosome(chrom);

	return true;
}

Genome.prototype.getChromosome = function(idx) {
	if (idx < 0 || idx >= this._chromosomeCount) {
		throw new RangeError('Invalid index into chromosomeList');
	}

	return this._chromosomeList[idx];
}

Genome.prototype.setChromosomeCount = function(count) {
	if (count < 0)
		return false;

	this._chromosomeList = [];
	this._chromosomeCount = count;

	for (var i=0; i<count; i++) {
		this._chromosomeList.push(new Chromosome());
	}

	return true;
}

Genome.prototype.getChromosomeCount = function() {
	return this._chromosomeCount;
}

Genome.prototype.copy = function(genome) {
	this.setChromosomeCount(genome._chromosomeCount);

	this._chromosomeList = [];

	for (var i=0; i<this._chromosomeCount; i++) {
		this._chromosomeList.push(new Chromosome(genome._chromosomeList[i]));
	}

	return this;
}

Genome.prototype.add = function(genome) {
	var Temp = new Genome();

	if (this._chromosomeCount !== genome._chromosomeCount) {
		throw new RangeError('Attempt to add genomes with differing chromosome counts.');
	}

	Temp.setChromosomeCount(this._chromosomeCount);

	for (var i=0; i<this._chromosomeCount; i++) {
		Temp._chromosomeList[i] = this._chromosomeList[i].add(genome._chromosomeList[i]);
	}

	return Temp;
}

Genome.prototype.mutate = function() {
	for (var i=0; i<this._chromosomeCount; i++) {
		this._chromosomeList[i].mutate();
	}

	return true;
}

Genome.prototype.mutateMutationFactors = function(chance, rate) {
	for (var i=0; i<this._chromosomeCount; i++) {
		this._chromosomeList[i].mutateMutationFactors(chance, rate);
	}

	return true;
}

Genome.prototype.save = function(fstream) {
}

Genome.prototype.load = function(fstream) {
}

// --------------------------------------------------------------------------
//	Organism
// --------------------------------------------------------------------------

Organism = function(organism) {
	if (organism === undefined) {
		this._states = [];
		this._sensors = [];
		this._stateCount = 0;
		this._sensorCount = 0;
		this._currentState = 0;
	} else {
		this.copy(organism);
	}
}

// --------------------------------------------------------------------------
//	Organism: State
// --------------------------------------------------------------------------

Organism.State = function(state) {
	if (state === undefined) {
		this._name = 'NOT_SET';
	} else {
		this.copy(state);
	}
}

Organism.State.prototype.setName = function(newName) {
	this._name = newName;
	return true;
}

Organism.State.prototype.copy = function(state) {
	this._name = state.name;
	return this;
}

Organism.State.prototype.save = function(fstream) {
}

Organism.State.prototype.load = function(fstream) {
}

// --------------------------------------------------------------------------
//	Organism: Sensor
// --------------------------------------------------------------------------

// --------------------------------------------------------------------------
exports.GA={};
exports.GA.Gene = Gene;
exports.GA.Chromosome = Chromosome;
exports.GA.Genome = Genome;
exports.Org={};
exports.Org.Organism = Organism;
exports.Org.Organism.State = Organism.State;
exports.Org.Organism.Sensor = Organism.Sensor;

<|endoftext|>


<commit_before>let PolarBear = Ember.Object.extend({
  interval: 1000,

  schedule(context, f) {
    return Ember.run.later(this, function() {
      f.apply(context);
      this.start(context, f);
    }, this.get('interval'));
  },

  kill() {
    return Ember.run.cancel(this.get('timer'));
  },

  start(context, f) {
    this.set('timer', this.schedule(context, f));
  }
});

PolarBear.reopenClass({
  type: 'PolarBear'
});

export default PolarBear;

<commit_msg>expose a flag that represents wheather the polling is alive or not<commit_after>let PolarBear = Ember.Object.extend({
  interval: 1000,

  isAlive: Ember.computed('timer', function() {
    return Ember.isPresent(this.get('timer'));
  }),

  schedule(context, f) {
    return Ember.run.later(this, function() {
      f.apply(context);
      this.start(context, f);
    }, this.get('interval'));
  },

  kill() {
    return Ember.run.cancel(this.get('timer'));
  },

  start(context, f) {
    this.set('timer', this.schedule(context, f));
  }
});

PolarBear.reopenClass({
  type: 'PolarBear'
});

export default PolarBear;

<|endoftext|>


<commit_before>import Mixin from '@ember/object/mixin';
import { computed } from '@ember/object';
import { get } from '@ember/object';

const bound = function(fnName) {
  return computed(fnName, function() {
    let fn = get(this, fnName);
    if (fn) { // https://github.com/zeppelin/ember-click-outside/issues/1
      return fn.bind(this);
    }
  });
};

const ios = () => {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
};

const documentOrBodyContains = (element) => {
  // https://github.com/zeppelin/ember-click-outside/issues/30
  if (typeof document.contains === 'function') {
    return document.contains(element);
  } else {
    document.body.contains(element);
  }
}

export default Mixin.create({
  clickOutside() {},
  clickHandler: bound('outsideClickHandler'),

  didInsertElement() {
    this._super(...arguments);

    if (!ios()) {
      return;
    }

    document.body.style.cursor = 'pointer';
  },

  willDestroyElement() {
    this._super(...arguments);

    if (!ios()) {
      return;
    }

    document.body.style.cursor = '';
  },

  outsideClickHandler(e) {
    const element = get(this, 'element');

    // Check if the click target still is in the DOM.
    // If not, there is no way to know if it was inside the element or not.
    const isRemoved = !e.target || !documentOrBodyContains(e.target);

    // Check the element is found as a parent of the click target.
    const isInside = element === e.target || element.contains(e.target);

    if (!isRemoved && !isInside) {
      this.clickOutside(e);
    }
  },

  addClickOutsideListener() {
    const clickHandler = get(this, 'clickHandler');
    document.addEventListener('click', clickHandler);
  },

  removeClickOutsideListener() {
    const clickHandler = get(this, 'clickHandler');
    document.removeEventListener('click', clickHandler);
  }
});
<commit_msg>Improve handling for dynamic content<commit_after>import Mixin from '@ember/object/mixin';
import { computed } from '@ember/object';
import { get } from '@ember/object';

const bound = function(fnName) {
  return computed(fnName, function() {
    let fn = get(this, fnName);
    if (fn) { // https://github.com/zeppelin/ember-click-outside/issues/1
      return fn.bind(this);
    }
  });
};

const ios = () => {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
};

export default Mixin.create({
  clickOutside() {},
  clickHandler: bound('outsideClickHandler'),

  didInsertElement() {
    this._super(...arguments);

    if (!ios()) {
      return;
    }

    document.body.style.cursor = 'pointer';
  },

  willDestroyElement() {
    this._super(...arguments);

    if (!ios()) {
      return;
    }

    document.body.style.cursor = '';
  },

  outsideClickHandler(e) {
    const isOnPath = e.path.includes(get(this, 'element'));

    if (!isOnPath) {
      this.clickOutside(e);
    }
  },

  addClickOutsideListener() {
    const clickHandler = get(this, 'clickHandler');
    document.addEventListener('click', clickHandler);
  },

  removeClickOutsideListener() {
    const clickHandler = get(this, 'clickHandler');
    document.removeEventListener('click', clickHandler);
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import Errors from 'ember-validations/errors';
import Base from 'ember-validations/validators/base';

var get = Ember.get;
var set = Ember.set;

var setValidityMixin = Ember.Mixin.create({
  isValid: Ember.computed('validators.@each.isValid', function() {
    var compactValidators = get(this, 'validators').compact();
    var filteredValidators = compactValidators.filter(function(validator) {
      return !get(validator, 'isValid');
    });

    return get(filteredValidators, 'length') === 0;
  }),
  isInvalid: Ember.computed.not('isValid')
});

var pushValidatableObject = function(model, property) {
  var content = get(model, property);

  model.removeObserver(property, pushValidatableObject);
  if (Ember.isArray(content)) {
    model.validators.pushObject(ArrayValidatorProxy.create({model: model, property: property, contentBinding: 'model.' + property}));
  } else {
    model.validators.pushObject(content);
  }
};

var lookupValidator = function(validatorName) {
  var container = get(this, 'container');
  var service = container.lookup('service:validations');
  var validators = [];
  var cache;

  if (service) {
    cache = get(service, 'cache');
  } else {
    cache = {};
  }

  if (cache[validatorName]) {
    validators = validators.concat(cache[validatorName]);
  } else {
    var local = container.lookupFactory('validator:local/'+validatorName);
    var remote = container.lookupFactory('validator:remote/'+validatorName);

    if (local || remote) { validators = validators.concat([local, remote]); }
    else {
      var base = container.lookupFactory('validator:'+validatorName);

      if (base) { validators = validators.concat([base]); }
      else {
        local = container.lookupFactory('ember-validations@validator:local/'+validatorName);
        remote = container.lookupFactory('ember-validations@validator:remote/'+validatorName);

        if (local || remote) { validators = validators.concat([local, remote]); }
      }
    }

    cache[validatorName] = validators;
  }

  if (Ember.isEmpty(validators)) {
    Ember.warn('Could not find the "'+validatorName+'" validator.');
  }

  return validators;
};

var ArrayValidatorProxy = Ember.ArrayProxy.extend(setValidityMixin, {
  validate: function() {
    return this._validate();
  },
  _validate: Ember.on('init', function() {
    var promises = get(this, 'content').invoke('_validate').without(undefined);
    return Ember.RSVP.all(promises);
  }),
  validators: Ember.computed.alias('content')
});

const mixin = Ember.Mixin.create(setValidityMixin, {
  init: function() {
    this._super();
    this.errors = Errors.create();
    this.dependentValidationKeys = {};
    this.validators = Ember.A();
    if (get(this, 'validations') === undefined) {
      this.validations = {};
    }
    this.buildValidators();
    this.validators.forEach(function(validator) {
      validator.addObserver('errors.[]', this, function(sender) {
        var errors = Ember.A();
        this.validators.forEach(function(validator) {
          if (validator.property === sender.property) {
            errors.addObjects(validator.errors);
          }
        }, this);
        set(this, 'errors.' + sender.property, errors);
      });
    }, this);
  },
  buildValidators: function() {
    var property;

    for (property in this.validations) {
      if (this.validations[property].constructor === Object) {
        this.buildRuleValidator(property);
      } else {
        this.buildObjectValidator(property);
      }
    }
  },
  buildRuleValidator: function(property) {
    var pushValidator = function(validator) {
      if (validator) {
        this.validators.pushObject(validator.create({model: this, property: property, options: this.validations[property][validatorName]}));
      }
    };

    if (this.validations[property].callback) {
      this.validations[property] = { inline: this.validations[property] };
    }

    var createInlineClass = function(callback) {
      return Base.extend({
        call: function() {
          var errorMessage = this.callback.call(this);

          if (errorMessage) {
            this.errors.pushObject(errorMessage);
          }
        },
        callback: callback
      });
    };

    for (var validatorName in this.validations[property]) {
      if (validatorName === 'inline') {
        pushValidator.call(this, createInlineClass(this.validations[property][validatorName].callback));
      } else if (this.validations[property].hasOwnProperty(validatorName)) {
        lookupValidator.call(this, validatorName).forEach(pushValidator, this);
      }
    }
  },
  buildObjectValidator: function(property) {
    if (Ember.isNone(get(this, property))) {
      this.addObserver(property, this, pushValidatableObject);
    } else {
      pushValidatableObject(this, property);
    }
  },
  validate: function() {
    var self = this;
    return this._validate().then(function(vals) {
      var errors = get(self, 'errors');
      if (vals.indexOf(false) > -1) {
        return Ember.RSVP.reject(errors);
      }
      return errors;
    });
  },
  _validate: Ember.on('init', function() {
    var promises = this.validators.invoke('_validate').without(undefined);
    return Ember.RSVP.all(promises);
  })
});

mixin[Ember.NAME_KEY]= 'ember-validations';
export default mixin;
<commit_msg>adding name to validity Mixin as it also appears in ember-inspector<commit_after>import Ember from 'ember';
import Errors from 'ember-validations/errors';
import Base from 'ember-validations/validators/base';

var get = Ember.get;
var set = Ember.set;

var setValidityMixin = Ember.Mixin.create({
  isValid: Ember.computed('validators.@each.isValid', function() {
    var compactValidators = get(this, 'validators').compact();
    var filteredValidators = compactValidators.filter(function(validator) {
      return !get(validator, 'isValid');
    });

    return get(filteredValidators, 'length') === 0;
  }),
  isInvalid: Ember.computed.not('isValid')
});
setValidityMixin[Ember.NAME_KEY]= 'ember-validations:validity';

var pushValidatableObject = function(model, property) {
  var content = get(model, property);

  model.removeObserver(property, pushValidatableObject);
  if (Ember.isArray(content)) {
    model.validators.pushObject(ArrayValidatorProxy.create({model: model, property: property, contentBinding: 'model.' + property}));
  } else {
    model.validators.pushObject(content);
  }
};

var lookupValidator = function(validatorName) {
  var container = get(this, 'container');
  var service = container.lookup('service:validations');
  var validators = [];
  var cache;

  if (service) {
    cache = get(service, 'cache');
  } else {
    cache = {};
  }

  if (cache[validatorName]) {
    validators = validators.concat(cache[validatorName]);
  } else {
    var local = container.lookupFactory('validator:local/'+validatorName);
    var remote = container.lookupFactory('validator:remote/'+validatorName);

    if (local || remote) { validators = validators.concat([local, remote]); }
    else {
      var base = container.lookupFactory('validator:'+validatorName);

      if (base) { validators = validators.concat([base]); }
      else {
        local = container.lookupFactory('ember-validations@validator:local/'+validatorName);
        remote = container.lookupFactory('ember-validations@validator:remote/'+validatorName);

        if (local || remote) { validators = validators.concat([local, remote]); }
      }
    }

    cache[validatorName] = validators;
  }

  if (Ember.isEmpty(validators)) {
    Ember.warn('Could not find the "'+validatorName+'" validator.');
  }

  return validators;
};

var ArrayValidatorProxy = Ember.ArrayProxy.extend(setValidityMixin, {
  validate: function() {
    return this._validate();
  },
  _validate: Ember.on('init', function() {
    var promises = get(this, 'content').invoke('_validate').without(undefined);
    return Ember.RSVP.all(promises);
  }),
  validators: Ember.computed.alias('content')
});

const mixin = Ember.Mixin.create(setValidityMixin, {
  init: function() {
    this._super();
    this.errors = Errors.create();
    this.dependentValidationKeys = {};
    this.validators = Ember.A();
    if (get(this, 'validations') === undefined) {
      this.validations = {};
    }
    this.buildValidators();
    this.validators.forEach(function(validator) {
      validator.addObserver('errors.[]', this, function(sender) {
        var errors = Ember.A();
        this.validators.forEach(function(validator) {
          if (validator.property === sender.property) {
            errors.addObjects(validator.errors);
          }
        }, this);
        set(this, 'errors.' + sender.property, errors);
      });
    }, this);
  },
  buildValidators: function() {
    var property;

    for (property in this.validations) {
      if (this.validations[property].constructor === Object) {
        this.buildRuleValidator(property);
      } else {
        this.buildObjectValidator(property);
      }
    }
  },
  buildRuleValidator: function(property) {
    var pushValidator = function(validator) {
      if (validator) {
        this.validators.pushObject(validator.create({model: this, property: property, options: this.validations[property][validatorName]}));
      }
    };

    if (this.validations[property].callback) {
      this.validations[property] = { inline: this.validations[property] };
    }

    var createInlineClass = function(callback) {
      return Base.extend({
        call: function() {
          var errorMessage = this.callback.call(this);

          if (errorMessage) {
            this.errors.pushObject(errorMessage);
          }
        },
        callback: callback
      });
    };

    for (var validatorName in this.validations[property]) {
      if (validatorName === 'inline') {
        pushValidator.call(this, createInlineClass(this.validations[property][validatorName].callback));
      } else if (this.validations[property].hasOwnProperty(validatorName)) {
        lookupValidator.call(this, validatorName).forEach(pushValidator, this);
      }
    }
  },
  buildObjectValidator: function(property) {
    if (Ember.isNone(get(this, property))) {
      this.addObserver(property, this, pushValidatableObject);
    } else {
      pushValidatableObject(this, property);
    }
  },
  validate: function() {
    var self = this;
    return this._validate().then(function(vals) {
      var errors = get(self, 'errors');
      if (vals.indexOf(false) > -1) {
        return Ember.RSVP.reject(errors);
      }
      return errors;
    });
  },
  _validate: Ember.on('init', function() {
    var promises = this.validators.invoke('_validate').without(undefined);
    return Ember.RSVP.all(promises);
  })
});

mixin[Ember.NAME_KEY]= 'ember-validations';
export default mixin;
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Object.extend({
  name: 'normal',
  retryOnFailureDelay: 10000,
  delay: 5000,
  workers: 5,
  activeJobs: Ember.A(),
  pendingJobs: Ember.A(),
  faltureJobs: Ember.A(),
  retryJobs: Ember.A(),

  init: function(){
    return this._super();
  },

  runJob(job){
    this.get('activeJobs').pushObject(job);
    Ember.run.later(() => {
      this.process(job);
    }, this.get('delay'));
  },

  isJobExist(job){
    let pendingJob = this.get('pendingJobs').find((item) => {
      return item.get('adapter') === job.get('adapter') && item.get('method') === job.get('method');
    });
    let retryJob =  this.get('retryJobs').find((item) => {
      return item.get('adapter') === job.get('adapter') && item.get('method') === job.get('method');
    });
    return pendingJob || retryJob;
  },

  pendingJobObserver: Ember.on('init', Ember.observer('pendingJobs.length',function(){
    if (this.get('pendingJobs.length')<= 0){
      return;
    }
    if (this.get('activeJobs').length < this.get('workers')){
      let job = this.get('pendingJobs').pop();
      if (job){
        this.runJob(job);
      }
    }
  })),

  add: function(job){
    if (!this.isJobExist(job)){
      this.get('pendingJobs').pushObject(job);
    }
  },

  remove: function(job){
    this.get('pendingJobs').removeObject(job);
  },

  process: function(job){
    console.log('process');
      let queue = this;
      job.perform().then(() => {
        this.get('activeJobs').removeObject(job);
        this.get('retryJobs').removeObject(job);
      }, () => {
        this.get('activeJobs').removeObject(job);
        queue.get('retryJobs').removeObject(job);

        if (job.get('needRetry')){
          job.decrementProperty('retryCount');
          queue.get('retryJobs').pushObject(job);
          Ember.run.later(() => {
            console.log('retry');

            queue.process(job);
          }, queue.get('retryOnFailureDelay'));
        }
        else{
          queue.get('retryJobs').removeObject(job);
          queue.get('faltureJobs').pushObject(job);
        }
      });
  }
});
<commit_msg>fix tests<commit_after>import Ember from 'ember';

export default Ember.Object.extend({
  name: 'normal',
  retryOnFailureDelay: 10000,
  delay: 5000,
  workers: 5,
  activeJobs: Ember.A(),
  pendingJobs: Ember.A(),
  faltureJobs: Ember.A(),
  retryJobs: Ember.A(),

  init: function(){
    return this._super();
  },

  runJob(job){
    this.get('activeJobs').pushObject(job);
    this.process(job);
    Ember.run.later(() => {
      this.process(job);
    }, this.get('delay'));
  },

  isJobExist(job){
    let pendingJob = this.get('pendingJobs').find((item) => {
      return item.get('adapter') === job.get('adapter') && item.get('method') === job.get('method');
    });
    let retryJob =  this.get('retryJobs').find((item) => {
      return item.get('adapter') === job.get('adapter') && item.get('method') === job.get('method');
    });
    return pendingJob || retryJob;
  },

  pendingJobObserver: Ember.on('init', Ember.observer('pendingJobs.[]',function(){
    if (this.get('pendingJobs.length')<= 0){
      return;
    }
    if (this.get('activeJobs').length < this.get('workers')){
      let job = this.get('pendingJobs').pop();
      if (job){
        this.runJob(job);
      }
    }
  })),

  add: function(job){
    if (!this.isJobExist(job)){
      this.get('pendingJobs').pushObject(job);
    }
  },

  remove: function(job){
    this.get('pendingJobs').removeObject(job);
  },

  process: function(job){
      let queue = this;
      job.perform().then(() => {
        this.get('activeJobs').removeObject(job);
        this.get('retryJobs').removeObject(job);
      }, () => {
        this.get('activeJobs').removeObject(job);
        queue.get('retryJobs').removeObject(job);

        if (job.get('needRetry')){
          job.decrementProperty('retryCount');
          queue.get('retryJobs').pushObject(job);
          Ember.run.later(() => {
            queue.process(job);
          }, queue.get('retryOnFailureDelay'));
        }
        else{
          queue.get('retryJobs').removeObject(job);
          queue.get('faltureJobs').pushObject(job);
        }
      });
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import ModelMeta from './model-meta';

/** computed property function for relation fields
 */
var _relationCPFunction = function(fieldMeta) {
    var relationComputedFunction;
    var fieldName = fieldMeta.get('name');

    // deals with multi relation field
    if (fieldMeta.get('isMulti')) {

        // "this" represents the model
        relationComputedFunction = function(key, value) {
            // setter
            if (arguments.length === 2) {
                this.setField(fieldName, value);
                return value;
            }

            // getter
            var db = this.get('meta.store.db');
            var val = this.get('content.'+fieldName);
            if (val && val.length) {
                var relationIds = this.get('content.'+fieldName).mapBy('_id');
                var relationType = this.get('meta.'+fieldName+'Field.type');
                return db[relationType].find({_id: {$in: relationIds}});
            }
        }.property('content.'+fieldName);

    } else {

        // "this" represents the model
        relationComputedFunction = function(key, value) {

            // getter
            if (arguments.length === 2) {
                this.setField(fieldName, value);
                return value;
            }

            // getter
            var db = this.get('meta.store.db');
            var relationId = this.get('content.'+fieldName+'._id');
            if (relationId) {
                var relationType = this.get('meta.'+fieldName+'Field.type');
                return db[relationType].first({_id: relationId});
            }
        }.property('content.'+fieldName);
    }
    return relationComputedFunction;
};

/** computed property function for regular fields
 */
var _regularCPFunction = function(fieldMeta) {

    // building the computed property function
    // "this" represents the model
    var fieldName = fieldMeta.get('name');
    var isBoolean = fieldMeta.get('isBoolean');
    var fieldComputedFunction = function(key, value) {

        // getter
        if (arguments.length === 1) {
            var val = this.get('content.'+fieldName);
            if (isBoolean) {
                val = !!val;
            }
            return val;

        // setter
        } else {
            if (isBoolean) {
                value = !!value;
            } else if (value === '') {
                value = undefined;
            }
            this.setField(fieldName, value);
            return value;
        }
    }.property('content.'+fieldName);

    return fieldComputedFunction;
};

/** A store is like a model instance factory.
 *  Its purpose is to deal with the stored data
 */
export default Ember.Object.extend({
    db: null,
    resource: null,
    modelClass: null,
    resourceStructure: null,

    /** build computed property for all structure's fields
     * If the field is a relation field, the computed property will
     * return a promise, otherwise, the value from the content
     */
    _buildComputedPropertiesFromStructure: function() {
        var computedProperties = {};
        var computedFunction;
        var modelClass = this.get('modelClass');
        var that = this;
        this.get('modelMeta.fieldNames').forEach(function(fieldName) {

            /** check if the computed property has not already been
             * defined by the developper.
             */
            var skip;
            try {
                skip = modelClass.metaForProperty(fieldName);
            } catch (e) {
                skip = false;
            }

            // set the function
            if (!skip) {

                var fieldMeta = that.get('modelMeta.'+fieldName+'Field');
                if (fieldMeta.get('isRelation')) {
                    computedFunction = _relationCPFunction(fieldMeta);
                } else {
                    computedFunction = _regularCPFunction(fieldMeta);
                }

                computedProperties[fieldName] = computedFunction;
            }
        });
        // update the model class
        modelClass.reopen(computedProperties);
    },

    resourceEndpoint: function() {
        var db = this.get('db');
        var resource = this.get('resource');
        var underscoredModelType = resource.underscore();
        return db.get('endpoint')+'/'+underscoredModelType;
    }.property('resource'),

    modelMeta: function() {
        var resource = this.get('resource');
        var resourceStructure = this.get('resourceStructure');
        return ModelMeta.create({
            resource: resource,
            store: this,
            content: resourceStructure
        });
    }.property('resource'),

    createRecord: function(record) {
        if (record === undefined) {
            record = {};
        }
        record = Ember.Object.create(record);
        var modelMeta = this.get('modelMeta');
        return this.get('modelClass').create({
            content: record,
            meta: modelMeta
        });
    },

    first: function(query) {
        query = query || {};
        if (!query._id) {
            console.log('!!!! no id', query);
            return this.createRecord({});
        }
        query._limit = 1;

        var that = this;
        var resourceEndpoint = this.get('resourceEndpoint');

        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data){
                    var record;
                    var content = {};
                    // if there is a match, we wrap all relations with Model objects
                    if (data.results.length > 0) {
                        content = data.results[0];
                    }
                    // build the model
                    record = that.createRecord(content);
                    return resolve(record);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });
        return Ember.ObjectProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    find: function(query) {
        if (!query) {
            query = {};
        }
        var resourceEndpoint = this.get('resourceEndpoint');
        var that = this;

        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data) {
                    var results = Ember.A(); // TODO switch to Collection.create(data);
                    var record;
                    data.results.forEach(function(item) {
                        record = that.createRecord(item);
                        results.pushObject(record);
                    });
                    return resolve(results);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });

        return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    groupBy: function(field, query) {
        if (!field) {
            console.error('field is required');
        }

        if(!query) {
            query = {};
        }
        var resourceEndpoint = this.get('resourceEndpoint')+'/facets/'+field;

        var that = this;
        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data) {
                    var results = Ember.A(); // TODO switch to Collection.create(data);
                    // var record;
                    data.results.forEach(function(item) {
                        // record = that.first({_id: item.facet});
                        // record.then(function(arf) {
                        //     console.log(arf);
                        // });
                        results.pushObject(item);
                    });
                    return resolve(results);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });

        return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    count: function(query) {
        if (!query) {
            query = {};
        }
        var resourceEndpoint = this.get('resourceEndpoint')+'/count';

        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data) {
                    return resolve(data);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });

        return promise;
    },

    sync: function(pojo) {
        var resourceEndpoint = this.get('resourceEndpoint');
        var postData = {payload: JSON.stringify(pojo)};
        var that = this;
        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                type: 'post',
                async: true,
                data: postData,
                success: function(data) {
                    var record = that.createRecord(data.object);
                    resolve(record);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });
        return Ember.ObjectProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    delete: function(recordId) {
        var resourceEndpoint = this.get('resourceEndpoint');
        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                url: resourceEndpoint+'/'+recordId,
                type: 'delete',
                async: true,
                success: function(data) {
                    resolve(data);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });
        return promise;
    }

});
<commit_msg>add stream function<commit_after>import Ember from 'ember';
import ModelMeta from './model-meta';

/** computed property function for relation fields
 */
var _relationCPFunction = function(fieldMeta) {
    var relationComputedFunction;
    var fieldName = fieldMeta.get('name');

    // deals with multi relation field
    if (fieldMeta.get('isMulti')) {

        // "this" represents the model
        relationComputedFunction = function(key, value) {
            // setter
            if (arguments.length === 2) {
                this.setField(fieldName, value);
                return value;
            }

            // getter
            var db = this.get('meta.store.db');
            var val = this.get('content.'+fieldName);
            if (val && val.length) {
                var relationIds = this.get('content.'+fieldName).mapBy('_id');
                var relationType = this.get('meta.'+fieldName+'Field.type');
                return db[relationType].find({_id: {$in: relationIds}});
            }
        }.property('content.'+fieldName);

    } else {

        // "this" represents the model
        relationComputedFunction = function(key, value) {

            // getter
            if (arguments.length === 2) {
                this.setField(fieldName, value);
                return value;
            }

            // getter
            var db = this.get('meta.store.db');
            var relationId = this.get('content.'+fieldName+'._id');
            if (relationId) {
                var relationType = this.get('meta.'+fieldName+'Field.type');
                return db[relationType].first({_id: relationId});
            }
        }.property('content.'+fieldName);
    }
    return relationComputedFunction;
};

/** computed property function for regular fields
 */
var _regularCPFunction = function(fieldMeta) {

    // building the computed property function
    // "this" represents the model
    var fieldName = fieldMeta.get('name');
    var isBoolean = fieldMeta.get('isBoolean');
    var fieldComputedFunction = function(key, value) {

        // getter
        if (arguments.length === 1) {
            var val = this.get('content.'+fieldName);
            if (isBoolean) {
                val = !!val;
            }
            return val;

        // setter
        } else {
            if (isBoolean) {
                value = !!value;
            } else if (value === '') {
                value = undefined;
            }
            this.setField(fieldName, value);
            return value;
        }
    }.property('content.'+fieldName);

    return fieldComputedFunction;
};

/** A store is like a model instance factory.
 *  Its purpose is to deal with the stored data
 */
export default Ember.Object.extend({
    db: null,
    resource: null,
    modelClass: null,
    resourceStructure: null,

    /** build computed property for all structure's fields
     * If the field is a relation field, the computed property will
     * return a promise, otherwise, the value from the content
     */
    _buildComputedPropertiesFromStructure: function() {
        var computedProperties = {};
        var computedFunction;
        var modelClass = this.get('modelClass');
        var that = this;
        this.get('modelMeta.fieldNames').forEach(function(fieldName) {

            /** check if the computed property has not already been
             * defined by the developper.
             */
            var skip;
            try {
                skip = modelClass.metaForProperty(fieldName);
            } catch (e) {
                skip = false;
            }

            // set the function
            if (!skip) {

                var fieldMeta = that.get('modelMeta.'+fieldName+'Field');
                if (fieldMeta.get('isRelation')) {
                    computedFunction = _relationCPFunction(fieldMeta);
                } else {
                    computedFunction = _regularCPFunction(fieldMeta);
                }

                computedProperties[fieldName] = computedFunction;
            }
        });
        // update the model class
        modelClass.reopen(computedProperties);
    },

    resourceEndpoint: function() {
        var db = this.get('db');
        var resource = this.get('resource');
        var underscoredModelType = resource.underscore();
        return db.get('endpoint')+'/'+underscoredModelType;
    }.property('resource'),

    modelMeta: function() {
        var resource = this.get('resource');
        var resourceStructure = this.get('resourceStructure');
        return ModelMeta.create({
            resource: resource,
            store: this,
            content: resourceStructure
        });
    }.property('resource'),

    createRecord: function(record) {
        if (record === undefined) {
            record = {};
        }
        record = Ember.Object.create(record);
        var modelMeta = this.get('modelMeta');
        return this.get('modelClass').create({
            content: record,
            meta: modelMeta
        });
    },

    first: function(query) {
        query = query || {};
        if (!query._id) {
            console.log('!!!! no id', query);
            return this.createRecord({});
        }
        query._limit = 1;

        var that = this;
        var resourceEndpoint = this.get('resourceEndpoint');

        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data){
                    var record;
                    var content = {};
                    // if there is a match, we wrap all relations with Model objects
                    if (data.results.length > 0) {
                        content = data.results[0];
                    }
                    // build the model
                    record = that.createRecord(content);
                    return resolve(record);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });
        return Ember.ObjectProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    find: function(query) {
        if (!query) {
            query = {};
        }
        var resourceEndpoint = this.get('resourceEndpoint');
        var that = this;

        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data) {
                    var results = Ember.A(); // TODO switch to Collection.create(data);
                    var record;
                    data.results.forEach(function(item) {
                        record = that.createRecord(item);
                        results.pushObject(record);
                    });
                    return resolve(results);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });

        return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    /** stream
     * Use `stream` if you want to fetch a lot of data.
     * `stream` is like `find` but can fetch thousand of records
     * while `find` is faster to retreive tens of records
     */
    stream: function(query) {
        if (!query) {
            query = {};
        }
        var resourceEndpoint = this.get('resourceEndpoint');
        var that = this;

        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint+'/export/json',
                async: true,
                data: query,
                success: function(data) {
                    return resolve(data);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });

        return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    groupBy: function(field, query) {
        if (!field) {
            console.error('field is required');
        }

        if(!query) {
            query = {};
        }
        var resourceEndpoint = this.get('resourceEndpoint')+'/facets/'+field;

        var that = this;
        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data) {
                    var results = Ember.A(); // TODO switch to Collection.create(data);
                    // var record;
                    data.results.forEach(function(item) {
                        // record = that.first({_id: item.facet});
                        // record.then(function(arf) {
                        //     console.log(arf);
                        // });
                        results.pushObject(item);
                    });
                    return resolve(results);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });

        return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    count: function(query) {
        if (!query) {
            query = {};
        }
        var resourceEndpoint = this.get('resourceEndpoint')+'/count';

        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                async: true,
                data: query,
                success: function(data) {
                    return resolve(data);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });

        return promise;
    },

    sync: function(pojo) {
        var resourceEndpoint = this.get('resourceEndpoint');
        var postData = {payload: JSON.stringify(pojo)};
        var that = this;
        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                dataType: "json",
                url: resourceEndpoint,
                type: 'post',
                async: true,
                data: postData,
                success: function(data) {
                    var record = that.createRecord(data.object);
                    resolve(record);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });
        return Ember.ObjectProxy.extend(Ember.PromiseProxyMixin).create({
            promise: promise
        });
    },

    delete: function(recordId) {
        var resourceEndpoint = this.get('resourceEndpoint');
        var promise = new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                url: resourceEndpoint+'/'+recordId,
                type: 'delete',
                async: true,
                success: function(data) {
                    resolve(data);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    console.log('errror>', jqXHR, textStatus, errorThrown);
                    reject(jqXHR.responseJSON);
                }
            });
        });
        return promise;
    }

});
<|endoftext|>


<commit_before>
import hljs from 'highlight.js';

export default function highlight(selector = 'pre code') {
  const codeBlocks = document.querySelectorAll(selector);

  Array.prototype.forEach.call(codeBlocks, (codeBlock) => {
    const block = codeBlock;
    let html = block.innerHTML;
    html = html.replace(/<!--([^>]+-->)/g, '');
    html = format(html);
    html = html.replace(/^\r?\n/g, '');

    block.textContent = html;

    hljs.highlightBlock(block);

    block.addEventListener('dblclick', () => {
      copyToClipboard(html);

      block.parentNode.parentNode.classList.add('blink');
      setTimeout(() => {
        block.parentNode.parentNode.classList.remove('blink');
      }, 400);
    });
  });
}

function indentation(level) {
  let result = '';
  let i = level * 2;

  if (level < 0) { throw new Error('Level is below 0'); }

  while (i !== 0) {
    i -= 1;
    result += ' ';
  }

  return result;
}

function format(html) {
  const tokens = html.trim().split(/</);
  let result = '';
  let indentLevel = 0;

  for (let i = 0, l = tokens.length; i < l; i += 1) {
    const parts = tokens[i].split(/>/);

    if (parts.length === 2) {
      if (tokens[i][0] === '/') { indentLevel -= 1; }
      result += indentation(indentLevel);

      if (tokens[i][0] !== '/') { indentLevel += 1; }
      if (i > 0) { result += '<'; }
      result += `${parts[0].trim()}>\n`;

      if (parts[1].trim() !== '') { result += `${indentation(indentLevel) + parts[1].trim().replace(/\s+/g, ' ')}\n`; }
      if (parts[0].match(/^(img|hr|br|input)/)) { indentLevel -= 1; }
    } else {
      result += `${indentation(indentLevel) + parts[0]}\n`;
    }
  }

  return result;
}

function copyToClipboard(content) {
  const textarea = document.createElement('textarea');
  textarea.innerHTML = content;
  document.body.appendChild(textarea);

  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}
<commit_msg>Update highlight.js<commit_after>
import hljs from 'highlight.js';

export default function highlight(selector = 'pre code') {
  const codeBlocks = document.querySelectorAll(selector);

  Array.prototype.forEach.call(codeBlocks, (codeBlock) => {
    const block = codeBlock;
    let html = block.innerHTML;
    html = html.replace(/<!--([^>]+-->)/g, '');
    html = format(html);
    html = html.replace(/^\r?\n/g, '');

    block.textContent = html;

    hljs.highlightBlock(block);

    block.addEventListener('dblclick', () => {
      copyToClipboard(html);

      block.parentNode.parentNode.classList.add('blink');
      setTimeout(() => {
        block.parentNode.parentNode.classList.remove('blink');
      }, 400);
    });
  });
}

function indentation(level) {
  let result = '';
  let i = level * 2;

  if (level < 0) { throw new Error('Level is below 0'); }

  while (i !== 0) {
    i -= 1;
    result += ' ';
  }

  return result;
}

function format(html) {
  const tokens = html.trim().split(/</);
  let result = '';
  let indentLevel = 0;

  for (let i = 0, l = tokens.length; i < l; i += 1) {
    const parts = tokens[i].split(/>/);

    if (parts.length === 2) {
      if (tokens[i][0] === '/') { indentLevel -= 1; }
      result += indentation(indentLevel);

      if (tokens[i][0] !== '/') { indentLevel += 1; }
      if (i > 0) { result += '<'; }
      result += `${parts[0].trim()}>\n`;

      if (parts[1].trim() !== '') { result += `${indentation(indentLevel) + parts[1].trim().replace(/\s+/g, ' ')}\n`; }
      if (parts[0].match(/^(img|hr|br|input|source|meta)/)) { indentLevel -= 1; }
    } else {
      result += `${indentation(indentLevel) + parts[0]}\n`;
    }
  }

  return result;
}

function copyToClipboard(content) {
  const textarea = document.createElement('textarea');
  textarea.innerHTML = content;
  document.body.appendChild(textarea);

  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}
<|endoftext|>


<commit_before>(function(angular) {

	var module = angular.module('net.enzey.nobind', []);

	var ctrlBind = function($parse) {
		return function($scope) {
			var resolveValueWithoutWatching = function(varExpression, func) {
				// varExpression.exp is passed as the 'old' value
				//   so that angular can remove the expression text from an
				//   element's attributes, such as when using an expression for the class.
				if (!func && typeof varExpression === 'function') {
					varExpression();
				} else {
					func($parse(varExpression)(this), varExpression.exp);
				}
			};
			$scope.$watch = resolveValueWithoutWatching;
			$scope.$watchCollection = resolveValueWithoutWatching;
		};
	};

	var linkBind = function($timeout) {
		return function(scope, element, attrs) {
			element.find('*').removeClass('ng-binding');
			$timeout(function() {
				scope.$destroy();
			}, 0, false);
		};
	};

	module.directive('nzNoBind', function ($parse, $timeout) {
		return {
			restrict: 'A',
			priority: 999999,
			scope: true,
			controller: ctrlBind($parse),
			link: function(scope, element, attrs) {
				element.removeClass('ng-scope');
				element.removeClass('ng-binding');
				linkBind($timeout)(scope, element, attrs);
			}
		};
	});

	module.directive('nzNoBindChildren', function ($parse, $timeout) {
		return {
			restrict: 'A',
			priority: -999999,
			scope: true,
			controller: ctrlBind($parse),
			link: linkBind($timeout)
		};
	});

})(angular);<commit_msg>Fix no-bind-children and scope vars being resolved in a promise.<commit_after>(function(angular) {

	var timeoutWait = 100;
	var destroyParam = 'noBind-DestroyMe';

	var module = angular.module('net.enzey.nobind', []);

	var ctrlBind = function($parse, $timeout) {
		return function($scope) {
			var realWatch = $scope.$watch;
			var resolveValueWithoutWatching = function(varExpression, func) {
				var workingScope = this;
				// varExpression.exp is passed as the 'old' value
				//   so that angular can remove the expression text from an
				//   element's attributes, such as when using an expression for the class.
				if (!func && typeof varExpression === 'function') {
					varExpression();
				} else {
					var resolvedVal = $parse(varExpression)(workingScope);
					if (resolvedVal === null || resolvedVal === undefined || resolvedVal === 0) {
						// Value is not set, wait for it to be set.
						$timeout(function() {
							resolveValueWithoutWatching.apply(workingScope, [varExpression, func]);
						}, timeoutWait, false);
					} else {
							func(resolvedVal, varExpression.exp);
							$scope[destroyParam] = true
					}
				}
			};
			var watchButDestroy = function(varExp, func) {
				var watchDestroyFunc;
				watchDestroyFunc = realWatch(varExp, function(arg1, arg2) {
					func(arg1, arg2);
				});
			};
			$scope.$watch = resolveValueWithoutWatching;
		};
	};

	var destroyTheScope = function($timeout, scope) {
		var scopeDestroyFn = function() {
			if (scope[destroyParam]) {
				$timeout(function() {
					scope.$destroy();
				}, 0, true);
			}
			else {
				$timeout(scopeDestroyFn, timeoutWait, false);
			}
		};
		scopeDestroyFn();
	};

	module.directive('nzNoBind', function ($parse, $timeout) {
		return {
			restrict: 'A',
			priority: 999999,
			scope: true,
			controller: ctrlBind($parse, $timeout),
			link: {
				pre: function(scope, element, attrs) {
				},
				post: function(scope, element, attrs) {
					element.removeClass('ng-binding');
					element.removeClass('ng-scope');
					element.find('*').removeClass('ng-binding');
					element.find('*').removeClass('ng-scope');

					destroyTheScope($timeout, scope);
				}
			}
		};
	});

	module.directive('nzNoBindChildren', function ($parse, $timeout, $compile) {
		return {
			restrict: 'A',
			priority: 999999,
			compile: function($element, $attrs) {

				var nestedHtml = $element[0].innerHTML;
				$element.empty();

				var childScope;
				return {
					pre: function(scope, element, attrs) {
						// Create child scope
						childScope = scope.$new();
						// Apply controller to scope
						ctrlBind($parse, $timeout)(childScope);

						var childElements = $compile('<div>' + nestedHtml + '</div>')(childScope).children();
						element.append(childElements);
					},
					post: function(scope, element, attrs) {
						element.find('*').removeClass('ng-binding');
						element.find('*').removeClass('ng-scope');

						destroyTheScope($timeout, childScope);
					}
				}
			}
		};
	});

})(angular);<|endoftext|>


<commit_before>// ==UserScript==
// @name         kafene-pinboard-style
// @namespace    0c2982529348
// @copyright    2012, kafene.org
// @license      MIT
// @include      http://pinboard.in/*
// @include      https://pinboard.in/*
// @include      http://www.pinboard.in/*
// @include      https://www.pinboard.in/*
// @match        http://*.pinboard.in/*
// @match        https://*.pinboard.in/*
// @run-at       document-start
// ==/UserScript==
/*jshint multistr:true */
window.addEventListener('load', function() {
    var heredoc = function(f) {
        var ret = f.toString();
        ret = ret.replace(/^[^\/]+\/\*!?/, '');
        ret = ret.replace(/\*\/[^\/]+$/, '');
        return ret;
    };
    var css = heredoc(function(){/*
* { box-sizing:border-box !important; max-width:100% !important; font-size:9pt; }
body, #pinboard, #content { width:100%; padding:0; margin:0; color:#333; }
body { overflow-y:scroll; background:#fff; }
.star { margin-left:-20px; }
.bookmark:not(.private) .star { margin-left:-25px; }
body, .display .description, .display a { font:9pt/1.3em 'Segoe UI', 'Droid Sans', sans-serif; }
a:not([onmouseover*='this.style']):hover { text-decoration:underline; }
#banner { display:block; padding:4px 10px; height:auto; width:100%; border-bottom:1px solid #ccc; background:#eee; margin-bottom:2em; }
#banner a:not(#pinboard_name), a.bookmark_title { color:#11a !important; }
#banner a#pinboard_name { color:#333 !important; }
#main_column, #profile_main_column { margin:0; padding:0 5% 0 5%; width:65%; min-height:500px !important; white-space:nowrap; }
#main_column #bookmarks { white-space:normal; }
.edit_checkbox { margin:7px 0 0 -40px; }
.display, .bookmark, #bulk_edit_box { padding:0; width:100%; margin:0; }
.bookmark { margin:0.5em 0 0 0; padding:0 0 0.5em 0; border-bottom:1px solid #eee !important; }
.bookmark.private { background:transparent !important; border:0; }
.bookmark:not(.private) { background:#eee; border:1px solid #ccc !important; padding:0.25em; }
.bookmark:not(.private) .edit_links:after { margin:0 0.25em; content:' public '; color:#c66 !important; font-weight:400; position:relative; }
.edit_links a.edit { color:#999 !important; }
a.bookmark_title { font-size:110%; line-height:100%; display:table; margin-bottom:0.25em; }
a.selected, a.unread { font-weight:bold; }
a.tag { line-height:1 !important; color:#990000 !important; }
a.url_link { padding:0 4px; border-radius:3px; }
.display a { line-height:1; }
.bookmark_count_box { white-space:nowrap; }
a.bookmark_count { padding-right:0.5em; }
.display br, #edit_bookmark_form p, #timer { display:none !important; }
.display .description a { color:#445588; }
.display .description { margin:0 0 0.25em 0; font-family:'Consolas', 'Droid Sans Mono', monospace; line-height:1.25em !important; white-space:pre-wrap; }
.display a[href^='/u:']:not([href*='t:']) { color:#333; }
.description blockquote { font-family:'Consolas', 'Droid Sans Mono', monospace; margin:0.5em; color:#333; }
#right_bar, #tag_cloud { margin:0; padding:0; float:left; width:30%; }
#right_bar #tag_cloud { width:100%; margin:0; }
.tag_table { margin:0; width:50%; }
#tag_cloud a { line-height:130% !important; font-size:100% !important; }
form[action='/add'], form[action='/add'] table { padding:0.5em; width:100%; }
form[action='/add'] input[type='text'], form[action='/add'] textarea { width:100%; }
.pin-ac { margin-top:-2px; }
#popup_header { margin:0.25em 0.5em; }
#edit_bookmark_form { width:100%; background:#ddd; border:1px solid #aaa; padding:0.5em; }
.edit_form_input { border:1px solid #aaa !important; margin:0; line-height:120%; }
#edit_form_checkboxes { margin:0.5em 0; }
textarea.edit_form_input { width:100%; margin:0.25em 0; height:12em; }
#footer { margin-bottom:1em; }
#main_column > form > table, textarea[name="note"] { width:100%; }
a.copy_link { display:none; }
*/});
    var style = document.createElement('style');
    style.innerHTML = css;
    var el = document.head || document.documentElement;
    el.appendChild(style);
});
<commit_msg>Delete kafene-pinboard-style.user.js<commit_after><|endoftext|>