<commit_before>/*
 * Copyright (c) 2013-2014 Chukong Technologies Inc.
 *
 * 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.
 */

//
// Javascript Bindigns helper file
//

// DO NOT ALTER THE ORDER
require('jsb_cocos2d_constants.js');
require('jsb_cocos2d.js');
require('jsb_cocos2d_extension.js');
require('jsb_cocos2d_studio.js');
require('jsb_cocos2d_ui.js');
require('jsb_property_impls.js');
require('jsb_property_apis.js');
require('jsb_create_apis.js');
require('jsb_chipmunk_constants.js');
require('jsb_chipmunk.js');
require('jsb_opengl_constants.js');
require('jsb_opengl.js');
require('jsb_cocosbuilder.js');
require('jsb_deprecated.js');
require('jsb_loaders.js');
<commit_msg>Feature #5027: Add pluginx js script<commit_after>/*
 * Copyright (c) 2013-2014 Chukong Technologies Inc.
 *
 * 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.
 */

//
// Javascript Bindigns helper file
//

// DO NOT ALTER THE ORDER
require('jsb_cocos2d_constants.js');
require('jsb_cocos2d.js');
require('jsb_cocos2d_extension.js');
require('jsb_cocos2d_studio.js');
require('jsb_cocos2d_ui.js');
require('jsb_property_impls.js');
require('jsb_property_apis.js');
require('jsb_create_apis.js');
require('jsb_chipmunk_constants.js');
require('jsb_chipmunk.js');
require('jsb_opengl_constants.js');
require('jsb_opengl.js');
require('jsb_cocosbuilder.js');
require('jsb_pluginx.js');
require('jsb_deprecated.js');
require('jsb_loaders.js');
<|endoftext|>


<commit_before>window.ChannelItemView = Backbone.View.extend({
  tagName: "li",

  events: {
    "click" : "clickHandler"
  },

  initialize: function() {
    this.model.bind('change', this.render, this);
    this.model.bind('destroy', this.remove, this);
    this.model.bind('remove', this.remove, this);
    this.model.bind('loading', this.setLoading, this);
    this.model.bind('loaded', this.stopLoading, this);
    this.model.bind('activate', this.setActive, this);
    this.model.bind('deactivate', this.setNotActive, this);
  },

  render: function() {
    this.$( this.el )
      .html( $.mustache($('#channel_li').html(), this.model.toJSON() ))
      .attr('id', 'channel-' + this.model.id);
    return this;
  },

  setActive: function() {
    this.$( this.el ).addClass('active');
  },
  setNotActive: function() {
    this.$( this.el ).removeClass('active');
  },

  setLoading: function() {
    this.$( this.el ).addClass('loading');
  },

  stopLoading: function() {
    this.$( this.el ).removeClass('loading');
  },

  setVisible: function() {
    this.$( this.el ).addClass("visible");
  },

  setHidden: function() {
    this.$( this.el ).removeClass("visible");
  },

  remove: function() {
    this.$( this.el ).remove();
  },

  clickHandler: function( e ) {
    Router.navigate(Router.getUsername() + "/channels/" + this.model.id + "/facts", true);

    this.model.set({new_facts: false});

    e.preventDefault();
  }
});
<commit_msg>Fixed a bug where navigate would follow the route twice (& call all methods twice)<commit_after>window.ChannelItemView = Backbone.View.extend({
  tagName: "li",

  events: {
    "click" : "clickHandler"
  },

  initialize: function() {
    this.model.bind('change', this.render, this);
    this.model.bind('destroy', this.remove, this);
    this.model.bind('remove', this.remove, this);
    this.model.bind('loading', this.setLoading, this);
    this.model.bind('loaded', this.stopLoading, this);
    this.model.bind('activate', this.setActive, this);
    this.model.bind('deactivate', this.setNotActive, this);
  },

  render: function() {
    this.$( this.el )
      .html( $.mustache($('#channel_li').html(), this.model.toJSON() ))
      .attr('id', 'channel-' + this.model.id);
    return this;
  },

  setActive: function() {
    this.$( this.el ).addClass('active');
  },
  setNotActive: function() {
    this.$( this.el ).removeClass('active');
  },

  setLoading: function() {
    this.$( this.el ).addClass('loading');
  },

  stopLoading: function() {
    this.$( this.el ).removeClass('loading');
  },

  setVisible: function() {
    this.$( this.el ).addClass("visible");
  },

  setHidden: function() {
    this.$( this.el ).removeClass("visible");
  },

  remove: function() {
    this.$( this.el ).remove();
  },

  clickHandler: function( e ) {
    // Nasty fix, previously we used triggerRoute = true here, to make sure the
    // route gets triggered, but somehow this called the Router twice.
    // @TODO read-later: http://lostechies.com/derickbailey/2011/08/28/dont-execute-a-backbone-js-route-handler-from-your-code/
    Router.navigate(Router.getUsername() + "/channels/" + this.model.id);
    Router.getChannelFacts(Router.getUsername(), this.model.id);

    this.model.set({new_facts: false});

    e.preventDefault();
  }
});
<|endoftext|>


<commit_before>var PipeStream = require('pipestream');
var url = require('url');
var https = require('https');
var http = require('http');
var util = require('../../util');
var config = util.config;

module.exports = function(req, res, next) {
	PipeStream.wrap(req);
	PipeStream.wrap(res, true);

	var clientReq, clientRes, errorEmitted;
	var reqTransform, resTransform;
	req.on('dest', function(_req) {
		clientReq = _req.on('error', onReqError);
	}).on('error', onReqError);
	res.on('src', function(_res) {
		clientRes = _res.on('error', onResError);
	}).on('error', onResError);

	function onReqError(err) {
		onError(reqTransform, err);
	}

	function onResError(err) {
		onError(resTransform, err);
	}

	function onError(obj, err) {
		if (errorEmitted) {
			return;
		}
		errorEmitted = true;
		clientReq && clientReq.abort();
		res.destroy();
		if (obj && EventEmitter.listenerCount(obj, 'error') > 0) {
			obj.emit('error', err);
		}
	}

	function request(options, response) {
		var client = options.protocol == 'https:' ? https : http;
		req.pipe(client.request(options, response || res.response));
	}

	function response(_res) {
		res.writeHead(_res.statusCode || 0, _res.headers);
		res.src(_res);
	}

	var fullUrl = req.fullUrl = util.getFullUrl(req);
	if (req.headers.host == config.localUIHost) {
		var options = url.parse(fullUrl);
		options.host = '127.0.0.1';
		options.hostname = null;
		options.port = config.uiport;
		options.headers = req.headers;
		request(options, response);
		return;
	}

	next();
};
<commit_msg>local.whistle.com<commit_after>var PipeStream = require('pipestream');
var url = require('url');
var https = require('https');
var http = require('http');
var util = require('../../util');
var filters = require('./filters');
var config = util.config;

module.exports = function(req, res, next) {
	PipeStream.wrap(req);
	PipeStream.wrap(res, true);

	var clientReq, clientRes, errorEmitted;
	var reqTransform, resTransform;
	req.on('dest', function(_req) {
		clientReq = _req.on('error', onReqError);
	}).on('error', onReqError);
	res.on('src', function(_res) {
		clientRes = _res.on('error', onResError);
	}).on('error', onResError);

	function onReqError(err) {
		onError(reqTransform, err);
	}

	function onResError(err) {
		onError(resTransform, err);
	}

	function onError(obj, err) {
		if (errorEmitted) {
			return;
		}
		errorEmitted = true;
		clientReq && clientReq.abort();
		res.destroy();
		if (obj && EventEmitter.listenerCount(obj, 'error') > 0) {
			obj.emit('error', err);
		}
	}

	function request(options, response) {
		var client = options.protocol == 'https:' ? https : http;
		req.pipe(client.request(options, response || res.response));
	}

	var fullUrl = req.fullUrl = util.getFullUrl(req);
	if (req.headers.host == config.localUIHost) {
		var options = url.parse(fullUrl);
		options.host = '127.0.0.1';
		options.hostname = null;
		options.port = config.uiport;
		options.headers = req.headers;
		req.pipe(http.request(options, function(_res) {
			res.writeHead(_res.statusCode || 0, _res.headers);
			res.src(_res);
		}));
		return;
	}

	next();
};
<|endoftext|>


<commit_before>import React from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import CloseOnEscape from 'react-close-on-escape';
let saveAs;
if (typeof window !== 'undefined') {
  saveAs = require('filesaver.js').saveAs
}

const onXClick = (e, close) => {
  e.preventDefault();
  close();
};

export default class DisplayTest extends React.Component {
  constructor() {
    super();
    this.onClick = this.onClick.bind(this);
  }

  componentDidMount() {
    document.addEventListener('click', this.onClick);
    if (this.code) {
      this.code.setAttribute('contentEditable', true);
    }
  }

  componentDidUpdate() {
    // will be string true when getting attribute from native dom element
    if (this.code && this.code.getAttribute('contentEditable') !== 'true') {
      this.code.setAttribute('contentEditable', true);
    }
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.onClick);
  }

  onClick({ target }) {
    if (this.container &&
        !this.container.contains(target) &&
        this.props.shouldShowTest() &&
        target.className !== 'redux-test-recorder-record-button') {
      this.props.hideTest();
    }
  }

  saveFile(e) {
    e.preventDefault();
    const file = new Blob([this.props.getTest()], {type: 'text/plain;charset=utf-8'});
    saveAs(file, 'test.js');
  }

  render() {
    const { getTest, shouldShowTest, onKeyPress, hideTest } = this.props;
    if (!shouldShowTest()) {
      return ;
    }

    const style = {
      position: 'absolute',
      width: 500,
      height: 600,
      right: 25,
      bottom: 80,
      backgroundColor: '#f8f8ff',
      color: 'black',
      boxShadow: '2px 2px 5px #888888',
      overflowY: 'auto',
      zIndex: 99
    };

    const xStyle = {
      float: 'right',
      fontSize: 22,
      fontWeight: 700,
      marginRight: 5,
      cursor: 'pointer',
      color: '#888888'
    };

    const saveStyle = {
      color: '#888888',
      fontSize: 22,
      fontWeight: 600,
      cursor: 'pointer'
    };

    return (
      <CloseOnEscape onEscape={onKeyPress}>

 this.container = container} onClick={this.onClick}>
           this.saveFile(e)}>Save As File
           onXClick(e, hideTest)}>X

 this.code = code} style={{outline: 'none'}}>

                <SyntaxHighlighter language='javascript' stylesheet='docco'>
                  {getTest()}
                </SyntaxHighlighter>

      </CloseOnEscape>
    );
  }
}
<commit_msg>add px values to react component styles to avoid react 15 warnings<commit_after>import React from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import CloseOnEscape from 'react-close-on-escape';
let saveAs;
if (typeof window !== 'undefined') {
  saveAs = require('filesaver.js').saveAs
}

const onXClick = (e, close) => {
  e.preventDefault();
  close();
};

export default class DisplayTest extends React.Component {
  constructor() {
    super();
    this.onClick = this.onClick.bind(this);
  }

  componentDidMount() {
    document.addEventListener('click', this.onClick);
    if (this.code) {
      this.code.setAttribute('contentEditable', true);
    }
  }

  componentDidUpdate() {
    // will be string true when getting attribute from native dom element
    if (this.code && this.code.getAttribute('contentEditable') !== 'true') {
      this.code.setAttribute('contentEditable', true);
    }
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.onClick);
  }

  onClick({ target }) {
    if (this.container &&
        !this.container.contains(target) &&
        this.props.shouldShowTest() &&
        target.className !== 'redux-test-recorder-record-button') {
      this.props.hideTest();
    }
  }

  saveFile(e) {
    e.preventDefault();
    const file = new Blob([this.props.getTest()], {type: 'text/plain;charset=utf-8'});
    saveAs(file, 'test.js');
  }

  render() {
    const { getTest, shouldShowTest, onKeyPress, hideTest } = this.props;
    if (!shouldShowTest()) {
      return ;
    }

    const style = {
      position: 'absolute',
      width: '500px',
      height: '600px',
      right: '25px',
      bottom: '80px',
      backgroundColor: '#f8f8ff',
      color: 'black',
      boxShadow: '2px 2px 5px #888888',
      overflowY: 'auto',
      zIndex: 99
    };

    const xStyle = {
      float: 'right',
      fontSize: '22px',
      fontWeight: 700,
      marginRight: '5px',
      cursor: 'pointer',
      color: '#888888'
    };

    const saveStyle = {
      color: '#888888',
      fontSize: '22px',
      fontWeight: 600,
      cursor: 'pointer'
    };

    return (
      <CloseOnEscape onEscape={onKeyPress}>

 this.container = container} onClick={this.onClick}>
           this.saveFile(e)}>Save As File
           onXClick(e, hideTest)}>X

 this.code = code} style={{outline: 'none'}}>

                <SyntaxHighlighter language='javascript' stylesheet='docco'>
                  {getTest()}
                </SyntaxHighlighter>

      </CloseOnEscape>
    );
  }
}
<|endoftext|>


<commit_before>$.register({
  rule: {
    host: /^gca\.sh$/,
  },
  ready: function () {
    'use strict';

    $.removeNodes('iframe');

    var jQuery = $.window.$;
    setTimeout(function () {
      jQuery("#captcha-dialog").dialog("open");
    }, 1000);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>Support repla.cr<commit_after>$.register({
  rule: {
    host: /^gca\.sh|repla\.cr$/,
  },
  ready: function () {
    'use strict';

    $.removeNodes('iframe');

    var jQuery = $.window.$;
    setTimeout(function () {
      jQuery("#captcha-dialog").dialog("open");
    }, 1000);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>angular.module('popup', []).controller('popup', popup);

function popup($scope) {
    var currentTab;
    chrome.tabs.query({active: true, currentWindow: true}, (currentTabs) => {
        currentTab = currentTabs[0];
        var urlWithoutHash = currentTab.url.split('#')[0];
        var baseUrl = urlWithoutHash.split('?')[0];

        chrome.tabs.query({ url: baseUrl + '*' }, (tabs) => {
            $scope.tabs = tabs;
            var matches = _.reject(tabs, {id: currentTab.id});
            $scope.exacts = _.filter(matches, {url: currentTab.url});
            var matchesWithoutHash = _.filter(matches, (tab) =>
                tab.url.split('#')[0] === urlWithoutHash
            );
            $scope.matchesOnlyBase = _.difference(matches, matchesWithoutHash);
            $scope.matchesExceptHash = _.difference(matchesWithoutHash, $scope.exacts);

            var urlParts = baseUrl.split('/');
            $scope.rule = {};
            if(baseUrl.indexOf('://') > -1) {
                $scope.rule.url = urlParts[0] + '//' + urlParts[2];
            } else {
                $scope.rule.url = urlParts[0];
            }
            $scope.rule.match = 'hash';
            $scope.$apply();

            matchRule(baseUrl, (rule) => {
                if(rule) {
                    $scope.rule = rule;
                    $scope.savedRule = _.clone(rule);
                }
                // loading done: safe to show form for user input
                $scope.showRuleForm = true;
                $scope.$apply();
            });
        });
    });

    $scope.goto = (tab) => {
        chrome.tabs.update(tab.id, {active:true});
        chrome.windows.update(tab.windowId, {focused:true});
        if($scope.closeTab) {
            chrome.tabs.remove(currentTab.id);
        }
    };

    $scope.pluralizeMsg = (count) => {
        if(count == 1) {
            return 'There is one other tab';
        }
        if(count > 1) {
            return 'There are ' + count + ' tabs';
        }
        return '';
    };

    $scope.saveRule = () => {
        loadRules((rules) => {
            if($scope.savedRule) {
                delete rules[$scope.savedRule.url];
            }
            rules[$scope.rule.url] = $scope.rule.match;
            saveRules(rules);
            $scope.savedRule = _.clone($scope.rule);
            $scope.$apply();
        });
    };

    $scope.showOptions = () => {
        chrome.runtime.openOptionsPage();
    };
}

// Work-around for chrome auto-focusing first anchor tag in popup
function focus(event) {
    event.target.blur();
    document.removeEventListener(focus);
}
document.addEventListener('focus', focus);
<commit_msg>add globals from rules lib<commit_after>/*global matchRule,loadRules,saveRules*/
angular.module('popup', []).controller('popup', popup);

function popup($scope) {
    var currentTab;
    chrome.tabs.query({active: true, currentWindow: true}, (currentTabs) => {
        currentTab = currentTabs[0];
        var urlWithoutHash = currentTab.url.split('#')[0];
        var baseUrl = urlWithoutHash.split('?')[0];

        chrome.tabs.query({ url: baseUrl + '*' }, (tabs) => {
            $scope.tabs = tabs;
            var matches = _.reject(tabs, {id: currentTab.id});
            $scope.exacts = _.filter(matches, {url: currentTab.url});
            var matchesWithoutHash = _.filter(matches, (tab) =>
                tab.url.split('#')[0] === urlWithoutHash
            );
            $scope.matchesOnlyBase = _.difference(matches, matchesWithoutHash);
            $scope.matchesExceptHash = _.difference(matchesWithoutHash, $scope.exacts);

            var urlParts = baseUrl.split('/');
            $scope.rule = {};
            if(baseUrl.indexOf('://') > -1) {
                $scope.rule.url = urlParts[0] + '//' + urlParts[2];
            } else {
                $scope.rule.url = urlParts[0];
            }
            $scope.rule.match = 'hash';
            $scope.$apply();

            matchRule(baseUrl, (rule) => {
                if(rule) {
                    $scope.rule = rule;
                    $scope.savedRule = _.clone(rule);
                }
                // loading done: safe to show form for user input
                $scope.showRuleForm = true;
                $scope.$apply();
            });
        });
    });

    $scope.goto = (tab) => {
        chrome.tabs.update(tab.id, {active:true});
        chrome.windows.update(tab.windowId, {focused:true});
        if($scope.closeTab) {
            chrome.tabs.remove(currentTab.id);
        }
    };

    $scope.pluralizeMsg = (count) => {
        if(count == 1) {
            return 'There is one other tab';
        }
        if(count > 1) {
            return 'There are ' + count + ' tabs';
        }
        return '';
    };

    $scope.saveRule = () => {
        loadRules((rules) => {
            if($scope.savedRule) {
                delete rules[$scope.savedRule.url];
            }
            rules[$scope.rule.url] = $scope.rule.match;
            saveRules(rules);
            $scope.savedRule = _.clone($scope.rule);
            $scope.$apply();
        });
    };

    $scope.showOptions = () => {
        chrome.runtime.openOptionsPage();
    };
}

// Work-around for chrome auto-focusing first anchor tag in popup
function focus(event) {
    event.target.blur();
    document.removeEventListener(focus);
}
document.addEventListener('focus', focus);
<|endoftext|>


<commit_before>(function ($) {
    "use strict";

    var
        hasSomeMultipleOf = function(remains, primeFactor) {
            var
                i = 0;

            while(i < remains.length) {
                if (remains[i++].multipleOf(primeFactor)) {
                    return true;
                }
            }

            return false;
        },

        calculateRemains = function(remains, primeFactor) {
            var
                i = 0;

            while(i < remains.length) {
                if (remains[i].multipleOf(primeFactor)) {
                    remains[i] /= primeFactor;
                }
                i++;
            }
        };

    try {
        Object.defineProperties($, {

            // greatest common divisor
            GCD: {
                value: function () {
                    var
                        iterator,
                        primeFactor = 2,
                        product = 1,
                        i = 0,
                        count = 0,
                        remains = [],

                        euclidesAlgorithm = function(a, b) {
                            var
                                rest = b;

                            while(rest !== 0) {
                               rest = a % b;
                               a = b;
                               b = rest;
                            }

                            return a;
                        },

                        everyoneAreMultipleOf = function(remains, factor) {
                            var
                                i = 0;

                            while(i < remains.length) {
                                if (!remains[i++].multipleOf(factor)) {
                                    return false;
                                }
                            }

                            return true;
                        };

                    remains = Array.from(arguments);
                    remains = remains.uniq();
                    if(remains.length == 1) {
                        return remains[0];
                    }

                    // properties

                    // se todos os números forem múltiplos entre si, o MDC será menor deles
                    if(remains.areMultiples()) {
                        return remains.min();
                    }

                    // o algorítmo de Euclides é mais eficiente para calcular o MDC entre apenas dois números
                    if(remains.length == 2) {
                        return euclidesAlgorithm(remains[0], remains[1]);
                    }

                    // dois números primos não são múltiplos entre si
                    i = 0;
                    while(true) {
                        if((remains[i]).isPrime()) {count++;}
                        if(count >= 2) {return 1;}
                        if(i == remains.length -1) {break;}
                        i++;
                    }

                    iterator = Math.PrimeFactorsDecomposition.Proxy
                        .new(remains);
                    iterator.decompose(function(r) {
                        primeFactor = iterator.primeFactor();
                        if(everyoneAreMultipleOf(r, primeFactor)) {
                            product *= primeFactor;
                        }
                    });

                    return product;
                }
            },

            // least common multiple
            LCM: {
                value: function () {
                    var
                        iterator,
                        primeFactor = 2,
                        remains = [],
                        product = 1,

                        for2Factors = function(numbers) {
                            var
                                product = 1;

                            numbers.forEach(function (v) {
                                product *= v;
                            });

                            return product/Math.GCD.apply(null, numbers);
                        };

                    remains = Array.from(arguments);
                    remains = remains.uniq();
                    if(remains.length == 1) {
                        return remains[0];
                    }

                    if(remains.areMultiples()) {
                        // return remains.max();
                    }

                    if(remains.length == 2) {
                        // return for2Factors(remains);
                    }

                    iterator = Math.PrimeFactorsDecomposition.Proxy
                        .new(remains);
                    iterator.decompose(function(r) {
                        primeFactor = iterator.primeFactor();
                        product *= primeFactor;
                    });

                    return product;
                }
            }

        });

    } catch(e) {}

})(Math);
<commit_msg>remove comentário<commit_after>(function ($) {
    "use strict";

    var
        hasSomeMultipleOf = function(remains, primeFactor) {
            var
                i = 0;

            while(i < remains.length) {
                if (remains[i++].multipleOf(primeFactor)) {
                    return true;
                }
            }

            return false;
        },

        calculateRemains = function(remains, primeFactor) {
            var
                i = 0;

            while(i < remains.length) {
                if (remains[i].multipleOf(primeFactor)) {
                    remains[i] /= primeFactor;
                }
                i++;
            }
        };

    try {
        Object.defineProperties($, {

            // greatest common divisor
            GCD: {
                value: function () {
                    var
                        iterator,
                        primeFactor = 2,
                        product = 1,
                        i = 0,
                        count = 0,
                        remains = [],

                        euclidesAlgorithm = function(a, b) {
                            var
                                rest = b;

                            while(rest !== 0) {
                               rest = a % b;
                               a = b;
                               b = rest;
                            }

                            return a;
                        },

                        everyoneAreMultipleOf = function(remains, factor) {
                            var
                                i = 0;

                            while(i < remains.length) {
                                if (!remains[i++].multipleOf(factor)) {
                                    return false;
                                }
                            }

                            return true;
                        };

                    remains = Array.from(arguments);
                    remains = remains.uniq();
                    if(remains.length == 1) {
                        return remains[0];
                    }

                    // properties

                    // se todos os números forem múltiplos entre si, o MDC será menor deles
                    if(remains.areMultiples()) {
                        return remains.min();
                    }

                    // o algorítmo de Euclides é mais eficiente para calcular o MDC entre apenas dois números
                    if(remains.length == 2) {
                        return euclidesAlgorithm(remains[0], remains[1]);
                    }

                    // dois números primos não são múltiplos entre si
                    i = 0;
                    while(true) {
                        if((remains[i]).isPrime()) {count++;}
                        if(count >= 2) {return 1;}
                        if(i == remains.length -1) {break;}
                        i++;
                    }

                    iterator = Math.PrimeFactorsDecomposition.Proxy
                        .new(remains);
                    iterator.decompose(function(r) {
                        primeFactor = iterator.primeFactor();
                        if(everyoneAreMultipleOf(r, primeFactor)) {
                            product *= primeFactor;
                        }
                    });

                    return product;
                }
            },

            // least common multiple
            LCM: {
                value: function () {
                    var
                        iterator,
                        primeFactor = 2,
                        remains = [],
                        product = 1,

                        for2Factors = function(numbers) {
                            var
                                product = 1;

                            numbers.forEach(function (v) {
                                product *= v;
                            });

                            return product/Math.GCD.apply(null, numbers);
                        };

                    remains = Array.from(arguments);
                    remains = remains.uniq();
                    if(remains.length == 1) {
                        return remains[0];
                    }

                    if(remains.areMultiples()) {
                        return remains.max();
                    }

                    if(remains.length == 2) {
                        return for2Factors(remains);
                    }

                    iterator = Math.PrimeFactorsDecomposition.Proxy
                        .new(remains);
                    iterator.decompose(function(r) {
                        primeFactor = iterator.primeFactor();
                        product *= primeFactor;
                    });

                    return product;
                }
            }

        });

    } catch(e) {}

})(Math);
<|endoftext|>


<commit_before>/*!
	Type checking and validation tool
	Made with care by Matteo Capucci <mattecapu@live.it>
	Nerd it on GitHub: https://github.com/mattecapu/types.js
*/

import Promise from 'bluebird';
import deepEqual from 'deep-equal';

const deepCompare = (a, b) => deepEqual(a, b, { strict: true });
const asArray = (obj) => [].slice.call(obj);

const SIGNUM_REGEX = /^-/;

// factory interface to mask the immutability
const typs = (...args) => new Typs(args, []);

const wrap_and_add = (function (constraint, transformer = (x) => x) {
	const wrapped_constraint = (objs, constraints) => {

		objs = transformer(objs);

		const next = () =>
			0 === constraints.length || constraints[0](objs, constraints.slice(1));

		let promises = [];

		if (!objs.every((o) => {
			const result = constraint(o);
			if (result instanceof Promise) {
				promises.push(result);
				return true;
			} else {
				return result;
			}
		})) return false;

		if (!promises.length) return next();

		return Promise.all(promises).then((results) => {
			if (results.some((x) => !x)) return false;
			return next();
		}).catch((error) => {
			throw error;
		});
	};

	// return a new object that validates with all the
	// previous constraints plus thew new one
	return new Typs(this.args, this.constraints.concat(wrapped_constraint));
});

// a class which represent a type signature
class Typs {
	constructor(args, constraints) {
		// abor empty arrays
		if (args.length === 0) args = [undefined];

		// expose as private properties
		Object.assign(this, { args, constraints });
		// expose wrap and add
		Object.assign(this, { add: wrap_and_add.bind(this) });
	}

	// checks if the arguments satisfy all the constraints of this type signature
	checkOn (...args) {
		if (0 === this.constraints.length) return true;
		return this.constraints[0](args, this.constraints.slice(1));
	}
	// checks if the objects passed to typs() satisfy this type signature
	check () {
		return this.checkOn.apply(this, this.args);
	}

	// negations of check() and checkOn()
	doesntCheckOn (obj) {
		return !this.checkOn(obj);
	}
	doesntCheck () {
		return !this.check();
	}

	// maps the arguments
	map (mapper) {
		if (typs(mapper).func().doesntCheck()) {
			throw new Error('typs().map() expects a function as its first parameter');
		}
		return this.add(() => true, (objs) => objs.map(mapper));
	}

	// switch the validation to items
	andEach () {
		return this.add(
			() => true,
			(objs) => {
				return objs.map((obj) => {
					if (typs(obj).hasLength().doesntCheck()) return obj;
					return asArray(obj);
				}).reduce((f, o) => f.concat(o), []);
			}
		);
	}
	// switch the validation to properties
	andEachProp () {
		return this.map((obj) => {
			if (typs(obj).object().notNil().doesntCheck()) return [obj];
			return Object.keys(obj).map((k) => obj[k]);
		}).andEach();
	}
	// switch the validation to keys
	andEachKey () {
		return this.map((obj) => {
			if (typs(obj).object().notNil().doesntCheck() && typs(obj).array().doesntCheck()) {
				throw new Error('typs().andEachKey() can\'t read keys of a non-object');
			}
			return Object.keys(obj);
		}).andEach();
	}
	// switch the validation to an array of key/values objects
	andEachEntry () {
		return this.map((obj) => {
			if (typs(obj).object().notNil().doesntCheck() && typs(obj).array().doesntCheck()) {
				throw new Error('typs().andEachEntry() can\'t read entries from a non-object');
			}
			return Object.keys(obj).map((key) => {
				return {key, value: obj[key]};
			});
		}).andEach();
	}

	// checks if obj doesn't match the specified type
	not (type) {
		return this.add((obj) => {
			return typs(obj).isnt(type);
		});
	}

	// checks if obj is null, undefined or NaN
	nil () {
		return this.add((obj) => {
			return obj === null || obj === void 0 || obj !== obj;
		});
	}
	notNil () {
		return this.not(typs().nil());
	}

	// checks if obj is undefined
	undef () {
		return this.add((obj) => {
			return obj === void 0;
		});
	}
	def () {
		return this.not(typs().undef());
	}

	// numbers
	number () {
		return this.add((obj) => {
			return (typs(obj).string().check()
					|| typeof obj === 'number' || obj instanceof Number)
					&& !isNaN(parseFloat(obj))
					&& (isFinite(obj.toString().replace(SIGNUM_REGEX, '')) || obj * obj === Infinity)
		});
	}

	// checks for finiteness
	finite () {
		return this.add((obj) => {
			return typs(obj).number().check() && isFinite(obj.toString().replace(SIGNUM_REGEX, ''));
		});
	}
	// checks for infiniteness
	infinite () {
		return this.number().not(typs().finite());
	}

	// checks if obj is an integer
	integer () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseInt(obj) === parseFloat(obj)
		});
	}

	// checks if obj is positive or negative
	positive () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) >= 0;
		});
	}
	negative () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) < 0;
		});
	}

	// checks if obj is different from 0
	notZero () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) !== 0;
		});
	}

	// checks if obj is greater than num
	greater (num) {
		if (typs(num).number().doesntCheck()) {
			throw new Error('typs().greater() expects a number as its first parameter');
		}
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) > parseFloat(num);
		});
	}

	// checks if obj is lesser than num
	lesser (num) {
		if (typs(num).number().doesntCheck()) {
			throw new Error('typs().greater() expects a number as its first parameter');
		}
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) < parseFloat(num);
		});
	}

	// checks if obj is between min and max, using includeStart and includeEnd to specify if include the bounds
	between ({min, max, includeStart = false, includeEnd = false}) {

		let types = [];

		min = parseFloat(min);
		max = parseFloat(max);

		// it doesn't duplicate the checks on lesser() and greater(),
		// but refires the exception to hide the rewiring of between()
		try {
			types.push(typs().greater(min).lesser(max));
		} catch(e) {
			throw new Error('typs().between() expects numeric bounds');
		}

		if (min > max) throw new Error('typs().between() expects ordered bounds');

		if (typs(includeStart, includeEnd).bool().doesntCheck()) {
			throw new Error('typs().between() expects includeStart and includeEnd to be booleans');
		}

		if (includeStart) types.push(typs().equals(min));
		if (includeEnd) types.push(typs().equals(max));

		return this.matchesAny(types);
	}

	// checks if obj is a boolean
	bool () {
		return this.add((obj) => {
			return typeof obj === 'boolean' || obj instanceof Boolean;
		});
	}

	// strings
	string () {
		return this.add((obj) => {
			return typeof obj === 'string' || obj instanceof String
		});
	}

	hasLength () {
		return this.matchesAny([
			typs().string(),
			typs().array(),
			typs().object().hasKeys(['length'])
		]);
	}

	// checks if obj.length respects the given constraints (good for any array-like object)
	len ({min, max, exact}) {
		const param_type = typs().notNil().integer().positive();

		if (typs(min).isnt(param_type) && typs(max).isnt(param_type) && typs(exact).isnt(param_type)) {
			throw new Error('typs().len() expects at least one parameter to be a positive integer');
		}

		min = parseInt(min);
		max = parseInt(max);
		exact = parseInt(exact);

		if (min > max) throw new Error('typs().len() expects ordered bounds');

		return this.add((obj) => {
			return typs(obj).hasLength().check()
					&& (typs(min).is(param_type) ? obj.length >= min : true)
					&& (typs(max).is(param_type) ? obj.length <= max : true)
					&& (typs(exact).is(param_type) ? obj.length === exact : true)
		});
	}

	// checks array-like objects for emptiness
	empty () {
		return this.add((obj) => {
			return typs(obj).len({exact: 0}).check();
		});
	}
	notEmpty () {
		return this.not(typs().empty());
	}

	// checks objects for emptiness
	hollow () {
		return this.def().andEachProp().undef();
	}
	notHollow () {
		return this.def().not(typs().hollow());
	}

	// checks if obj matches the provided regex
	regex (regex) {
		if (!typs(regex).instanceOf(RegExp)) {
			throw new Error('typs().regex() expects a RegExp object as its first parameter');
		}
		return this.add((obj) => {
			return typs(obj).string().check() && regex.test(obj);
		});
	}

	// arrays
	array () {
		return this.add(Array.isArray);
	}

	// checks if a collection has any duplicate entries
	unique () {
		return this.add((obj) => {
			if (typs(obj).hasLength().doesntCheck()) return false;
			return asArray(obj).every((e, i, arr) => i === arr.indexOf(e));
		});
	}

	// objects
	object () {
		return this.add((obj) => {
			return typs(obj).array().doesntCheck() && typeof obj === 'object';
		});
	}

	// returns true if accessing obj[<key>] doesn't raise an exception
	keyable () {
		return this.notNil().matchesAny([
			typs().object(),
			typs().array(),
			typs().string()
		]);
	}

	// checks if obj has all keys defined
	hasKeys (keys) {
		if (typs(keys).array().doesntCheck()) {
			throw new Error('typs().hasKeys() expects an array as its first parameter');
		}
		return this.add((obj) => {
			if (typs(obj).keyable().doesntCheck()) return false;
			return keys.every((key) => key in obj);
		});
	}

	// checks if obj is an instance of the given class
	instanceOf (class_func) {
		if (typs(class_func).func().doesntCheck()) {
			throw new Error('typs().instanceOf() expects a function class as its first parameter');
		}
		return this.add((obj) => {
			return obj instanceof class_func;
		});
	}

	// checks if obj is a Typs type signature
	type () {
		return this.add((obj) => {
			if (obj instanceof Typs) return true;
			if (typs(obj).object().doesntCheck()) return false;
			return Object.keys(obj).every((key) => {
				return typs(obj[key]).type().check();
			});
		});
	}

	// checks if type matches obj
	matches (type) {
		if (typs(type).type().doesntCheck()) {
			throw new Error('typs().matches() expects a type signature object as its first parameter');
		}
		if (type instanceof Typs) {
			return this.add((obj) => {
				return type.checkOn(obj);
			});
		}
		return this.add((obj) => {
			if (typs(obj).keyable().doesntCheck()) return false;
			return Object.keys(type).every((key) => {
				if (typs(type[key]).object().check()) {
					// nested objects
					return typs(obj[key]).is(type[key]);
				} else {
					// simple type checks
					return type[key].checkOn(obj[key]);
				}
			});
		});
	}

	// shortcuts for matches().check()
	is (type) {
		return this.matches(type).check();
	}
	are (type) {
		return this.is(type);
	}
	isnt (type) {
		return !this.is(type);
	}
	arent (type) {
		return this.isnt(type);
	}

	// checks if obj satisfies one or more type signatures
	matchesAny (types) {
		if (typs(types).array().doesntCheck()) {
			throw new Error('typs().matchesAny() expectes an array of types as its first parameter');
		}
		if (typs.apply(typs, types).type().doesntCheck()) {
			throw new Error('typs().matchesAny() expectes an array of types as its first parameter');
		}
		return this.add((obj) => {
			return types.some((t) => typs(obj).is(t));
		});
	}
	isAny (types) {
		return this.matchesAny(types).check();
	}

	// check type signature for all the elements of a collection
	eachMatches (type) {
		if (typs(type).type().doesntCheck()) {
			throw new Error('typs().eachMatches() expects a type as its first parameter');
		}
		return this.hasLength().andEach().matches(type);
	}

	// checks if value equals to obj
	equals (value) {
		return this.add((obj) => {
			return deepCompare(value, obj);
		});
	}
	notEquals (value) {
		return this.not(typs().equals(value));
	}

	// checks if obj is one element of domain
	oneOf (domain) {
		if (typs(domain).hasLength().doesntCheck()) {
			throw new Error('typs().oneOf() expects an iterable collection as its first parameter');
		}
		return this.add((obj) => {
			if (typeof obj === 'undefined') return false;
			return -1 !== domain.indexOf(obj);
		});
	}

	// functions
	func () {
		return this.add((obj) => {
			return typeof obj === 'function';
		});
	}

	// checks if obj satisfies the constraints defined in the function constraint(obj);
	satisfies (constraint) {
		if (typs(constraint).func().doesntCheck()) {
			throw new Error('typs().satisfies() expects a function as its first argument');
		}
		return this.add(constraint);
	}
}

export default typs;
<commit_msg>code style<commit_after>/*!
	Type checking and validation tool
	Made with care by Matteo Capucci <mattecapu@live.it>
	Nerd it on GitHub: https://github.com/mattecapu/types.js
*/

import Promise from 'bluebird';
import deepEqual from 'deep-equal';

const deepCompare = (a, b) => deepEqual(a, b, { strict: true });
const asArray = (obj) => [].slice.call(obj);

const SIGNUM_REGEX = /^-/;

// factory interface to mask the immutability
const typs = (...args) => new Typs(args, []);

function wrap_and_add (constraint, transformer = (x) => x) {
	const wrapped_constraint = (objs, constraints) => {

		objs = transformer(objs);

		const next = () =>
			0 === constraints.length || constraints[0](objs, constraints.slice(1));

		let promises = [];

		if (!objs.every((o) => {
			const result = constraint(o);
			if (result instanceof Promise) {
				promises.push(result);
				return true;
			} else {
				return result;
			}
		})) return false;

		if (!promises.length) return next();

		return Promise.all(promises).then((results) => {
			if (results.some((x) => !x)) return false;
			return next();
		}).catch((error) => {
			throw error;
		});
	};

	// return a new object that validates with all the
	// previous constraints plus thew new one
	return new Typs(this.args, this.constraints.concat(wrapped_constraint));
};

// a class which represent a type signature
class Typs {
	constructor(args, constraints) {
		// abor empty arrays
		if (args.length === 0) args = [undefined];

		// expose as private properties
		Object.assign(this, { args, constraints });
		// expose wrap and add
		Object.assign(this, { add: wrap_and_add.bind(this) });
	}

	// checks if the arguments satisfy all the constraints of this type signature
	checkOn (...args) {
		if (0 === this.constraints.length) return true;
		return this.constraints[0](args, this.constraints.slice(1));
	}
	// checks if the objects passed to typs() satisfy this type signature
	check () {
		return this.checkOn.apply(this, this.args);
	}

	// negations of check() and checkOn()
	doesntCheckOn (obj) {
		return !this.checkOn(obj);
	}
	doesntCheck () {
		return !this.check();
	}

	// maps the arguments
	map (mapper) {
		if (typs(mapper).func().doesntCheck()) {
			throw new Error('typs().map() expects a function as its first parameter');
		}
		return this.add(() => true, (objs) => objs.map(mapper));
	}

	// switch the validation to items
	andEach () {
		return this.add(
			() => true,
			(objs) => {
				return objs.map((obj) => {
					if (typs(obj).hasLength().doesntCheck()) return obj;
					return asArray(obj);
				}).reduce((f, o) => f.concat(o), []);
			}
		);
	}
	// switch the validation to properties
	andEachProp () {
		return this.map((obj) => {
			if (typs(obj).object().notNil().doesntCheck()) return [obj];
			return Object.keys(obj).map((k) => obj[k]);
		}).andEach();
	}
	// switch the validation to keys
	andEachKey () {
		return this.map((obj) => {
			if (typs(obj).object().notNil().doesntCheck() && typs(obj).array().doesntCheck()) {
				throw new Error('typs().andEachKey() can\'t read keys of a non-object');
			}
			return Object.keys(obj);
		}).andEach();
	}
	// switch the validation to an array of key/values objects
	andEachEntry () {
		return this.map((obj) => {
			if (typs(obj).object().notNil().doesntCheck() && typs(obj).array().doesntCheck()) {
				throw new Error('typs().andEachEntry() can\'t read entries from a non-object');
			}
			return Object.keys(obj).map((key) => {
				return {key, value: obj[key]};
			});
		}).andEach();
	}

	// checks if obj doesn't match the specified type
	not (type) {
		return this.add((obj) => {
			return typs(obj).isnt(type);
		});
	}

	// checks if obj is null, undefined or NaN
	nil () {
		return this.add((obj) => {
			return obj === null || obj === void 0 || obj !== obj;
		});
	}
	notNil () {
		return this.not(typs().nil());
	}

	// checks if obj is undefined
	undef () {
		return this.add((obj) => {
			return obj === void 0;
		});
	}
	def () {
		return this.not(typs().undef());
	}

	// numbers
	number () {
		return this.add((obj) => {
			return (typs(obj).string().check()
					|| typeof obj === 'number' || obj instanceof Number)
					&& !isNaN(parseFloat(obj))
					&& (isFinite(obj.toString().replace(SIGNUM_REGEX, '')) || obj * obj === Infinity)
		});
	}

	// checks for finiteness
	finite () {
		return this.add((obj) => {
			return typs(obj).number().check() && isFinite(obj.toString().replace(SIGNUM_REGEX, ''));
		});
	}
	// checks for infiniteness
	infinite () {
		return this.number().not(typs().finite());
	}

	// checks if obj is an integer
	integer () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseInt(obj) === parseFloat(obj)
		});
	}

	// checks if obj is positive or negative
	positive () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) >= 0;
		});
	}
	negative () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) < 0;
		});
	}

	// checks if obj is different from 0
	notZero () {
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) !== 0;
		});
	}

	// checks if obj is greater than num
	greater (num) {
		if (typs(num).number().doesntCheck()) {
			throw new Error('typs().greater() expects a number as its first parameter');
		}
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) > parseFloat(num);
		});
	}

	// checks if obj is lesser than num
	lesser (num) {
		if (typs(num).number().doesntCheck()) {
			throw new Error('typs().greater() expects a number as its first parameter');
		}
		return this.add((obj) => {
			return typs(obj).number().check() && parseFloat(obj) < parseFloat(num);
		});
	}

	// checks if obj is between min and max, using includeStart and includeEnd to specify if include the bounds
	between ({min, max, includeStart = false, includeEnd = false}) {

		let types = [];

		min = parseFloat(min);
		max = parseFloat(max);

		// it doesn't duplicate the checks on lesser() and greater(),
		// but refires the exception to hide the rewiring of between()
		try {
			types.push(typs().greater(min).lesser(max));
		} catch(e) {
			throw new Error('typs().between() expects numeric bounds');
		}

		if (min > max) throw new Error('typs().between() expects ordered bounds');

		if (typs(includeStart, includeEnd).bool().doesntCheck()) {
			throw new Error('typs().between() expects includeStart and includeEnd to be booleans');
		}

		if (includeStart) types.push(typs().equals(min));
		if (includeEnd) types.push(typs().equals(max));

		return this.matchesAny(types);
	}

	// checks if obj is a boolean
	bool () {
		return this.add((obj) => {
			return typeof obj === 'boolean' || obj instanceof Boolean;
		});
	}

	// strings
	string () {
		return this.add((obj) => {
			return typeof obj === 'string' || obj instanceof String
		});
	}

	hasLength () {
		return this.matchesAny([
			typs().string(),
			typs().array(),
			typs().object().hasKeys(['length'])
		]);
	}

	// checks if obj.length respects the given constraints (good for any array-like object)
	len ({min, max, exact}) {
		const param_type = typs().notNil().integer().positive();

		if (typs(min).isnt(param_type) && typs(max).isnt(param_type) && typs(exact).isnt(param_type)) {
			throw new Error('typs().len() expects at least one parameter to be a positive integer');
		}

		min = parseInt(min);
		max = parseInt(max);
		exact = parseInt(exact);

		if (min > max) throw new Error('typs().len() expects ordered bounds');

		return this.add((obj) => {
			return typs(obj).hasLength().check()
					&& (typs(min).is(param_type) ? obj.length >= min : true)
					&& (typs(max).is(param_type) ? obj.length <= max : true)
					&& (typs(exact).is(param_type) ? obj.length === exact : true)
		});
	}

	// checks array-like objects for emptiness
	empty () {
		return this.add((obj) => {
			return typs(obj).len({exact: 0}).check();
		});
	}
	notEmpty () {
		return this.not(typs().empty());
	}

	// checks objects for emptiness
	hollow () {
		return this.def().andEachProp().undef();
	}
	notHollow () {
		return this.def().not(typs().hollow());
	}

	// checks if obj matches the provided regex
	regex (regex) {
		if (!typs(regex).instanceOf(RegExp)) {
			throw new Error('typs().regex() expects a RegExp object as its first parameter');
		}
		return this.add((obj) => {
			return typs(obj).string().check() && regex.test(obj);
		});
	}

	// arrays
	array () {
		return this.add(Array.isArray);
	}

	// checks if a collection has any duplicate entries
	unique () {
		return this.add((obj) => {
			if (typs(obj).hasLength().doesntCheck()) return false;
			return asArray(obj).every((e, i, arr) => i === arr.indexOf(e));
		});
	}

	// objects
	object () {
		return this.add((obj) => {
			return typs(obj).array().doesntCheck() && typeof obj === 'object';
		});
	}

	// returns true if accessing obj[<key>] doesn't raise an exception
	keyable () {
		return this.notNil().matchesAny([
			typs().object(),
			typs().array(),
			typs().string()
		]);
	}

	// checks if obj has all keys defined
	hasKeys (keys) {
		if (typs(keys).array().doesntCheck()) {
			throw new Error('typs().hasKeys() expects an array as its first parameter');
		}
		return this.add((obj) => {
			if (typs(obj).keyable().doesntCheck()) return false;
			return keys.every((key) => key in obj);
		});
	}

	// checks if obj is an instance of the given class
	instanceOf (class_func) {
		if (typs(class_func).func().doesntCheck()) {
			throw new Error('typs().instanceOf() expects a function class as its first parameter');
		}
		return this.add((obj) => {
			return obj instanceof class_func;
		});
	}

	// checks if obj is a Typs type signature
	type () {
		return this.add((obj) => {
			if (obj instanceof Typs) return true;
			if (typs(obj).object().doesntCheck()) return false;
			return Object.keys(obj).every((key) => {
				return typs(obj[key]).type().check();
			});
		});
	}

	// checks if type matches obj
	matches (type) {
		if (typs(type).type().doesntCheck()) {
			throw new Error('typs().matches() expects a type signature object as its first parameter');
		}
		if (type instanceof Typs) {
			return this.add((obj) => {
				return type.checkOn(obj);
			});
		}
		return this.add((obj) => {
			if (typs(obj).keyable().doesntCheck()) return false;
			return Object.keys(type).every((key) => {
				if (typs(type[key]).object().check()) {
					// nested objects
					return typs(obj[key]).is(type[key]);
				} else {
					// simple type checks
					return type[key].checkOn(obj[key]);
				}
			});
		});
	}

	// shortcuts for matches().check()
	is (type) {
		return this.matches(type).check();
	}
	are (type) {
		return this.is(type);
	}
	isnt (type) {
		return !this.is(type);
	}
	arent (type) {
		return this.isnt(type);
	}

	// checks if obj satisfies one or more type signatures
	matchesAny (types) {
		if (typs(types).array().doesntCheck()) {
			throw new Error('typs().matchesAny() expectes an array of types as its first parameter');
		}
		if (typs.apply(typs, types).type().doesntCheck()) {
			throw new Error('typs().matchesAny() expectes an array of types as its first parameter');
		}
		return this.add((obj) => {
			return types.some((t) => typs(obj).is(t));
		});
	}
	isAny (types) {
		return this.matchesAny(types).check();
	}

	// check type signature for all the elements of a collection
	eachMatches (type) {
		if (typs(type).type().doesntCheck()) {
			throw new Error('typs().eachMatches() expects a type as its first parameter');
		}
		return this.hasLength().andEach().matches(type);
	}

	// checks if value equals to obj
	equals (value) {
		return this.add((obj) => {
			return deepCompare(value, obj);
		});
	}
	notEquals (value) {
		return this.not(typs().equals(value));
	}

	// checks if obj is one element of domain
	oneOf (domain) {
		if (typs(domain).hasLength().doesntCheck()) {
			throw new Error('typs().oneOf() expects an iterable collection as its first parameter');
		}
		return this.add((obj) => {
			if (typeof obj === 'undefined') return false;
			return -1 !== domain.indexOf(obj);
		});
	}

	// functions
	func () {
		return this.add((obj) => {
			return typeof obj === 'function';
		});
	}

	// checks if obj satisfies the constraints defined in the function constraint(obj);
	satisfies (constraint) {
		if (typs(constraint).func().doesntCheck()) {
			throw new Error('typs().satisfies() expects a function as its first argument');
		}
		return this.add(constraint);
	}
}

export default typs;
<|endoftext|>


<commit_before>
ClientExpress.EventListener = (function(server) {

  var EventListener = function() {
  };

  EventListener.prototype.registerEventHandlers = function(server) {
    setup_onclick_event_handler(server);
    setup_onsubmit_event_handler(server);
    setup_onpopstate_event_handler(server);
  };

  var setup_onclick_event_handler = function(server) {
    document.onclick = function() {
      var ev = arguments[0] || window.event;
      var element = ev.target || ev.srcElement;

      if (element.tagName.toLowerCase() == 'a') {
        var request = new ClientExpress.Request({
          method: 'get',
          fullPath: element.href,
          title: element.title || '',
          session: server.session,
          delegateToServer: function () {
            if (element.href.substr(0, 4) == 'http') {
              window.location = element.href;
              return;
            }
            window.location.pathname = element.href;
          }
        });

        server.processRequest(request);
        return false;
      }
    };
  };

  var setup_onsubmit_event_handler = function(server) {
    document.onsubmit = function() {
      var ev = arguments[0] || window.event;
      var element = ev.target || ev.srcElement;

      if (element.tagName.toLowerCase() == 'form') {
        var self = this

        var request = new ClientExpress.Request({
          method: element.method,
          fullPath: [element.action, ClientExpress.utils.serializeArray(element)].join("?"),
          title: element.title,
          session: server.session,
          delegateToServer: function () {
            element.submit();
          }
        });

        server.processRequest(request);
        return false;
      }
    };
  };

  var setup_onpopstate_event_handler = function(server) {
    // if (window.addEventListener) {
    //   window.addEventListener('popstate', onPopStateHandler, false);
    // } else if (window.attachEvent) {
    //   window.attachEvent('onpopstate', onPopStateHandler);
    // }
  };

  return EventListener;
})();
<commit_msg>searching for :// instead of http so ftp:// or file:// will work as well now<commit_after>
ClientExpress.EventListener = (function(server) {

  var EventListener = function() {
  };

  EventListener.prototype.registerEventHandlers = function(server) {
    setup_onclick_event_handler(server);
    setup_onsubmit_event_handler(server);
    setup_onpopstate_event_handler(server);
  };

  var setup_onclick_event_handler = function(server) {
    document.onclick = function() {
      var ev = arguments[0] || window.event;
      var element = ev.target || ev.srcElement;

      if (element.tagName.toLowerCase() == 'a') {
        var request = new ClientExpress.Request({
          method: 'get',
          fullPath: element.href,
          title: element.title || '',
          session: server.session,
          delegateToServer: function () {
            if (element.href.indexOf("://") != -1) {
              window.location = element.href;
              return;
            }
            window.location.pathname = element.href;
          }
        });

        server.processRequest(request);
        return false;
      }
    };
  };

  var setup_onsubmit_event_handler = function(server) {
    document.onsubmit = function() {
      var ev = arguments[0] || window.event;
      var element = ev.target || ev.srcElement;

      if (element.tagName.toLowerCase() == 'form') {
        var self = this

        var request = new ClientExpress.Request({
          method: element.method,
          fullPath: [element.action, ClientExpress.utils.serializeArray(element)].join("?"),
          title: element.title,
          session: server.session,
          delegateToServer: function () {
            element.submit();
          }
        });

        server.processRequest(request);
        return false;
      }
    };
  };

  var setup_onpopstate_event_handler = function(server) {
    // if (window.addEventListener) {
    //   window.addEventListener('popstate', onPopStateHandler, false);
    // } else if (window.attachEvent) {
    //   window.attachEvent('onpopstate', onPopStateHandler);
    // }
  };

  return EventListener;
})();
<|endoftext|>


<commit_before>// @flow

import jsYaml from 'js-yaml'
import type {BuildingType} from '../types'
import {email} from 'react-native-communications'
import dedent from 'dedent'
import querystring from 'querystring'

export function submitReport(current: BuildingType, suggestion: BuildingType) {
  // calling trim() on these to remove the trailing newlines
  const before = stringifyBuilding(current).trim()
  const after = stringifyBuilding(suggestion).trim()

  const body = makeEmailBody(before, after, current.name)

  return email(
    ['allaboutolaf@stolaf.edu'],
    [],
    [],
    `[building] Suggestion for ${current.name}`,
    body,
  )
}

function makeEmailBody(before: string, after: string, title: string): string {
  return dedent`
  Hi! Thanks for letting us know about a schedule change.

  Please do not change anything below this line.

  ------------

  Project maintainers: ${makeIssueLink(before, after, title)}

  ${makeHtmlBody(before, after)}
  `
}

function makeMarkdownBody(before, after) {
  // dedent works by removing all common whitespace at the beginning
  // of lines, so the closing backtick has to be at the same level
  // as the text.
  return dedent`
  ## Before:

  \`\`\`yaml
  ${before}
  \`\`\`

  ## After:

  \`\`\`yaml
  ${after}
  \`\`\`
  `
}

function makeHtmlBody(before, after) {
  return `

Before:

${before}

After:

${after}

  `
}

function makeIssueLink(before: string, after: string, title: string): string {
  const q = querystring.stringify({
    'labels[]': 'data/hours',
    title: `Building hours update for ${title}`,
    body: makeMarkdownBody(before, after),
  })
  return `https://github.com/StoDevX/AAO-React-Native/issues/new?${q}`
}

function stringifyBuilding(building: BuildingType): string {
  let res = ''
  let prev = null
  let data = jsYaml.safeDump(building, {flowLevel: 4}).split('\n')
  for (let line of data) {
    if (['schedule:', 'breakSchedule:'].includes(line)) {
      res += `\n\n${line}`
    } else if (line.startsWith('  - title:') && prev !== 'schedule:') {
      res += `\n\n${line}`
    } else {
      res += `\n${line}`
    }
    prev = line
  }
  return res
}
<commit_msg>remove dedent from building-hours/submit<commit_after>// @flow

import jsYaml from 'js-yaml'
import type {BuildingType} from '../types'
import {email} from 'react-native-communications'
import querystring from 'querystring'

export function submitReport(current: BuildingType, suggestion: BuildingType) {
  // calling trim() on these to remove the trailing newlines
  const before = stringifyBuilding(current).trim()
  const after = stringifyBuilding(suggestion).trim()

  const body = makeEmailBody(before, after, current.name)

  return email(
    ['allaboutolaf@stolaf.edu'],
    [],
    [],
    `[building] Suggestion for ${current.name}`,
    body,
  )
}

function makeEmailBody(before: string, after: string, title: string): string {
  return `
Hi! Thanks for letting us know about a schedule change.

Please do not change anything below this line.

------------

Project maintainers: ${makeIssueLink(before, after, title)}

${makeHtmlBody(before, after)}
`
}

const makeMarkdownBody = (before, after) => `
## Before:

\`\`\`yaml
${before}
\`\`\`

## After:

\`\`\`yaml
${after}
\`\`\`

`.trim()

const makeHtmlBody = (before, after) => `

Before:

${before}

After:

${after}

`

function makeIssueLink(before: string, after: string, title: string): string {
  const q = querystring.stringify({
    'labels[]': 'data/hours',
    title: `Building hours update for ${title}`,
    body: makeMarkdownBody(before, after),
  })
  return `https://github.com/StoDevX/AAO-React-Native/issues/new?${q}`
}

function stringifyBuilding(building: BuildingType): string {
  let res = ''
  let prev = null
  let data = jsYaml.safeDump(building, {flowLevel: 4}).split('\n')
  for (let line of data) {
    if (['schedule:', 'breakSchedule:'].includes(line)) {
      res += `\n\n${line}`
    } else if (line.startsWith('  - title:') && prev !== 'schedule:') {
      res += `\n\n${line}`
    } else {
      res += `\n${line}`
    }
    prev = line
  }
  return res
}
<|endoftext|>


<commit_before>'use strict';

(function(window, document, $, module, exports, require, swal, Qiniu, QiniuConfig){
  var Loader = require('component/common/loader');

  $('[name=addQueueBtn]').click(function() {
    $('body').append($('#create-tpl').html());
    $('#create1').modal({backdrop: 'static', keyboard: false});

    $('#create1 #queue-form').on('submit', function (e) {
      if (e.isDefaultPrevented()) {
      } else {
        e.preventDefault();
        var sceneStrs = [];
        var name = $('#create1 [name=name]').val();
        Loader.show();
        $.ajax({
          url : '/api/admin/replyQueue',
          type : 'POST',
          data : JSON.stringify({name: name}),
          dataType: 'json',
          contentType: 'application/json',
          success : function(data) {
            Loader.hide();
            console.log(data);
            if (data.error) {
              if (typeof data.error.message === 'object') {
                data.error.message = data.error.message.join('\n');
              }
              return swal('错误', data.error.message, 'error');
            }
            swal({
                title : "队列添加成功",
                type : "success"
              },
              function () {
                $('#create').modal('hide');
                location.reload();
              });
          }
        });
      }
    });
    $('#create').on('hidden.bs.modal', function () {
      $('#create').remove();
    });
  });

})(window, document, window['jQuery'], module, exports, require, window['swal'], window['Qiniu'], window['QiniuConfig']);<commit_msg>create1<commit_after>'use strict';

(function(window, document, $, module, exports, require, swal, Qiniu, QiniuConfig){
  var Loader = require('component/common/loader');

  $('[name=addQueueBtn]').click(function() {
    $('body').append($('#create1-tpl').html());
    $('#create1').modal({backdrop: 'static', keyboard: false});

    $('#create1 #queue-form').on('submit', function (e) {
      if (e.isDefaultPrevented()) {
      } else {
        e.preventDefault();
        var sceneStrs = [];
        var name = $('#create1 [name=name]').val();
        Loader.show();
        $.ajax({
          url : '/api/admin/replyQueue',
          type : 'POST',
          data : JSON.stringify({name: name}),
          dataType: 'json',
          contentType: 'application/json',
          success : function(data) {
            Loader.hide();
            console.log(data);
            if (data.error) {
              if (typeof data.error.message === 'object') {
                data.error.message = data.error.message.join('\n');
              }
              return swal('错误', data.error.message, 'error');
            }
            swal({
                title : "队列添加成功",
                type : "success"
              },
              function () {
                $('#create').modal('hide');
                location.reload();
              });
          }
        });
      }
    });
    $('#create').on('hidden.bs.modal', function () {
      $('#create').remove();
    });
  });

})(window, document, window['jQuery'], module, exports, require, window['swal'], window['Qiniu'], window['QiniuConfig']);<|endoftext|>


<commit_before>'use strict'

describe('Flashcard editor', function() {

    beforeEach(function() {
        browser().navigateTo('/');
        restartDB();
        sleep(0.3);
        browser().navigateTo('/#/FlashcardList/someFlashcardListId1');
    });

    it("should contain edit button in preview mode", function() {
        // then
        expect(element('.flashcards-container > div:nth-child(1) .front button.edit:visible').count()).toBe(1);
    });

    it("should not contain edit button in edit mode", function() {
        // when
        element('.flashcards-container > div:nth-child(1) .front button.edit').click();

        // then
        expect(element('.flashcards-container > div:nth-child(1) .front button.edit:visible').count()).toBe(0);
    });

    it('should not contain the "save" button in preview mode', function() {
        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .save:visible').count()).toBe(0);
    });

    it('should contain the "save" button in edit mode', function() {
        // when
        element('.flashcards-container > div:nth-child(1) > .front markdown-editor div').dblclick();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .save:visible').count()).toBe(1);
    });

    it('should save the new text upon editing', function() {
        // when
        element('.flashcards-container > div:nth-child(1) > .front markdown-editor div').dblclick();
        element('.flashcards-container > div:nth-child(1) > .front textarea').val('brand *new* text');
        element('.flashcards-container > div:nth-child(1) > .front .save:visible').click();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .preview').html()).toContain('brand new text');
    });

    it('should save the new text upon refreshing the page', function() {
        // when
        element('.flashcards-container > div:nth-child(1) > .front markdown-editor div').dblclick();
        element('.flashcards-container > div:nth-child(1) > .front textarea').val('brand *new* text');
        element('.flashcards-container > div:nth-child(1) > .front .save:visible').click();
        browser().reload();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .preview').html()).toContain('brand new text');
    });

    it('should have filling text when there is empty text', function() {
        // when
        element('.flashcards-container > div:nth-child(1) > .front markdown-editor div').dblclick();
        element('.flashcards-container > div:nth-child(1) > .front textarea').val('');
        element('.flashcards-container > div:nth-child(1) > .front .save:visible').click();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .preview').text()).toContain('No text given');
    });
});<commit_msg>Change edit mode to button in e2e tests<commit_after>'use strict'

describe('Flashcard editor', function() {

    beforeEach(function() {
        browser().navigateTo('/');
        restartDB();
        sleep(0.3);
        browser().navigateTo('/#/FlashcardList/someFlashcardListId1');
    });

    it("should contain edit button in preview mode", function() {
        // then
        expect(element('.flashcards-container > div:nth-child(1) .front button.edit:visible').count()).toBe(1);
    });

    it("should not contain edit button in edit mode", function() {
        // when
        element('.flashcards-container > div:nth-child(1) .front button.edit').click();

        // then
        expect(element('.flashcards-container > div:nth-child(1) .front button.edit:visible').count()).toBe(0);
    });

    it('should not contain the "save" button in preview mode', function() {
        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .save:visible').count()).toBe(0);
    });

    it('should contain the "save" button in edit mode', function() {
        // when
        element('.flashcards-container > div:nth-child(1) .front button.edit').click();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .save:visible').count()).toBe(1);
    });

    it('should save the new text upon editing', function() {
        // when
        element('.flashcards-container > div:nth-child(1) .front button.edit').click();
        element('.flashcards-container > div:nth-child(1) > .front textarea').val('brand *new* text');
        element('.flashcards-container > div:nth-child(1) > .front .save:visible').click();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .preview').html()).toContain('brand new text');
    });

    it('should save the new text upon refreshing the page', function() {
        // when
        element('.flashcards-container > div:nth-child(1) .front button.edit').click();
        element('.flashcards-container > div:nth-child(1) > .front textarea').val('brand *new* text');
        element('.flashcards-container > div:nth-child(1) > .front .save:visible').click();
        browser().reload();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .preview').html()).toContain('brand new text');
    });

    it('should have filling text when there is empty text', function() {
        // when
        element('.flashcards-container > div:nth-child(1) .front button.edit').click();
        element('.flashcards-container > div:nth-child(1) > .front textarea').val('');
        element('.flashcards-container > div:nth-child(1) > .front .save:visible').click();

        // then
        expect(element('.flashcards-container > div:nth-child(1) > .front .preview').text()).toContain('No text given');
    });
});<|endoftext|>


<commit_before>var GITHUB_INTEGRATION_ID = 1755
var GITHUB_PRIVATE_KEY = process.env.GITHUB_PRIVATE_KEY
var GIPHY_API_KEY = process.env.GIPHY_API_KEY

var jwt = require('jsonwebtoken')
var tools = require('./gitTools')
var request = require('request')

const getJWT = () => {
  return new Promise((resolve, reject) => {
    jwt.sign(
      {iss: GITHUB_INTEGRATION_ID},
      GITHUB_PRIVATE_KEY,
      {algorithm: 'RS256', expiresIn: '1m'},
      (err, token) => {
        if (err) { reject('There was a problem with the github certificate.') }
        else { resolve(token) }
      }
    )
  })
}

const getGiphyFromPullTitle = (title) => {
  return new Promise((resolve, reject) => {
    var searchTerms = encodeURIComponent(title)
    var giphySearchUrl = 'http://api.giphy.com/v1/gifs/search?q=' + searchTerms + '&api_key=' + GIPHY_API_KEY
    var giphyGifUrl = 'http://i.giphy.com/'

    request.get(
      {url: giphySearchUrl},
      (err, res, body) => {
        const {data} = body
        if (data && data.length) {
          let randomOne = data[Math.floor(Math.random() * data.length)]
          resolve('![](' + giphyGifUrl + randomOne.id + '.' + randomOne.type + ')')
        } else {
          reject()
        }
      }
    )
  })
}

const makeGithubFeatureDeployComments = ({
  installationId,
  pullUrl,
  message
}) => {
  getJWT().then((token) => {
    tools.getGithubToken(installationId, token).then((ghToken) => {
      tools.getPullRequest(pullUrl, ghToken).then((pull) => {
        if (message) {
          tools.commentOnPullRequest(pull.comments_url, message, ghToken).then((newComment) => {
            tools.getPullComments(pull.comments_url, ghToken).then((comments) => {
              var oldBotComments = comments.filter((c) => {c.user.id === newComment.user.id && c.id !== newComment.id})
              console.log(oldBotComments)
              // tools.deleteMultipleComments(oldBotComments, ghToken).then(() => {
              //
              // }) // end delete old bot comments
            }) // end getPullComments
          }) // end first comment
        }
      }) // end getPullRequest
    }) // end getGithubToken
  }).catch((e) => { console.log(e) }) // end getJWT
}

module.exports = {
  makeGithubFeatureDeployComments
}
<commit_msg>Add bug fix<commit_after>var GITHUB_INTEGRATION_ID = 1755
var GITHUB_PRIVATE_KEY = process.env.GITHUB_PRIVATE_KEY
var GIPHY_API_KEY = process.env.GIPHY_API_KEY

var jwt = require('jsonwebtoken')
var tools = require('./gitTools')
var request = require('request')

const getJWT = () => {
  return new Promise((resolve, reject) => {
    jwt.sign(
      {iss: GITHUB_INTEGRATION_ID},
      GITHUB_PRIVATE_KEY,
      {algorithm: 'RS256', expiresIn: '1m'},
      (err, token) => {
        if (err) { reject('There was a problem with the github certificate.') }
        else { resolve(token) }
      }
    )
  })
}

const getGiphyFromPullTitle = (title) => {
  return new Promise((resolve, reject) => {
    var searchTerms = encodeURIComponent(title)
    var giphySearchUrl = 'http://api.giphy.com/v1/gifs/search?q=' + searchTerms + '&api_key=' + GIPHY_API_KEY
    var giphyGifUrl = 'http://i.giphy.com/'

    request.get(
      {url: giphySearchUrl},
      (err, res, body) => {
        const {data} = body
        if (data && data.length) {
          let randomOne = data[Math.floor(Math.random() * data.length)]
          resolve('![](' + giphyGifUrl + randomOne.id + '.' + randomOne.type + ')')
        } else {
          reject()
        }
      }
    )
  })
}

const makeGithubFeatureDeployComments = ({
  installationId,
  pullUrl,
  message
}) => {
  getJWT().then((token) => {
    tools.getGithubToken(installationId, token).then((ghToken) => {
      console.log(ghToken)
      tools.getPullRequest(pullUrl, ghToken).then((pull) => {
        if (message) {
          tools.commentOnPullRequest(pull.comments_url, message, ghToken).then((newComment) => {
            tools.getPullComments(pull.comments_url, ghToken).then((comments) => {
              var oldBotComments = comments.filter((c) => {c.user.id === newComment.user.id && c.id !== newComment.id})
              console.log(oldBotComments)
              // tools.deleteMultipleComments(oldBotComments, ghToken).then(() => {
              //
              // }) // end delete old bot comments
            }) // end getPullComments
          }) // end first comment
        }
      }) // end getPullRequest
    }) // end getGithubToken
  }).catch((e) => { console.log(e) }) // end getJWT
}

module.exports = {
  makeGithubFeatureDeployComments
}
<|endoftext|>