<commit_before>/*  Copyright (c) 2018, Klendi Gocci.

    17 March, 2018
    https://github.com/klendi
    https://twitter.com/klendigocci

    ------------------------------------------------------------------------
    Explains a word or a sentence from urban-dictionary API

    The following command is uisng a free API from http://urbandictionary.com/
    The API request can be found here: http://api.urbandictionary.com/v0/

    Usage:
      !urban <Any Word Or Sentence Here>

    Example:
      !urban gtg

    GTG
      ------ Definition ------
      Internet shorthand for "got to go". Also it can mean "good to go" depending on contex
      ------ Second Definition ------
      got to go

      ------ First Example ------
      Good to go:
      "Say im heading out. You coming?"
      "gtg"

      Got to go:
      "Shoot, it's almost midnight gtg."
      ------ Second Example ------
      Rachel I gtg
    ------------------------------------------------------------------------

*/
'use strict'
const Discord = require('discord.js');
const Subiex = require('../bot.js');
const http = require('http')

var methods = {}
var randomCache = []

Subiex.registerCommand('urban', 'default', (message) => {
    let msg = message.content + '';

    term(msg, function(error, entries) {
        if (error) {
            console.error(error.message)
            message.channel.send(error.message);
        } else {
            if (entries.length == 1) {
                message.channel.send({
                    embed: {
                        color: 9384170,
                        title: '**' + entries[0].word + '**',
                        fields: [{
                                name: "Definition",
                                value: entries[0].definition
                            },
                            {
                                name: "**Example**",
                                value: entries[0].example
                            },
                        ],
                    }
                });
            } else if (entries.length > 1) {
                if (entries[0].definition.length < 1024 && entries[1].definition.length < 1024 && entries[0].example.length < 1024 && entries[0].example.length < 1024) {
                    message.channel.send({
                        embed: {
                            color: 9384170,
                            title: '**' + entries[0].word + '**',
                            fields: [{
                                    name: "Definition",
                                    value: entries[0].definition,
                                },
                                {
                                    name: 'Second Definition',
                                    value: entries[1].definition,
                                },
                                {
                                    name: "**First Example**",
                                    value: entries[0].example,
                                },
                                {
                                    name: "**Second Example**",
                                    value: entries[1].example,
                                },
                            ],
                        }
                    });
                } else {
                    console.log("Error");
                    console.log("Length of entries[0].definition " + entries[0].definition.length);
                    console.log("Length of entries[1].definition " + entries[1].definition.length);
                    console.log("Length of entries[1].example " + entries[1].example.length);
                    console.log("Length of entries[0].example " + entries[0].example.length);

                }
            }
        }
    })

}, ['urban', 'urban', 'urban-dict'], 'Get urban dictionary word explanation!', '[]')

function get(url, callback) {
    http.get(url, function(result) {
        const contentType = result.headers['content-type']
        const statusCode = result.statusCode

        let error
        if (statusCode !== 200) {
            error = new Error('Unable to send request for definitions. Status code: ' + statusCode)
        } else if (contentType.indexOf('application/json') === -1) {
            error = new Error("Content retrieved isn't JSON. Content type: '" + contentType + "'")
        }

        if (error) {
            // Removes response data to clear up memory.
            result.resume()
            callback(error)
            return
        }

        result.setEncoding('utf8')

        let rawData = ''
        result.on('data', function(buffer) {
            rawData += buffer
        })
        result.on('end', function() {
            try {
                callback(null, JSON.parse(rawData))
            } catch (error) {
                callback(new Error('Failed to parse retrieved Urban Dictionary JSON.'))
                console.log('rawData is: ' + rawData)
            }
        })
    })
}

function term(word, callback) {
    get('http://api.urbandictionary.com/v0/define?term=' + encodeURIComponent(word), function(error, result) {
        if (error) {
            callback(error)
            return
        }

        if (!result || result.result_type !== 'exact') {
            callback(new Error(word + ' is undefined.'))
            return
        }

        callback(null, result.list)
    })
}<commit_msg>Urban Dict Fix<commit_after>/*  Copyright (c) 2018, Klendi Gocci.

    17 March, 2018
    https://github.com/klendi
    https://twitter.com/klendigocci

    ------------------------------------------------------------------------
    Explains a word or a sentence from urban-dictionary API

    The following command is uisng a free API from http://urbandictionary.com/
    The API request can be found here: http://api.urbandictionary.com/v0/

    Usage:
      !urban <Any Word Or Sentence Here>

    Example:
      !urban gtg

    GTG
      ------ Definition ------
      Internet shorthand for "got to go". Also it can mean "good to go" depending on contex
      ------ Second Definition ------
      got to go

      ------ First Example ------
      Good to go:
      "Say im heading out. You coming?"
      "gtg"

      Got to go:
      "Shoot, it's almost midnight gtg."
      ------ Second Example ------
      Rachel I gtg
    ------------------------------------------------------------------------

*/
'use strict'
const Discord = require('discord.js');
const Subiex = require('../bot.js');
const http = require('http')

var methods = {}
var randomCache = []

Subiex.registerCommand('urban', 'default', (message) => {
    let msg = message.content + '';

    term(msg, function(error, entries) {
        if (error) {
            console.error(error.message)
            message.channel.send(error.message);
        } else {
            if (entries.length == 1) {
                message.channel.send({
                    embed: {
                        color: 9384170,
                        title: '**' + entries[0].word + '**',
                        fields: [{
                                name: "Definition",
                                value: entries[0].definition
                            },
                            {
                                name: "**Example**",
                                value: entries[0].example
                            },
                        ],
                    }
                });
            } else if (entries.length > 1) {
                if (entries[0].definition.length < 1024 && entries[1].definition.length < 1024 && entries[0].example.length < 1024 && entries[0].example.length < 1024) {
                    message.channel.send({
                        embed: {
                            color: 9384170,
                            title: '**' + entries[0].word + '**',
                            fields: [{
                                    name: "Definition",
                                    value: entries[0].definition,
                                },
                                {
                                    name: 'Second Definition',
                                    value: entries[1].definition,
                                },
                                {
                                    name: "**First Example**",
                                    value: entries[0].example,
                                },
                                {
                                    name: "**Second Example**",
                                    value: entries[1].example,
                                },
                            ],
                        }
                    });
                } else {
                    console.log("Error");
                    console.log("Length of entries[0].definition " + entries[0].definition.length);
                    console.log("Length of entries[1].definition " + entries[1].definition.length);
                    console.log("Length of entries[1].example " + entries[1].example.length);
                    console.log("Length of entries[0].example " + entries[0].example.length);

                }
            }
        }
    })

}, ['urban', 'urban', 'urban-dict'], 'Get urban dictionary word explanation!', '[]')

function get(url, callback) {
    http.get(url, function(result) {
        const contentType = result.headers['content-type']
        const statusCode = result.statusCode

        let error
        if (statusCode !== 200) {
            error = new Error('Unable to send request for definitions. Status code: ' + statusCode)
        } else if (contentType.indexOf('application/json') === -1) {
            error = new Error("Content retrieved isn't JSON. Content type: '" + contentType + "'")
        }

        if (error) {
            // Removes response data to clear up memory.
            result.resume()
            callback(error)
            return
        }

        result.setEncoding('utf8')

        let rawData = ''
        result.on('data', function(buffer) {
            rawData += buffer
        })
        result.on('end', function() {
            try {
                callback(null, JSON.parse(rawData))
            } catch (error) {
                callback(new Error('Failed to parse retrieved Urban Dictionary JSON.'))
                console.log('rawData is: ' + rawData)
            }
        })
    })
}

function term(word, callback) {
    get('http://api.urbandictionary.com/v0/define?term=' + encodeURIComponent(word), function(error, result) {
        if (error) {
            callback(error)
            return
        }

        if (!result) {
            callback(new Error(word + ' is undefined.'))
            return
        }

        callback(null, result.list)
    })
}<|endoftext|>


<commit_before>
/**
 * Copyright (c) 2016-present, Viro Media, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ViroTextStylePropTypes
 * @flow
 */
'use strict';

var ColorPropType = require('react-native').ColorPropType;
var ViroStylePropTypes = require('./ViroPropTypes');
var PropTypes = require('react/lib/ReactPropTypes');

var ViroTextStylePropTypes =  Object.assign(Object.create(ViroStylePropTypes), {
  color: ColorPropType,
  fontFamily: PropTypes.string,
  fontSize: PropTypes.number,

  /**
   * Specifies text alignment.
   */
  textAlign: PropTypes.oneOf(
    [ 'left'/*default*/, 'right', 'center', 'justify']
  ),

  textAlignVertical: PropTypes.oneOf(
    ['top' /*default*/, 'bottom', 'center']
  ),

  textClipMode: PropTypes.oneOf(['none', 'clipToBounds']),
  textLineBreakMode: PropTypes.oneOf(['wordwrap','charwrap','justify','none'])
});

module.exports = ViroTextStylePropTypes;
<commit_msg>VIRO-1077: remove justify from text alignment<commit_after>
/**
 * Copyright (c) 2016-present, Viro Media, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ViroTextStylePropTypes
 * @flow
 */
'use strict';

var ColorPropType = require('react-native').ColorPropType;
var ViroStylePropTypes = require('./ViroPropTypes');
var PropTypes = require('react/lib/ReactPropTypes');

var ViroTextStylePropTypes =  Object.assign(Object.create(ViroStylePropTypes), {
  color: ColorPropType,
  fontFamily: PropTypes.string,
  fontSize: PropTypes.number,

  /**
   * Specifies text alignment.
   */
  textAlign: PropTypes.oneOf(
    [ 'left'/*default*/, 'right', 'center']
  ),

  textAlignVertical: PropTypes.oneOf(
    ['top' /*default*/, 'bottom', 'center']
  ),

  textClipMode: PropTypes.oneOf(['none', 'clipToBounds']),
  textLineBreakMode: PropTypes.oneOf(['wordwrap','charwrap','justify','none'])
});

module.exports = ViroTextStylePropTypes;
<|endoftext|>


<commit_before>/*
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
(
/**
* @param {Window} window
* @param {undefined} undefined
*/
function (window, undefined) {
var AscBrowser = {
    userAgent : "",
    isIE : false,
    isMacOs : false,
    isSafariMacOs : false,
    isAppleDevices : false,
    isAndroid : false,
    isMobile : false,
    isGecko : false,
    isChrome : false,
    isOpera : false,
    isWebkit : false,
    isSafari : false,
    isArm : false,
    isMozilla : false,
	isRetina : false,
    isLinuxOS : false,
	retinaPixelRatio : 1,
	isVivaldiLinux : false
};

// user agent lower case
AscBrowser.userAgent = navigator.userAgent.toLowerCase();

// ie detect
AscBrowser.isIE =  (AscBrowser.userAgent.indexOf("msie") > -1 ||
                    AscBrowser.userAgent.indexOf("trident") > -1 ||
					AscBrowser.userAgent.indexOf("edge") > -1);

AscBrowser.isIeEdge = (AscBrowser.userAgent.indexOf("edge/") > -1);

AscBrowser.isIE9 =  (AscBrowser.userAgent.indexOf("msie9") > -1 || AscBrowser.userAgent.indexOf("msie 9") > -1);
AscBrowser.isIE10 =  (AscBrowser.userAgent.indexOf("msie10") > -1 || AscBrowser.userAgent.indexOf("msie 10") > -1);

// macOs detect
AscBrowser.isMacOs = (AscBrowser.userAgent.indexOf('mac') > -1);

// chrome detect
AscBrowser.isChrome = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("chrome") > -1);

// safari detect
AscBrowser.isSafari = !AscBrowser.isIE && !AscBrowser.isChrome && (AscBrowser.userAgent.indexOf("safari") > -1);

// macOs safari detect
AscBrowser.isSafariMacOs = (AscBrowser.isSafari && AscBrowser.isMacOs);

// apple devices detect
AscBrowser.isAppleDevices = (AscBrowser.userAgent.indexOf("ipad") > -1 ||
                             AscBrowser.userAgent.indexOf("iphone") > -1 ||
                             AscBrowser.userAgent.indexOf("ipod") > -1);

// android devices detect
AscBrowser.isAndroid = (AscBrowser.userAgent.indexOf("android") > -1);

// mobile detect
AscBrowser.isMobile = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent || navigator.vendor || window.opera);

// gecko detect
AscBrowser.isGecko = (AscBrowser.userAgent.indexOf("gecko/") > -1);

// opera detect
AscBrowser.isOpera = (!!window.opera || AscBrowser.userAgent.indexOf("opr/") > -1);

// webkit detect
AscBrowser.isWebkit = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("webkit") > -1);

// arm detect
AscBrowser.isArm = (AscBrowser.userAgent.indexOf("arm") > -1);

AscBrowser.isMozilla = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("firefox") > -1);

AscBrowser.isLinuxOS = (AscBrowser.userAgent.indexOf(" linux ") > -1);

AscBrowser.isVivaldiLinux = AscBrowser.isLinuxOS && (AscBrowser.userAgent.indexOf("vivaldi") > -1);

AscBrowser.zoom = 1;

AscBrowser.checkZoom = function()
{
    if (AscBrowser.isAndroid)
	{
		AscBrowser.isRetina = (window.devicePixelRatio >= 1.9);
		AscBrowser.retinaPixelRatio = window.devicePixelRatio;
		return;
	}

	AscBrowser.zoom = 1.0;
	AscBrowser.isRetina = false;
	AscBrowser.retinaPixelRatio = 1;

    if (AscBrowser.isChrome && !AscBrowser.isOpera && !AscBrowser.isMobile && document && document.firstElementChild && document.body)
    {
        if (false)
		{
			// этот код - рабочий, но только если этот ифрейм открыт на весь размер браузера
            // (window.outerWidth и window.innerWidth зависимы)
			if (window.innerWidth > 300)
				AscBrowser.zoom = window.outerWidth / window.innerWidth;

			if (Math.abs(AscBrowser.zoom - 1) < 0.1)
				AscBrowser.zoom = 1;

			AscBrowser.zoom = window.outerWidth / window.innerWidth;

			var _devicePixelRatio = window.devicePixelRatio / AscBrowser.zoom;

			// device pixel ratio: кратно 0.5
			_devicePixelRatio = (5 * (((2.5 + 10 * _devicePixelRatio) / 5) >> 0)) / 10;

			AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
			if (2 == _devicePixelRatio)
				AscBrowser.isRetina = true;

			// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
			//document.firstElementChild.style.zoom = "reset";
			document.firstElementChild.style.zoom = 1.0 / AscBrowser.zoom;
		}
		else
        {
            // делаем простую проверку
            // считаем: 0 < window.devicePixelRatio < 2 => _devicePixelRatio = 1; zoom = window.devicePixelRatio / _devicePixelRatio;
			// считаем: window.devicePixelRatio >= 2 => _devicePixelRatio = 2; zoom = window.devicePixelRatio / _devicePixelRatio;
            if (window.devicePixelRatio > 0.1)
			{
				if (window.devicePixelRatio < 1.99)
				{
					var _devicePixelRatio = 1;
					AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
				}
				else
				{
					var _devicePixelRatio = 2;
					AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
					AscBrowser.isRetina = true;
				}
				// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
				//document.firstElementChild.style.zoom = "reset";
				document.firstElementChild.style.zoom = 1.0 / AscBrowser.zoom;
			}
			else
				document.firstElementChild.style.zoom = "normal";
        }

        if (AscBrowser.isRetina)
        	AscBrowser.retinaPixelRatio = 2;
    }
    else
    {
		AscBrowser.isRetina = (Math.abs(2 - (window.devicePixelRatio / AscBrowser.zoom)) < 0.01);
		if (AscBrowser.isRetina)
			AscBrowser.retinaPixelRatio = 2;

		if (AscBrowser.isMobile)
		{
			AscBrowser.isRetina = (window.devicePixelRatio >= 1.9);
			AscBrowser.retinaPixelRatio = window.devicePixelRatio;
		}
    }
};

AscBrowser.checkZoom();

AscBrowser.convertToRetinaValue = function(value, isScale)
{
	if (isScale === true)
		return ((value * AscBrowser.retinaPixelRatio) + 0.5) >> 0;
	else
		return ((value / AscBrowser.retinaPixelRatio) + 0.5) >> 0;
};

    //--------------------------------------------------------export----------------------------------------------------
    window['AscCommon'] = window['AscCommon'] || {};
    window['AscCommon'].AscBrowser = AscBrowser;
})(window);
<commit_msg>Fix bug 40527<commit_after>/*
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
(
/**
* @param {Window} window
* @param {undefined} undefined
*/
function (window, undefined) {
var AscBrowser = {
    userAgent : "",
    isIE : false,
    isMacOs : false,
    isSafariMacOs : false,
    isAppleDevices : false,
    isAndroid : false,
    isMobile : false,
    isGecko : false,
    isChrome : false,
    isOpera : false,
	isOperaOld : false,
    isWebkit : false,
    isSafari : false,
    isArm : false,
    isMozilla : false,
	isRetina : false,
    isLinuxOS : false,
	retinaPixelRatio : 1,
	isVivaldiLinux : false
};

// user agent lower case
AscBrowser.userAgent = navigator.userAgent.toLowerCase();

// ie detect
AscBrowser.isIE =  (AscBrowser.userAgent.indexOf("msie") > -1 ||
                    AscBrowser.userAgent.indexOf("trident") > -1 ||
					AscBrowser.userAgent.indexOf("edge") > -1);

AscBrowser.isIeEdge = (AscBrowser.userAgent.indexOf("edge/") > -1);

AscBrowser.isIE9 =  (AscBrowser.userAgent.indexOf("msie9") > -1 || AscBrowser.userAgent.indexOf("msie 9") > -1);
AscBrowser.isIE10 =  (AscBrowser.userAgent.indexOf("msie10") > -1 || AscBrowser.userAgent.indexOf("msie 10") > -1);

// macOs detect
AscBrowser.isMacOs = (AscBrowser.userAgent.indexOf('mac') > -1);

// chrome detect
AscBrowser.isChrome = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("chrome") > -1);

// safari detect
AscBrowser.isSafari = !AscBrowser.isIE && !AscBrowser.isChrome && (AscBrowser.userAgent.indexOf("safari") > -1);

// macOs safari detect
AscBrowser.isSafariMacOs = (AscBrowser.isSafari && AscBrowser.isMacOs);

// apple devices detect
AscBrowser.isAppleDevices = (AscBrowser.userAgent.indexOf("ipad") > -1 ||
                             AscBrowser.userAgent.indexOf("iphone") > -1 ||
                             AscBrowser.userAgent.indexOf("ipod") > -1);

// android devices detect
AscBrowser.isAndroid = (AscBrowser.userAgent.indexOf("android") > -1);

// mobile detect
AscBrowser.isMobile = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent || navigator.vendor || window.opera);

// gecko detect
AscBrowser.isGecko = (AscBrowser.userAgent.indexOf("gecko/") > -1);

// opera detect
AscBrowser.isOpera = (!!window.opera || AscBrowser.userAgent.indexOf("opr/") > -1);
AscBrowser.isOperaOld = (!!window.opera);

// webkit detect
AscBrowser.isWebkit = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("webkit") > -1);

// arm detect
AscBrowser.isArm = (AscBrowser.userAgent.indexOf("arm") > -1);

AscBrowser.isMozilla = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("firefox") > -1);

AscBrowser.isLinuxOS = (AscBrowser.userAgent.indexOf(" linux ") > -1);

AscBrowser.isVivaldiLinux = AscBrowser.isLinuxOS && (AscBrowser.userAgent.indexOf("vivaldi") > -1);

AscBrowser.zoom = 1;

AscBrowser.checkZoom = function()
{
    if (AscBrowser.isAndroid)
	{
		AscBrowser.isRetina = (window.devicePixelRatio >= 1.9);
		AscBrowser.retinaPixelRatio = window.devicePixelRatio;
		return;
	}

	AscBrowser.zoom = 1.0;
	AscBrowser.isRetina = false;
	AscBrowser.retinaPixelRatio = 1;

    if (AscBrowser.isChrome && !AscBrowser.isOperaOld && !AscBrowser.isMobile && document && document.firstElementChild && document.body)
    {
        if (false)
		{
			// этот код - рабочий, но только если этот ифрейм открыт на весь размер браузера
            // (window.outerWidth и window.innerWidth зависимы)
			if (window.innerWidth > 300)
				AscBrowser.zoom = window.outerWidth / window.innerWidth;

			if (Math.abs(AscBrowser.zoom - 1) < 0.1)
				AscBrowser.zoom = 1;

			AscBrowser.zoom = window.outerWidth / window.innerWidth;

			var _devicePixelRatio = window.devicePixelRatio / AscBrowser.zoom;

			// device pixel ratio: кратно 0.5
			_devicePixelRatio = (5 * (((2.5 + 10 * _devicePixelRatio) / 5) >> 0)) / 10;

			AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
			if (2 == _devicePixelRatio)
				AscBrowser.isRetina = true;

			// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
			//document.firstElementChild.style.zoom = "reset";
			document.firstElementChild.style.zoom = 1.0 / AscBrowser.zoom;
		}
		else
        {
            // делаем простую проверку
            // считаем: 0 < window.devicePixelRatio < 2 => _devicePixelRatio = 1; zoom = window.devicePixelRatio / _devicePixelRatio;
			// считаем: window.devicePixelRatio >= 2 => _devicePixelRatio = 2; zoom = window.devicePixelRatio / _devicePixelRatio;
            if (window.devicePixelRatio > 0.1)
			{
				if (window.devicePixelRatio < 1.99)
				{
					var _devicePixelRatio = 1;
					AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
				}
				else
				{
					var _devicePixelRatio = 2;
					AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
					AscBrowser.isRetina = true;
				}
				// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
				//document.firstElementChild.style.zoom = "reset";
				document.firstElementChild.style.zoom = 1.0 / AscBrowser.zoom;
			}
			else
				document.firstElementChild.style.zoom = "normal";
        }

        if (AscBrowser.isRetina)
        	AscBrowser.retinaPixelRatio = 2;
    }
    else
    {
		AscBrowser.isRetina = (Math.abs(2 - (window.devicePixelRatio / AscBrowser.zoom)) < 0.01);
		if (AscBrowser.isRetina)
			AscBrowser.retinaPixelRatio = 2;

		if (AscBrowser.isMobile)
		{
			AscBrowser.isRetina = (window.devicePixelRatio >= 1.9);
			AscBrowser.retinaPixelRatio = window.devicePixelRatio;
		}
    }
};

AscBrowser.checkZoom();

AscBrowser.convertToRetinaValue = function(value, isScale)
{
	if (isScale === true)
		return ((value * AscBrowser.retinaPixelRatio) + 0.5) >> 0;
	else
		return ((value / AscBrowser.retinaPixelRatio) + 0.5) >> 0;
};

    //--------------------------------------------------------export----------------------------------------------------
    window['AscCommon'] = window['AscCommon'] || {};
    window['AscCommon'].AscBrowser = AscBrowser;
})(window);
<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    reset();
    thenSwitch = nowSwitch;
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught + ".         Timer : " + parseInt(countDown / 100), 32, 32);
};

var gameOver = function () {

};

var main = function () {
  now = Date.now();
  var delta = now - then;

  var nowSwitch = Date.now();
  countDown = nowSwitch - thenSwitch;

  update(delta / 1000);
  if (countDown >= 900) {
    thenSwitch = nowSwitch;
    reset();
  }
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown = 0;
var lives = 5;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<commit_msg>Update canvas2.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    reset();
    thenSwitch = nowSwitch;
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught + ".         Lives : " + lives, 32, 32);
};

var gameOver = function () {

};

var main = function () {
  now = Date.now();
  var delta = now - then;

  var nowSwitch = Date.now();
  countDown = nowSwitch - thenSwitch;

  update(delta / 1000);
  if (countDown >= 900) {
    thenSwitch = nowSwitch;
    reset();
  }
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown = 0;
var lives = 5;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<|endoftext|>


<commit_before>linkify = {
  // Static values used in creating the URL regexes
  RE_EMAIL_PATTERN: '\\b[\\w.-]+\\+*[\\w.-]+@(?:(?:[\\w-]+\\.)+[A-Za-z]{2,6}|(?:\\d{1,3}\\.){3}\\d{1,3})',
  RE_TLD: '(?:aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)',
  RE_URL_MIDCHAR: '[\\w\\.,@?^=%*"&,:;/~\+#\'|-]',  // characters allowed in URL center
  RE_URL_ENDCHAR: '[\\w@?^=%&/~\+#-]',              // URL must end with one of these chars
  RE_URL_SCHEME: '(?:http|ftp|https|news|mms)://',  // protocol

  // Text to turn in to emoticon images
  // "8)" must have a non-word character before it to protect "(2007-2008)" case
  emoticons: [
    {regex: ':-?D',     shortcut: ':D',   width: 18,  height: 18,    image: 'bigsmile.png'},
    {regex: ':-?o',     shortcut: ':o',   width: 18,  height: 18,    image: 'gasp.png'},
    {regex: ':-?p',     shortcut: ':p',   width: 18,  height: 18,    image: 'tongue.png'},
    {regex: '8-?\\)',   shortcut: '8)',   width: 18,  height: 18,    image: 'cool.png'},
    {regex: ':-?\\(',   shortcut: ':(',   width: 18,  height: 18,    image: 'frown.png'},
    {regex: ':-\\*',    shortcut: ':-*',  width: 18,  height: 18,    image: 'kiss.png'},
    {regex: ':\\\\',    shortcut: ':\\',  width: 18,  height: 18,    image: 'slant.png'},
    {regex: ':-?\\)',   shortcut: ':)',   width: 18,  height: 18,    image: 'smile.png'},
    {regex: ':-?\\|',   shortcut: ':|',   width: 18,  height: 18,    image: 'straightface.png'},
    {regex: ';-?\\)',   shortcut: ';)',   width: 18,  height: 18,    image: 'wink.png'}
  ],

  // Intialize the linkification variables
  // Call this before calling linkify(...)
  init: function() {
    this.RE_URL_ENDING = '(?:'+this.RE_URL_MIDCHAR+'*(?:\\('+this.RE_URL_MIDCHAR+'*\\)'+this.RE_URL_ENDCHAR+'*|'+this.RE_URL_ENDCHAR+'))?';
    this.RE_FULL_URL = this.RE_URL_SCHEME+'\\w+(?:.\\w+)'+this.RE_URL_ENDING;
    this.RE_OTHER_URL = '\\w[\\w_-]*(?:\\.\\w[\\w_-]*)*\\.'+this.RE_TLD+'(?:\\/'+this.RE_URL_ENDING+')?\\b';
  },

  /**
   * Add an word-based emoticon to the list of emoticons to check for
   *
   * @param filename - Name of the image file (the full path is created in the emoticon_text function)
   * @param shortcut - Text used to create the emoticon (e.g. "embarrassed" or "puking" )
   * @param height - Height in pixels of the image
   * @param width - Width in pixels of the image
   **/
  add_emoticon: function(filename, shortcut, height, width) {
    var emoticon_data = {
      image: filename,
      shortcut: shortcut,
      height: height,
      width: width,
      regex: '\\('+shortcut+'\\)',
      shortcut: '('+shortcut+')'
    };
    this.emoticons.push(emoticon_data);
  },

  /**
   * Linkify a string, replacing text urls with url
   * Note: init must be called before this function can be used
   *
   * @param text - String to be linkified
   * @param emoticonify - Whether to replace text emoticons with images
   * @param matched_links - Return param (pass by ref) - Array of links matched during linkification
   **/
  linkify: function(text, emoticonify, truncate_length, matched_links) {
    if (typeof emoticonify == 'undefined') {
      emoticonify = true;
    }

    if (typeof matched_links == 'undefined') {
      match_and_replace = [];
    }

    text = this.match_and_replace(this.RE_EMAIL_PATTERN, text, false, false, truncate_length, matched_links);
    text = this.match_and_replace(this.RE_FULL_URL, text, true, false, truncate_length, matched_links);
    text = this.match_and_replace(this.RE_OTHER_URL, text, true, true, truncate_length, matched_links);

    if (emoticonify) {
      text = this.emoticon_text(text);
    }

    return text;
  },

  /**
   * Internal helper function for linkification
   **/
  match_and_replace: function(pattern, input, is_url, add_http, truncate_length, matched_links) {
    if (typeof add_http == 'undefined') {
      add_http = true;
    }

    var start = 0;
    var offset = 0;
    var match_length = 0;
    var end_tag_pos = 0;
    var close_anchor_re = /<\/[aA]>/;
    var re = new RegExp(pattern, "g");

    var match = {};
    var max_iter = 20;
    var cur_iter = 0;
    while (match = re.exec(input)) {
      cur_iter++;
      if (cur_iter > max_iter)
        break;

      start = match.index; // start of match
      match_length = match[0].length;

      // If we find an opening a tag, advance to its end and continue looking
      var substr = input.substring(offset, start);
      if (substr.search(/<[aA]/) >= 0) {
        close_anchor_re.lastIndex = offset;
        var close_anchor_pos = input.substring(offset, input.length).search(close_anchor_re);

        // If we find an opening tag without a matching closing tag, just return the input we have
        if (close_anchor_pos < 0)
          return input;

        end_tag_pos = close_anchor_pos + offset;

        // RegExp.lastIndex is used to tell the regexp where to start matching
        re.lastIndex = end_tag_pos + 4;
        offset = end_tag_pos + 4;

        continue;
      }

      // Do the actual replecement of text with anchor tag
      var address = input.substr(start, match_length);
      var actual = input.substr(start, match_length);

      if (add_http) {
        actual = 'http://'+actual;
      }
      var replacement = ' truncate_length) {
            address = address.substr(0, truncate_length) + '...';
        }

      // Add word break tags to allow wrapping where appropriate
      replacement += '>'+address.replace(new RegExp("([/=])", 'g'), "<wbr>$1")+'';
      if (matched_links) {
        matched_links.push(actual);
      }

      input = input.slice(0, start) + replacement + input.slice(start+match_length, input.length);
      re.lastIndex = start + replacement.length;
      offset = start + replacement.length;
    }

    return input;
  },

  /**
   * Replace text emoticons with images
   **/
  emoticon_text: function(text) {
    for (var idx in this.emoticons) {
      var e_data = this.emoticons[idx];
      var regex = e_data.regex;
      var img = e_data.image;

      // (not a word character)(smiley regex)(not a word character)
      var pattern = new RegExp('(^|\\W)'+regex+'(?=\\W|$)', 'gim');
      text = text.replace(pattern, '$1');
    }
    return text;
  }
};
<commit_msg>Escape quotes in links<commit_after>linkify = {
  // Static values used in creating the URL regexes
  RE_EMAIL_PATTERN: '\\b[\\w.-]+\\+*[\\w.-]+@(?:(?:[\\w-]+\\.)+[A-Za-z]{2,6}|(?:\\d{1,3}\\.){3}\\d{1,3})',
  RE_TLD: '(?:aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)',
  RE_URL_MIDCHAR: '[\\w\\.,@?^=%*"&,:;/~\+#\'|-]',  // characters allowed in URL center
  RE_URL_ENDCHAR: '[\\w@?^=%&/~\+#-]',              // URL must end with one of these chars
  RE_URL_SCHEME: '(?:http|ftp|https|news|mms)://',  // protocol

  // Text to turn in to emoticon images
  // "8)" must have a non-word character before it to protect "(2007-2008)" case
  emoticons: [
    {regex: ':-?D',     shortcut: ':D',   width: 18,  height: 18,    image: 'bigsmile.png'},
    {regex: ':-?o',     shortcut: ':o',   width: 18,  height: 18,    image: 'gasp.png'},
    {regex: ':-?p',     shortcut: ':p',   width: 18,  height: 18,    image: 'tongue.png'},
    {regex: '8-?\\)',   shortcut: '8)',   width: 18,  height: 18,    image: 'cool.png'},
    {regex: ':-?\\(',   shortcut: ':(',   width: 18,  height: 18,    image: 'frown.png'},
    {regex: ':-\\*',    shortcut: ':-*',  width: 18,  height: 18,    image: 'kiss.png'},
    {regex: ':\\\\',    shortcut: ':\\',  width: 18,  height: 18,    image: 'slant.png'},
    {regex: ':-?\\)',   shortcut: ':)',   width: 18,  height: 18,    image: 'smile.png'},
    {regex: ':-?\\|',   shortcut: ':|',   width: 18,  height: 18,    image: 'straightface.png'},
    {regex: ';-?\\)',   shortcut: ';)',   width: 18,  height: 18,    image: 'wink.png'}
  ],

  // Intialize the linkification variables
  // Call this before calling linkify(...)
  init: function() {
    this.RE_URL_ENDING = '(?:'+this.RE_URL_MIDCHAR+'*(?:\\('+this.RE_URL_MIDCHAR+'*\\)'+this.RE_URL_ENDCHAR+'*|'+this.RE_URL_ENDCHAR+'))?';
    this.RE_FULL_URL = this.RE_URL_SCHEME+'\\w+(?:.\\w+)'+this.RE_URL_ENDING;
    this.RE_OTHER_URL = '\\w[\\w_-]*(?:\\.\\w[\\w_-]*)*\\.'+this.RE_TLD+'(?:\\/'+this.RE_URL_ENDING+')?\\b';
  },

  /**
   * Add an word-based emoticon to the list of emoticons to check for
   *
   * @param filename - Name of the image file (the full path is created in the emoticon_text function)
   * @param shortcut - Text used to create the emoticon (e.g. "embarrassed" or "puking" )
   * @param height - Height in pixels of the image
   * @param width - Width in pixels of the image
   **/
  add_emoticon: function(filename, shortcut, height, width) {
    var emoticon_data = {
      image: filename,
      shortcut: shortcut,
      height: height,
      width: width,
      regex: '\\('+shortcut+'\\)',
      shortcut: '('+shortcut+')'
    };
    this.emoticons.push(emoticon_data);
  },

  /**
   * Linkify a string, replacing text urls with url
   * Note: init must be called before this function can be used
   *
   * @param text - String to be linkified
   * @param emoticonify - Whether to replace text emoticons with images
   * @param matched_links - Return param (pass by ref) - Array of links matched during linkification
   **/
  linkify: function(text, emoticonify, truncate_length, matched_links) {
    if (typeof emoticonify == 'undefined') {
      emoticonify = true;
    }

    if (typeof matched_links == 'undefined') {
      match_and_replace = [];
    }

    text = this.match_and_replace(this.RE_EMAIL_PATTERN, text, false, false, truncate_length, matched_links);
    text = this.match_and_replace(this.RE_FULL_URL, text, true, false, truncate_length, matched_links);
    text = this.match_and_replace(this.RE_OTHER_URL, text, true, true, truncate_length, matched_links);

    if (emoticonify) {
      text = this.emoticon_text(text);
    }

    return text;
  },

  /**
   * Internal helper function for linkification
   **/
  match_and_replace: function(pattern, input, is_url, add_http, truncate_length, matched_links) {
    if (typeof add_http == 'undefined') {
      add_http = true;
    }

    var start = 0;
    var offset = 0;
    var match_length = 0;
    var end_tag_pos = 0;
    var close_anchor_re = /<\/[aA]>/;
    var re = new RegExp(pattern, "g");

    var match = {};
    var max_iter = 20;
    var cur_iter = 0;
    while (match = re.exec(input)) {
      cur_iter++;
      if (cur_iter > max_iter)
        break;

      start = match.index; // start of match
      match_length = match[0].length;

      // If we find an opening a tag, advance to its end and continue looking
      var substr = input.substring(offset, start);
      if (substr.search(/<[aA]/) >= 0) {
        close_anchor_re.lastIndex = offset;
        var close_anchor_pos = input.substring(offset, input.length).search(close_anchor_re);

        // If we find an opening tag without a matching closing tag, just return the input we have
        if (close_anchor_pos < 0)
          return input;

        end_tag_pos = close_anchor_pos + offset;

        // RegExp.lastIndex is used to tell the regexp where to start matching
        re.lastIndex = end_tag_pos + 4;
        offset = end_tag_pos + 4;

        continue;
      }

      // Do the actual replecement of text with anchor tag
      var address = input.substr(start, match_length);
      var actual = input.substr(start, match_length);

      if (add_http) {
        actual = 'http://'+actual;
      }
      var replacement = ' truncate_length) {
            address = address.substr(0, truncate_length) + '...';
        }

      // Add word break tags to allow wrapping where appropriate
      replacement += '>'+address.replace(new RegExp("([/=])", 'g'), "<wbr>$1")+'';
      if (matched_links) {
        matched_links.push(actual);
      }

      input = input.slice(0, start) + replacement + input.slice(start+match_length, input.length);
      re.lastIndex = start + replacement.length;
      offset = start + replacement.length;
    }

    return input;
  },

  /**
   * Replace text emoticons with images
   **/
  emoticon_text: function(text) {
    for (var idx in this.emoticons) {
      var e_data = this.emoticons[idx];
      var regex = e_data.regex;
      var img = e_data.image;

      // (not a word character)(smiley regex)(not a word character)
      var pattern = new RegExp('(^|\\W)'+regex+'(?=\\W|$)', 'gim');
      text = text.replace(pattern, '$1');
    }
    return text;
  }
};
<|endoftext|>


<commit_before>$(function() {
  var urls = [];

  function redraw() {
    $(".js-urls").empty();
    urls.forEach(function(item, idx) {
      $(".js-urls").append("
" + item + " Remove
");
    });
    $(".js-delete").click(function() {
      deleteUrl(parseInt($(this).attr("data-id")));
    });
  }

  function load() {
    try {
      urls = JSON.parse(localStorage.getItem("urls"));
    } catch(e) {
      urls = [];
    }
  }

  function save() {
    localStorage.setItem("urls", JSON.stringify(urls));
  }

  function addUrl(url) {
    url = url.match("(?:http(?:s)?://)?(.*)")[1];
    urls.push(url);
    save();
    redraw();
  }

  function deleteUrl(item) {
    urls.splice(item, 1);
    save();
    redraw();
  }

  load();
  redraw();

  $(".add-button").click(function() {
    addUrl($(".add-url").val());
    $(".add-url").val("");
    return false;
  });
});
<commit_msg>added radix to parseint for jslint<commit_after>$(function() {
  var urls = [];

  function redraw() {
    $(".js-urls").empty();
    urls.forEach(function(item, idx) {
      $(".js-urls").append("
" + item + " Remove
");
    });
    $(".js-delete").click(function() {
      deleteUrl(parseInt($(this).attr("data-id"), 10));
    });
  }

  function load() {
    try {
      urls = JSON.parse(localStorage.getItem("urls"));
    } catch(e) {
      urls = [];
    }
  }

  function save() {
    localStorage.setItem("urls", JSON.stringify(urls));
  }

  function addUrl(url) {
    url = url.match("(?:http(?:s)?://)?(.*)")[1];
    urls.push(url);
    save();
    redraw();
  }

  function deleteUrl(item) {
    urls.splice(item, 1);
    save();
    redraw();
  }

  load();
  redraw();

  $(".add-button").click(function() {
    addUrl($(".add-url").val());
    $(".add-url").val("");
    return false;
  });
});
<|endoftext|>


<commit_before>
  var deep = "autonomias";
  var createdBubbles = false;
  var procesos_electorales;
  var animate_interval;
  var previous_year;
  var failCircle;

  var years_nodata = {};

  function updateDeepnessFromZoomLevel(zoom_level) {
    if (zoom_level == 6) {
      return "autonomias";
    } else if (zoom_level > 6 && zoom_level < 11) {
      return "provincias";
    } else {
      return "municipios";
    }
  }

  function initializeHeader() {
    deep = updateDeepnessFromZoomLevel(start_zoom);

    /* Receive all the vars without data */
    getUnavailableData(deep);

    // Graph - Map
    if (state == "grafico") {
      $('div#tab_menu a.map').removeClass('selected');
      $('div#tab_menu a.stats').addClass('selected');
      restartGraph();
      $('div#map').css('zIndex',0);
      $('div#graph').css('zIndex',10);
    }

    // Initialize select
    $('div.option_list ul li a.'+compare).closest('li').addClass('selected');
    $('div.option_list ul li a.'+compare).closest('div.select').addClass('selected');
    var value = $('div.option_list ul li a.'+compare).text();
    $('div.option_list ul li a.'+compare).closest('div.select').find('span.inner_select a').text(value);

    //Control tab menu - map or graph
    $('div#tab_menu a').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      var className = ($(this).hasClass('map'))?'map':'graph';
      if (!$(this).hasClass('selected')) {

        infoTooltip.hide();

        $('div#tab_menu a').removeClass('selected');
        if (className == 'map') {
        $("#graph").hide();
          state = "mapa";
          // This element belongs to body, not to graph container
          graphBubbleInfowindow.hide();
          $('div#map').css('zIndex',10);
          $('div#graph').css('zIndex',0);
        } else {
        $("#graph").show();
          // Hide the legend if this is visible...
          graphLegend.hideFast();
          state = "grafico";
          restartGraph();
          $('div#map').css('zIndex',0);
          $('div#graph').css('zIndex',10);
        }
        // Stop the slider animation if it is playing
        clearInterval(animate_interval);

        $(this).addClass('selected');
        changeHash();
      }
    });

    /* Animate electoral slider process */
    // Play animation process
    $('a.play').live('click',function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      //Remove play class and add pause class
      $(this).removeClass('play').addClass('stop');
      $(this).attr('href','#stop');
      animate_interval = setInterval(function(){animateSlider();},1000);
    });

    // Stop animation process
    $('a.stop').live('click',function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      clearInterval(animate_interval);
      $(this).removeClass('stop').addClass('play');
      $(this).attr('href','#play');
    });

    // Next - before
    $('div.years_content a.left').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      graphBubbleInfowindow.hide();
      updateNewSliderValue(year-1);
    });
    $('div.years_content a.right').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      updateNewSliderValue(year+1);
    });

    // Year Slider
    $("div.year_slider").slider({
      range: "min",
      min: 1987,
      max: 2011,
      value: year,
      step: 1,
      create: function(event,ui) {
        $(this).find('a.ui-slider-handle').text(year);
      },
      slide: function( event, ui ) {
        $(this).find('a.ui-slider-handle').text(ui.value);
        year = ui.value;
      },
      change: function( event, ui ) {
        $(this).find('a.ui-slider-handle').text(ui.value);
        year = ui.value;
      },
      start: function(event, ui) {
        if (state === "grafico" && graphBubbleInfowindow.isOpen()) {
          graphBubbleInfowindow.hide();
        }
        previous_year = ui.value;
      },
      stop: function( event, ui ) {
        if (ui.value!=previous_year) {
          updateNewSliderValue(new_value);
        }
      }
    });

    /*Info tooltip when you select a variable*/
    var infoTooltip = (function() {

      $('div.info_tooltip a.close').click(function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        hideTooltip();
      });

      $('div.info_tooltip a.more').click(function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        hideTooltip();
        explanationwindow.show();
      });

      function hideTooltip() {
        $("div.info_tooltip").fadeOut("slow");
        $('body').unbind("click");
      }

      function showInfoTooltip(title, position) {
        $("div.info_tooltip").fadeOut("slow", function() {

          var info = tooltipInfo[title];

          if (info !== undefined) {
            $("div.info_tooltip h5").text(title);
            $("div.info_tooltip p").text(info.content);
            $("div.info_tooltip ul li.left").html("+25" + info.left);
            $("div.info_tooltip ul li.right").html("-25" + info.right);

            $("div.info_tooltip").css("left", position-7);
            $("div.info_tooltip").fadeIn("slow", function() {
              $('body').click(function(event) {
                if (!$(event.target).closest('div.info_tooltip').length) { hideTooltip(); }
              });
            });
            refreshHeight();
          }
        });
      }

      function refreshHeight() {
        var height = $("div.info_tooltip div.content").height() + 50;
        height = (height > 231) ? 231 : height;
        $("div.info_tooltip").css("height", height + "px");
      }

      return {
        hide: hideTooltip,
        show: showInfoTooltip
      };
    }());

    /*SELECTS*/
    /*Select event*/
    $('div.select div.outer_select').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();

      $('div.select').each(function(i,ele){$(ele).removeClass('opened');});

      if (!$(this).closest('div.select').hasClass('opened')) {
        infoTooltip.hide();
        if ($(this).parent().find('li.selected').length) {
          var index = $(this).parent().find('li.selected').index();
          $(this).parent().find('div.option_list').css('top',-(index*24)+'px');
        } else {
          $(this).parent().find('div.option_list').css('top','0px');
        }
        $(this).closest('div.select').addClass('opened');
      } else {
        $(this).closest('div.select').removeClass('opened');
      }

      $('body').click(function(event) {
        if (!$(event.target).closest('div.option_list').length) {
          $('div.select').each(function(i,ele){$(ele).removeClass('opened');});
          $('body').unbind('click');
        }
      });
    });

    /*Select list events*/
    $('div.option_list ul li a').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();

      var value = $(this).text();

      if (!$(this).parent().hasClass('selected') && !$(this).parent().hasClass('disabled')) {
        compare = $(this).attr('class').replace(/_/g,' ');
        axisLegend.update(tooltipInfo[value]);
        graphBubbleInfowindow.hide();

        if (state == 'mapa') {
          refreshBubbles();
        } else {
          console.log(deep);
          setValue(global_url + "/graphs/"+deep+"/"+graph_version+"/"+((name=="España")?'':name+'_')+normalization[compare]+"_"+year+".json");
        }

        drawNoDataBars();
        changeHash();

        $('div.select span.inner_select a').each(function(i,ele){$(this).text($(this).attr('title'));});
        $('div.option_list ul li').each(function(i,ele){$(ele).removeClass('selected');});
        $('div.select').each(function(i,ele){$(ele).removeClass('selected');});

        infoTooltip.show(value, $(this).closest('div.select').position().left);

        $(this).parent().addClass('selected');
        $(this).closest('div.select').addClass('selected').removeClass('opened');
        $(this).closest('div.select').find('span.inner_select a').text(value);
        $('body').unbind('click');
      }
    });

    /*failCircle*/
    failCircle = (function() {
      var data_not_found = false;

      $("#map_fail_circle a.why").live("click", function(ev) {
        ev.stopPropagation();
        ev.preventDefault();
        explanationwindow.show();
      });

      $("#map_fail_circle a.next").live("click", function(ev) {
        ev.stopPropagation();
        ev.preventDefault();
        goToNextYear();
      });

      function showError() {
        if (data_not_found != true) {
          $('#map_fail_background, #map_fail_circle').fadeIn("slow", function() { data_not_found = true; });
        }
      }

      function hideError() {
        $('#map_fail_background, #map_fail_circle').fadeOut("slow", function() { data_not_found = undefined; })
      }

      function goToNextYear() {
        var next_available_year = getNextAvailableYear();
        year = getNextAvailableYear();
        updateNewSliderValue(year);
        failCircle.hide();
      }

      function hasFailed() {
        return data_not_found;
      }

      return {
        show: showError,
        hide: hideError,
        failed: hasFailed
      }
    })();

  }

  function animateSlider() {
    var new_value = $("div.year_slider").slider('value') + 1;
    if (new_value>2011) {
      $('a.action').removeClass('stop').addClass('play');
      $('a.action.play').attr('href','#play');
      clearInterval(animate_interval);
      return false;
    } else {
      updateNewSliderValue(new_value);
    }
  }

  function getUnavailableData(deep) {
    $.getJSON(global_url + "/graphs/meta/" + deep + ".json", function(data) {
      years_nodata[deep] = new Object();
      _.each(data,function(ele,i){
        years_nodata[deep][i] = new Array();
        years_nodata[deep][i] = ele;
      });
      drawNoDataBars();
    });
  }

  function drawNoDataBars() {
    $('span.slider_no_data_left').hide();
    $('span.slider_no_data_right').hide();

    var deep;
    var zoom = peninsula.getZoom();
    if (zoom==6) {
      deep = "autonomias";
      if (years_nodata["autonomias"]==undefined) {
        getUnavailableData('autonomias');
        return false;
      }
    } else if (zoom>6 && zoom<11) {
      deep = "provincias";
      if (years_nodata["provincias"]==undefined) {
        getUnavailableData('provincias');
        return false;
      }
    } else {
      deep = "municipios";
      if (years_nodata["municipios"]==undefined) {
        getUnavailableData('municipios');
        return false;
      }
    }

    if (years_nodata[deep][normalization[compare]]!=undefined) {
      var left_no = years_nodata[deep][normalization[compare]][0] - 1987;
      var lenght_array = years_nodata[deep][normalization[compare]].length;
      var right_no = 2011 - years_nodata[deep][normalization[compare]][lenght_array-1];

      if (left_no!=0) {
        $('span.slider_no_data_left').css({width:(left_no*4.16)+"%"});
        $('span.slider_no_data_left').show();
      } else {
        $('span.slider_no_data_left').hide();
      }

      if (right_no!=0) {
        $('span.slider_no_data_right').css({width:(right_no*4.16)+"%"});
        $('span.slider_no_data_right').show();
      } else {
        $('span.slider_no_data_right').hide();
      }
    }

    if (!checkFailYear(year)) {
      failCircle.show();
    } else {
      failCircle.hide();
    }
  }

  function checkFailYear(year) {
    var deep;
    var zoom = peninsula.getZoom();
    if (zoom==6) {
      deep = "autonomias";
    } else if (zoom>6 && zoom<11) {
      deep = "provincias";
    } else {
      deep = "municipios";
    }
    if (years_nodata[deep][normalization[compare]]!=undefined) {
      var length_array = years_nodata[deep][normalization[compare]].length;
      return (year>=years_nodata[deep][normalization[compare]][0]) && (year<=years_nodata[deep][normalization[compare]][length_array-1]);
    } else {
      return false;
    }

  }

  function updateNewSliderValue(new_year) {
    $("div.year_slider").slider('value', new_year);

    if (state == 'mapa') {
      if (graph_hack_year[year] != graph_hack_year[new_year]) {
        refreshTiles();
      }
      if (!checkFailYear(new_year)) {
        failCircle.show();
      } else {
        failCircle.hide();
      }
      refreshBubbles();
    } else {
      var url = global_url + "/graphs/"+deep+"/"+graph_version+"/"+((name=="España")?'':name+'_')+normalization[compare]+"_"+year+".json";

      // Let's decide if we must update (setValue) or create the bubbles
      if (createdBubbles == true) {
        setValue(url);
      } else {
        createBubbles(url);
      }
    }

    year = new_year;
    changeHash();
  }

<commit_msg>Fixed var name problem in the updateNewSliderValue call. Updated div names for the fail_circle function<commit_after>
  var deep = "autonomias";
  var createdBubbles = false;
  var procesos_electorales;
  var animate_interval;
  var previous_year;
  var failCircle;

  var years_nodata = {};

  function updateDeepnessFromZoomLevel(zoom_level) {
    if (zoom_level == 6) {
      return "autonomias";
    } else if (zoom_level > 6 && zoom_level < 11) {
      return "provincias";
    } else {
      return "municipios";
    }
  }

  function initializeHeader() {
    deep = updateDeepnessFromZoomLevel(start_zoom);

    /* Receive all the vars without data */
    getUnavailableData(deep);

    // Graph - Map
    if (state == "grafico") {
      $('div#tab_menu a.map').removeClass('selected');
      $('div#tab_menu a.stats').addClass('selected');
      restartGraph();
      $('div#map').css('zIndex',0);
      $('div#graph').css('zIndex',10);
    }

    // Initialize select
    $('div.option_list ul li a.'+compare).closest('li').addClass('selected');
    $('div.option_list ul li a.'+compare).closest('div.select').addClass('selected');
    var value = $('div.option_list ul li a.'+compare).text();
    $('div.option_list ul li a.'+compare).closest('div.select').find('span.inner_select a').text(value);

    //Control tab menu - map or graph
    $('div#tab_menu a').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      var className = ($(this).hasClass('map'))?'map':'graph';
      if (!$(this).hasClass('selected')) {

        infoTooltip.hide();

        $('div#tab_menu a').removeClass('selected');
        if (className == 'map') {
        $("#graph").hide();
          state = "mapa";
          // This element belongs to body, not to graph container
          graphBubbleInfowindow.hide();
          $('div#map').css('zIndex',10);
          $('div#graph').css('zIndex',0);
        } else {
        $("#graph").show();
          // Hide the legend if this is visible...
          graphLegend.hideFast();
          state = "grafico";
          restartGraph();
          $('div#map').css('zIndex',0);
          $('div#graph').css('zIndex',10);
        }
        // Stop the slider animation if it is playing
        clearInterval(animate_interval);

        $(this).addClass('selected');
        changeHash();
      }
    });

    /* Animate electoral slider process */
    // Play animation process
    $('a.play').live('click',function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      //Remove play class and add pause class
      $(this).removeClass('play').addClass('stop');
      $(this).attr('href','#stop');
      animate_interval = setInterval(function(){animateSlider();},1000);
    });

    // Stop animation process
    $('a.stop').live('click',function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      clearInterval(animate_interval);
      $(this).removeClass('stop').addClass('play');
      $(this).attr('href','#play');
    });

    // Next - before
    $('div.years_content a.left').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      graphBubbleInfowindow.hide();
      updateNewSliderValue(year-1);
    });
    $('div.years_content a.right').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      updateNewSliderValue(year+1);
    });

    // Year Slider
    $("div.year_slider").slider({
      range: "min",
      min: 1987,
      max: 2011,
      value: year,
      step: 1,
      create: function(event,ui) {
        $(this).find('a.ui-slider-handle').text(year);
      },
      slide: function( event, ui ) {
        $(this).find('a.ui-slider-handle').text(ui.value);
        year = ui.value;
      },
      change: function( event, ui ) {
        $(this).find('a.ui-slider-handle').text(ui.value);
        year = ui.value;
      },
      start: function(event, ui) {
        if (state === "grafico" && graphBubbleInfowindow.isOpen()) {
          graphBubbleInfowindow.hide();
        }
        previous_year = ui.value;
      },
      stop: function( event, ui ) {
        if (ui.value!=previous_year) {
          updateNewSliderValue(ui.value);
        }
      }
    });

    /*Info tooltip when you select a variable*/
    var infoTooltip = (function() {

      $('div.info_tooltip a.close').click(function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        hideTooltip();
      });

      $('div.info_tooltip a.more').click(function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        hideTooltip();
        explanationwindow.show();
      });

      function hideTooltip() {
        $("div.info_tooltip").fadeOut("slow");
        $('body').unbind("click");
      }

      function showInfoTooltip(title, position) {
        $("div.info_tooltip").fadeOut("slow", function() {

          var info = tooltipInfo[title];

          if (info !== undefined) {
            $("div.info_tooltip h5").text(title);
            $("div.info_tooltip p").text(info.content);
            $("div.info_tooltip ul li.left").html("+25" + info.left);
            $("div.info_tooltip ul li.right").html("-25" + info.right);

            $("div.info_tooltip").css("left", position-7);
            $("div.info_tooltip").fadeIn("slow", function() {
              $('body').click(function(event) {
                if (!$(event.target).closest('div.info_tooltip').length) { hideTooltip(); }
              });
            });
            refreshHeight();
          }
        });
      }

      function refreshHeight() {
        var height = $("div.info_tooltip div.content").height() + 50;
        height = (height > 231) ? 231 : height;
        $("div.info_tooltip").css("height", height + "px");
      }

      return {
        hide: hideTooltip,
        show: showInfoTooltip
      };
    }());

    /*SELECTS*/
    /*Select event*/
    $('div.select div.outer_select').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();

      $('div.select').each(function(i,ele){$(ele).removeClass('opened');});

      if (!$(this).closest('div.select').hasClass('opened')) {
        infoTooltip.hide();
        if ($(this).parent().find('li.selected').length) {
          var index = $(this).parent().find('li.selected').index();
          $(this).parent().find('div.option_list').css('top',-(index*24)+'px');
        } else {
          $(this).parent().find('div.option_list').css('top','0px');
        }
        $(this).closest('div.select').addClass('opened');
      } else {
        $(this).closest('div.select').removeClass('opened');
      }

      $('body').click(function(event) {
        if (!$(event.target).closest('div.option_list').length) {
          $('div.select').each(function(i,ele){$(ele).removeClass('opened');});
          $('body').unbind('click');
        }
      });
    });

    /*Select list events*/
    $('div.option_list ul li a').click(function(ev){
      ev.stopPropagation();
      ev.preventDefault();

      var value = $(this).text();

      if (!$(this).parent().hasClass('selected') && !$(this).parent().hasClass('disabled')) {
        compare = $(this).attr('class').replace(/_/g,' ');
        axisLegend.update(tooltipInfo[value]);
        graphBubbleInfowindow.hide();

        if (state == 'mapa') {
          refreshBubbles();
        } else {
          console.log(deep);
          setValue(global_url + "/graphs/"+deep+"/"+graph_version+"/"+((name=="España")?'':name+'_')+normalization[compare]+"_"+year+".json");
        }

        drawNoDataBars();
        changeHash();

        $('div.select span.inner_select a').each(function(i,ele){$(this).text($(this).attr('title'));});
        $('div.option_list ul li').each(function(i,ele){$(ele).removeClass('selected');});
        $('div.select').each(function(i,ele){$(ele).removeClass('selected');});

        infoTooltip.show(value, $(this).closest('div.select').position().left);

        $(this).parent().addClass('selected');
        $(this).closest('div.select').addClass('selected').removeClass('opened');
        $(this).closest('div.select').find('span.inner_select a').text(value);
        $('body').unbind('click');
      }
    });

    /*failCircle*/
    failCircle = (function() {
      var data_not_found = false;

      $("#map div.fail a.why").live("click", function(ev) {
        ev.stopPropagation();
        ev.preventDefault();
        explanationwindow.show();
      });

      $("#map div.fail a.next").live("click", function(ev) {
        ev.stopPropagation();
        ev.preventDefault();
        goToNextYear();
      });

      function showError() {
        if (data_not_found != true) {
          $('#map div.fail').fadeIn("slow", function() { data_not_found = true; });
        }
      }

      function hideError() {
        $('#map div.fail').fadeOut("slow", function() { data_not_found = undefined; })
      }

      function goToNextYear() {
        var next_available_year = getNextAvailableYear();
        year = getNextAvailableYear();
        updateNewSliderValue(year);
        failCircle.hide();
      }

      function hasFailed() {
        return data_not_found;
      }

      return {
        show: showError,
        hide: hideError,
        failed: hasFailed
      }
    })();

  }

  function animateSlider() {
    var new_value = $("div.year_slider").slider('value') + 1;
    if (new_value>2011) {
      $('a.action').removeClass('stop').addClass('play');
      $('a.action.play').attr('href','#play');
      clearInterval(animate_interval);
      return false;
    } else {
      updateNewSliderValue(new_value);
    }
  }

  function getUnavailableData(deep) {
    $.getJSON(global_url + "/graphs/meta/" + deep + ".json", function(data) {
      years_nodata[deep] = new Object();
      _.each(data,function(ele,i){
        years_nodata[deep][i] = new Array();
        years_nodata[deep][i] = ele;
      });
      drawNoDataBars();
    });
  }

  function drawNoDataBars() {
    $('span.slider_no_data_left').hide();
    $('span.slider_no_data_right').hide();

    var deep;
    var zoom = peninsula.getZoom();
    if (zoom==6) {
      deep = "autonomias";
      if (years_nodata["autonomias"]==undefined) {
        getUnavailableData('autonomias');
        return false;
      }
    } else if (zoom>6 && zoom<11) {
      deep = "provincias";
      if (years_nodata["provincias"]==undefined) {
        getUnavailableData('provincias');
        return false;
      }
    } else {
      deep = "municipios";
      if (years_nodata["municipios"]==undefined) {
        getUnavailableData('municipios');
        return false;
      }
    }

    if (years_nodata[deep][normalization[compare]]!=undefined) {
      var left_no = years_nodata[deep][normalization[compare]][0] - 1987;
      var lenght_array = years_nodata[deep][normalization[compare]].length;
      var right_no = 2011 - years_nodata[deep][normalization[compare]][lenght_array-1];

      if (left_no!=0) {
        $('span.slider_no_data_left').css({width:(left_no*4.16)+"%"});
        $('span.slider_no_data_left').show();
      } else {
        $('span.slider_no_data_left').hide();
      }

      if (right_no!=0) {
        $('span.slider_no_data_right').css({width:(right_no*4.16)+"%"});
        $('span.slider_no_data_right').show();
      } else {
        $('span.slider_no_data_right').hide();
      }
    }

    if (!checkFailYear(year)) {
      failCircle.show();
    } else {
      failCircle.hide();
    }
  }

  function checkFailYear(year) {
    var deep;
    var zoom = peninsula.getZoom();
    if (zoom==6) {
      deep = "autonomias";
    } else if (zoom>6 && zoom<11) {
      deep = "provincias";
    } else {
      deep = "municipios";
    }
    if (years_nodata[deep][normalization[compare]]!=undefined) {
      var length_array = years_nodata[deep][normalization[compare]].length;
      return (year>=years_nodata[deep][normalization[compare]][0]) && (year<=years_nodata[deep][normalization[compare]][length_array-1]);
    } else {
      return false;
    }

  }

  function updateNewSliderValue(new_year) {
    $("div.year_slider").slider('value', new_year);

    if (state == 'mapa') {
      if (graph_hack_year[year] != graph_hack_year[new_year]) {
        refreshTiles();
      }
      if (!checkFailYear(new_year)) {
        failCircle.show();
      } else {
        failCircle.hide();
      }
      refreshBubbles();
    } else {
      var url = global_url + "/graphs/"+deep+"/"+graph_version+"/"+((name=="España")?'':name+'_')+normalization[compare]+"_"+year+".json";

      // Let's decide if we must update (setValue) or create the bubbles
      if (createdBubbles == true) {
        setValue(url);
      } else {
        createBubbles(url);
      }
    }

    year = new_year;
    changeHash();
  }

<|endoftext|>


<commit_before>// Description:
// Shows the departure and arrival times of an airplane.
//
// Dependencies:
// Requires jQuery.
//
// Commands:
// american airlines 102 - will show details about the flight.
function ddg_spice_airlines (api_result) {
    "use strict";

    // Check if we have anything returned.
    if(!api_result || !api_result.flight) {
        return Spice.failed('airlines');
    }

    var MILLIS_PER_MIN = 60000;
    var MILLIS_PER_HOUR = MILLIS_PER_MIN * 60;
    var STATUS = {
        "S": "Scheduled",
        "A": "In the air",
        "U": "Unknown status",
        "R": "Redirected flight",
        "L": "Landed",
        "D": "Diverted",
        "C": "Cancelled",
        "NO": "Not Operational",
        "DN": "Data Needed"
    };

    // Check if flight is an array or not.
    var flight = [];
    if(!($.isArray(api_result.flight))){
        flight = [api_result.flight];
    } else {
        flight = api_result.flight;
    }

    // Parse string, and return the date (either arrival or departure date).
    var getDateFromString = function(date) {
        date = date.match(/([\d]{4})\-([\d]{2})\-([\d]{2})T([\d]{2}):([\d]{2}):([\d]{2})/);
        var now = new Date();
        var milliseconds = Date.UTC(date[1], date[2] - 1, date[3], date[4], date[5], date[6]) +
                                (now.getTimezoneOffset() * MILLIS_PER_MIN);
        return new Date(milliseconds);
    };

    // Compute the difference between now and the time of departure or arrival.
    var relativeTime = function(date, airportOffset) {
        // This is the time of departure or arrival (not sure why we're getting the difference).
        date = date.getTime() - (date.getTimezoneOffset() * MILLIS_PER_MIN);

        // This is the current time at the airport (in milliseconds).
        var now = new Date().getTime() + (airportOffset * MILLIS_PER_HOUR);

        return date - now;
    };

    // Convert the time from milliseconds to hours and minutes.
    var toTime = function(delta) {
        var time = "";
        var hours = Math.floor(Math.abs(delta / MILLIS_PER_HOUR));
        var minutes = Math.floor(Math.abs((delta % MILLIS_PER_HOUR) / MILLIS_PER_MIN));

        if (0 < hours) {
            time += hours + " hrs ";
        }
        if (0 < minutes) {
            time += minutes + " mins ";
        }

        if(delta === 0) {
            return "now";
        } else if(delta > 0) {
            return "in " + time;
        } else {
            return time + "ago";
        }
    };

    // Check when the plane will depart (or if it has departed).
    Handlebars.registerHelper("airline_status", function(airportOffset, isDeparture) {
        var dateObject = arrivalDate;
        if(isDeparture) {
            dateObject = departureDate;
        }

        var delta = relativeTime(dateObject, airportOffset);

        if(isDeparture) {
            if(delta === 0) {
                return "Departing";
            } else if(delta > 0) {
                return "Departs";
            } else {
                return "Departed";
            }
        } else {
            if(delta === 0) {
                return "Arriving";
            } else if(delta > 0) {
                return "Arrives";
            } else {
                return "Arrived";
            }
        }
    });

    // Compute for the relative time (e.g. 31 minutes ago).
    Handlebars.registerHelper("relative", function(airportOffset, isDeparture) {
        var dateObject = arrivalDate;
        if(isDeparture) {
            dateObject = departureDate;
        }

        var delta = relativeTime(dateObject, airportOffset);
        var time = toTime(delta);

        return time;
    });

    Handlebars.registerHelper("airportName", function(name) {
        return name.replace(/airport|international/ig, "");
    });

    // Add the date and time or departure or arrival.
    Handlebars.registerHelper("airline_time", function(isDeparture, arrivalDate, departureDate) {
        var dateObject = new Date(arrivalDate);
        if(isDeparture) {
            dateObject = new Date(departureDate);
        }

        var hours = dateObject.getHours();
        var minutes = dateObject.getMinutes();

        var date = dateObject.toDateString();
        date = date.substring(0, date.lastIndexOf(" "));

        // AM or PM?
        var suffix = (hours >= 12) ? "PM" : "AM";

        // Convert to 12-hour time.
        if(hours > 12) {
            hours -= 12;
        } else if(hours === 0) {
            hours = 12;
        }

        // Add leading zeroes.
        minutes = minutes < 10 ? "0" + minutes : minutes;

        return hours + ":" + minutes + " " + suffix;
    });

    // Check if the airplane is on-time or delayed.
    var onTime = function(flight, departureDate, arrivalDate) {
        var scheduledDeparture = getDateFromString(flight.ScheduledGateDepartureDate);
        var scheduledArrival = getDateFromString(flight.ScheduledGateArrivalDate);

        var deltaDepart = new Date(departureDate) - scheduledDeparture;
        var deltaArrive = new Date(arrivalDate) - scheduledArrival;
        if(flight.StatusCode === "A" || flight.StatusCode === "S") {
            if(MILLIS_PER_MIN * 5 < deltaDepart && MILLIS_PER_MIN * 5 < deltaArrive) {
                return ["Delayed", false];
            } else {
                return ["On Time", true];
            }
        }
        return [STATUS[flight.StatusCode], true];
    };

    Handlebars.registerHelper("status", function(flight, departureDate, arrivalDate) {
	var result = onTime(flight, departureDate, arrivalDate);
	var ok_class = result[1] ? "tile__ok" : "tile__not";
	return '
' + result[0] + '
';
    });

    // array of flights
    var results = [];

    // package up the flights into the result array
    for(var i = 0; i < flight.length; i++) {
        var departureDate = getDateFromString(flight[i].ActualGateDepartureDate ||
					      flight[i].EstimatedGateDepartureDate ||
					      flight[i].DepartureDate).toString();
        var arrivalDate = getDateFromString(flight[i].ActualGateArrivalDate ||
					    flight[i].EstimatedGateArrivalDate ||
					    flight[i].ArrivalDate).toString();

	var scheduledDepartureDate = getDateFromString(flight[i].ScheduledGateDepartureDate).toString();
	var scheduledArrivalDate = getDateFromString(flight[i].ScheduledGateArrivalDate).toString();

	// Get the weekday and the day.
	var dateObject = new Date(departureDate);

        var date = dateObject.toDateString();
	date = date.split(" ");

        var departing = {
                airportTimezone: flight[i].DepartureAirportTimeZoneOffset,
                airport: flight[i].Origin,
                terminal: flight[i].DepartureTerminal || "N/A",
                gate: flight[i].DepartureGate || "N/A",
                isDeparted: true,
	        weekday: date[0].toUpperCase(),
	        day: date[2]
            },
            arriving = {
                airportTimezone: flight[i].ArrivalAirportTimeZoneOffset,
                airport: flight[i].Destination,
                terminal: flight[i].ArrivalTerminal || "N/A",
                gate: flight[i].ArrivalGate || "N/A",
                isDeparted: false
            };

        results.push({
	    flight: flight[i],
	    departing: departing,
	    arriving: arriving,
	    departureDate: departureDate,
	    arrivalDate: arrivalDate,
	    scheduledDepartureDate: scheduledDepartureDate,
	    scheduledArrivalDate: scheduledArrivalDate
	});
    }

    // Display.
    var source = "http://www.flightstats.com/go/FlightStatus/flightStatusByFlight.do?&airlineCode=" +
	flight[0].Airline.AirlineCode +
	"&flightNumber=" +
	flight[0].FlightNumber;

    // Sort the items based on the departureDate.
    results.sort(function(a, b) {
	a = +new Date(a.departureDate);
	b = +new Date(b.departureDate);

	if(a  b) {
	    return 1;
	}

	return 0;
    });

    Spice.add({
        data: results,
        sourceUrl: source,
        sourceName: "FlightStats",
        id: "airlines",
        name: "Flights",
        view: "Tiles",
        meta: {
	    minItemsForModeSwitch: 3,
            sourceName: 'FlightStatus',
            sourceUrl: source,
            itemType: "Flight Status for " + DDG.capitalizeWords(flight[0].Airline.Name) + " " + flight[0].FlightNumber
        },
	normalize: function(item) {
	    return {
		url: "http://www.flightstats.com/go/FlightStatus/flightStatusByFlight.do?&airlineCode=" + item.flight.Airline.AirlineCode + "&flightNumber=" + item.flight.FlightNumber
	    }
	},
	template_group: 'base',
        templates : {
	    detail: false,
	    options: {
		content: Spice.airlines.content,
                variant: 'xwide'
            }
        },
    });
};
<commit_msg>Cleanup airlines.js Wrap in closure, change 'template_group' -> 'group' remove multiple 'var' declarations<commit_after>(function(env) {
    env.ddg_spice_airlines = function(api_result) {
        "use strict";

        // Check if we have anything returned.
        if (!api_result || !api_result.flight) {
            return Spice.failed('airlines');
        }

        var MILLIS_PER_MIN = 60000,
            MILLIS_PER_HOUR = MILLIS_PER_MIN * 60,
            STATUS = {
                "S": "Scheduled",
                "A": "In the air",
                "U": "Unknown status",
                "R": "Redirected flight",
                "L": "Landed",
                "D": "Diverted",
                "C": "Cancelled",
                "NO": "Not Operational",
                "DN": "Data Needed"
            };

        // Check if flight is an array or not.
        var flight = [];
        if (!($.isArray(api_result.flight))) {
            flight = [api_result.flight];
        } else {
            flight = api_result.flight;
        }

        // array of flights
        var results = [];

        // package up the flights into the result array
        for (var i = 0; i < flight.length; i++) {
            var departureDate = DDG.getDateFromString(flight[i].ActualGateDepartureDate ||
                flight[i].EstimatedGateDepartureDate ||
                flight[i].DepartureDate).toString();
            var arrivalDate = DDG.getDateFromString(flight[i].ActualGateArrivalDate ||
                flight[i].EstimatedGateArrivalDate ||
                flight[i].ArrivalDate).toString();

            var scheduledDepartureDate = DDG.getDateFromString(flight[i].ScheduledGateDepartureDate).toString();
            var scheduledArrivalDate = DDG.getDateFromString(flight[i].ScheduledGateArrivalDate).toString();

            // Get the weekday and the day.
            var dateObject = new Date(departureDate);

            var date = dateObject.toDateString();
            date = date.split(" ");

            var departing = {
                airportTimezone: flight[i].DepartureAirportTimeZoneOffset,
                airport: flight[i].Origin,
                terminal: flight[i].DepartureTerminal || "N/A",
                gate: flight[i].DepartureGate || "N/A",
                isDeparted: true,
                weekday: date[0].toUpperCase(),
                day: date[2]
            },
                arriving = {
                    airportTimezone: flight[i].ArrivalAirportTimeZoneOffset,
                    airport: flight[i].Destination,
                    terminal: flight[i].ArrivalTerminal || "N/A",
                    gate: flight[i].ArrivalGate || "N/A",
                    isDeparted: false
                };

            results.push({
                flight: flight[i],
                departing: departing,
                arriving: arriving,
                departureDate: departureDate,
                arrivalDate: arrivalDate,
                scheduledDepartureDate: scheduledDepartureDate,
                scheduledArrivalDate: scheduledArrivalDate
            });
        }

        // Display.
        var source = "http://www.flightstats.com/go/FlightStatus/flightStatusByFlight.do?&airlineCode=" +
            flight[0].Airline.AirlineCode +
            "&flightNumber=" +
            flight[0].FlightNumber;

        // Sort the items based on the departureDate.
        results.sort(function(a, b) {
            a = +new Date(a.departureDate);
            b = +new Date(b.departureDate);

            if (a  b) {
                return 1;
            }

            return 0;
        });

        Spice.add({
            data: results,
            id: "airlines",
            name: "Flights",
            meta: {
                minItemsForModeSwitch: 3,
                sourceName: 'FlightStatus',
                sourceUrl: source,
                itemType: "Flight Status for " + DDG.capitalizeWords(flight[0].Airline.Name) + " " + flight[0].FlightNumber
            },
            normalize: function(item) {
                return {
                    url: "http://www.flightstats.com/go/FlightStatus/flightStatusByFlight.do?&airlineCode=" +
                        item.flight.Airline.AirlineCode +
                        "&flightNumber=" +
                        item.flight.FlightNumber
                }
            },
            templates: {
                group: 'base',
                detail: false,
                options: {
                    content: Spice.airlines.content,
                    variant: 'xwide'
                }
            },
        });
    };

    // Compute the difference between now and the time of departure or arrival.
    function relativeTime(date, airportOffset) {
        // This is the time of departure or arrival (not sure why we're getting the difference).
        date = date.getTime() - (date.getTimezoneOffset() * MILLIS_PER_MIN);

        // This is the current time at the airport (in milliseconds).
        var now = new Date().getTime() + (airportOffset * MILLIS_PER_HOUR);

        return date - now;
    };

    // Convert the time from milliseconds to hours and minutes.
    function toTime(delta) {
        var time = "",
            hours = Math.floor(Math.abs(delta / MILLIS_PER_HOUR)),
            minutes = Math.floor(Math.abs((delta % MILLIS_PER_HOUR) / MILLIS_PER_MIN));

        if (0 < hours) {
            time += hours + " hrs ";
        }
        if (0 < minutes) {
            time += minutes + " mins ";
        }

        if(delta === 0) {
            return "now";
        } else if(delta > 0) {
            return "in " + time;
        } else {
            return time + "ago";
        }
    };

    // Check when the plane will depart (or if it has departed).
    Handlebars.registerHelper("airline_status", function(airportOffset, isDeparture) {
        var dateObject = arrivalDate;
        if(isDeparture) {
            dateObject = departureDate;
        }

        var delta = relativeTime(dateObject, airportOffset);

        if(isDeparture) {
            if(delta === 0) {
                return "Departing";
            } else if(delta > 0) {
                return "Departs";
            } else {
                return "Departed";
            }
        } else {
            if(delta === 0) {
                return "Arriving";
            } else if(delta > 0) {
                return "Arrives";
            } else {
                return "Arrived";
            }
        }
    });

    // Compute for the relative time (e.g. 31 minutes ago).
    Handlebars.registerHelper("relative", function(airportOffset, isDeparture) {
        var dateObject = arrivalDate;
        if(isDeparture) {
            dateObject = departureDate;
        }

        var delta = relativeTime(dateObject, airportOffset),
            time = toTime(delta);

        return time;
    });

    Handlebars.registerHelper("airportName", function(name) {
        return name.replace(/airport|international/ig, "");
    });

    // Add the date and time or departure or arrival.
    Handlebars.registerHelper("airline_time", function(isDeparture, arrivalDate, departureDate) {
        var dateObject = new Date(arrivalDate);
        if(isDeparture) {
            dateObject = new Date(departureDate);
        }

        var hours = dateObject.getHours(),
            minutes = dateObject.getMinutes(),
            date = dateObject.toDateString();

        date = date.substring(0, date.lastIndexOf(" "));

        // AM or PM?
        var suffix = (hours >= 12) ? "PM" : "AM";

        // Convert to 12-hour time.
        if(hours > 12) {
            hours -= 12;
        } else if(hours === 0) {
            hours = 12;
        }

        // Add leading zeroes.
        minutes = minutes < 10 ? "0" + minutes : minutes;

        return hours + ":" + minutes + " " + suffix;
    });

    // Check if the airplane is on-time or delayed.
    function onTime(flight, departureDate, arrivalDate) {
        var scheduledDeparture = DDG.getDateFromString(flight.ScheduledGateDepartureDate),
            scheduledArrival = DDG.getDateFromString(flight.ScheduledGateArrivalDate),
            deltaDepart = new Date(departureDate) - scheduledDeparture,
            deltaArrive = new Date(arrivalDate) - scheduledArrival;

        if (flight.StatusCode === "A" || flight.StatusCode === "S") {
            if (MILLIS_PER_MIN * 5 < deltaDepart && MILLIS_PER_MIN * 5 < deltaArrive) {
                return ["Delayed", false];
            } else {
                return ["On Time", true];
            }
        }
        return [STATUS[flight.StatusCode], true];
    };

    Handlebars.registerHelper("status", function(flight, departureDate, arrivalDate) {
        var result = onTime(flight, departureDate, arrivalDate),
            ok_class = result[1] ? "tile__ok" : "tile__not";
        return '
' + result[0] + '
';
    });
}(this))<|endoftext|>


<commit_before>CONFIG = {
    port: 8000,

    /**
     * 是否啟用文字檔的記錄
     * @type Boolean
     */
    enable_jieba_log: false,

    /**
     * 文字檔記錄的位置
     * @type String
     */
    jieba_log_path: "/tmp/jieba.log",

    linked_data_proxy_check_url: "http://localhost:3000/check/wiki,moedict,cbdb,tgaz,cdict/",

    /**
     * 停用字，這些字不查詢
     * @type String
     */
    stopword: ".,\/#!$%\^&\*;:{}=\-_`~()"
        + "«»/•† ‡¿№×‰ºª‱¶§|‖¦©℗®℠™¤฿¢₡₢$₫₯₠€ƒ₣₭₾ℳ₥₦₧₱₰£៛₪৳₮₩¥⁂❧☞‽◊⁀"
        + "\n\r。，
─「」；：:！？{}()[].0123456789"
        + "〇零一二三四五六七八九十月日時分"
        + "…、%％【】※『』 ㈠㈡　，、。．？！～＄％＠＆＃＊‧；︰…‥﹐﹒˙·﹔﹕‘’“”〝〞‵′〃├─┼┴┬┤┌┐╞═╪╡│▕└┘╭╮╰╯╔╦╗╠═╬╣╓╥╖╒╤╕║╚╩╝╟╫╢╙╨╜╞╪╡╘╧╛﹣﹦≡｜∣∥–︱—︳╴¯￣﹉﹊﹍﹎﹋﹌﹏︴﹨∕╲╱＼／↑↓←→↖↗↙↘〔〕【】﹝﹞〈〉﹙﹚《》（）｛｝﹛﹜『』「」＜＞≦≧﹤﹥︵︶︷︸︹︺︻︼︽︾︿﹀∩∪﹁﹂﹃﹄◎⊕⊙○●△▲▽▼☆★◇◆□■☎☏◐◑♡♥♣♧☻☺♠♤▪▫∴∵☜☞♫♬◊♦►◁∈∋◘◙♀♂♩♪☼￥〒￠￡※↔↕♨卍◈§♭＿ˍ▁▂▃▄▅▆▇█▏▎▍▌▋▊▉◢◣◥◤►◄▣▤▥▦▧▨▩▒░㊣㊟㊕㊗㊡㊝①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩１２３４５６７８９０〡〢〣〤〥〦〧〨〩十卄卅ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩανξοπρστυφχψωクラピカマニアチェックあなたのテスト≠〃てたこれまでキャンプシーズにかけるかがきいレャズンをえたコンパやすうなどすそビジネられていアウドアやにびせだも来つリビをしたとにオはわゅうごりよろしくそうまムペㄱㄲㄳㄴㄵㄶㄷㄸㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅃㅄㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅥㅦㅧㅨㅩㅪㅫㅬㅭㅮㅯㅰㅱㅲㅳㅴㅵㅶㅷㅸㅹㅺㅻㅼㅽㅾㅿㆀㆁㆂㆃㆄㆅㆆㆇㆈㆉㆊ╳＋﹢－×÷＝≠≒∞ˇ±√⊥∠∟⊿㏒㏑∫∮∵∴ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩ˙ˊˇˋÄÃÇÊËÎÏÐÑÕÖÛÜãäêëîïõöŸŴŽŤŘŇĩħąčĤ",

    /**
     * 同時查詢資料的上限
     * @type Number
     */
    linked_data_proxy_request_max: 20,

    /**
     * 一次傳送的字句
     * @type Number
     */
    batch_check: 100
};<commit_msg>0529 不限制送出的數量<commit_after>CONFIG = {
    port: 8000,

    /**
     * 是否啟用文字檔的記錄
     * @type Boolean
     */
    enable_jieba_log: false,

    /**
     * 文字檔記錄的位置
     * @type String
     */
    jieba_log_path: "/tmp/jieba.log",

    linked_data_proxy_check_url: "http://localhost:3000/check/wiki,moedict,cbdb,tgaz,cdict/",

    /**
     * 停用字，這些字不查詢
     * @type String
     */
    stopword: ".,\/#!$%\^&\*;:{}=\-_`~()"
        + "«»/•† ‡¿№×‰ºª‱¶§|‖¦©℗®℠™¤฿¢₡₢$₫₯₠€ƒ₣₭₾ℳ₥₦₧₱₰£៛₪৳₮₩¥⁂❧☞‽◊⁀"
        + "\n\r。，
─「」；：:！？{}()[].0123456789"
        + "〇零一二三四五六七八九十月日時分"
        + "…、%％【】※『』 ㈠㈡　，、。．？！～＄％＠＆＃＊‧；︰…‥﹐﹒˙·﹔﹕‘’“”〝〞‵′〃├─┼┴┬┤┌┐╞═╪╡│▕└┘╭╮╰╯╔╦╗╠═╬╣╓╥╖╒╤╕║╚╩╝╟╫╢╙╨╜╞╪╡╘╧╛﹣﹦≡｜∣∥–︱—︳╴¯￣﹉﹊﹍﹎﹋﹌﹏︴﹨∕╲╱＼／↑↓←→↖↗↙↘〔〕【】﹝﹞〈〉﹙﹚《》（）｛｝﹛﹜『』「」＜＞≦≧﹤﹥︵︶︷︸︹︺︻︼︽︾︿﹀∩∪﹁﹂﹃﹄◎⊕⊙○●△▲▽▼☆★◇◆□■☎☏◐◑♡♥♣♧☻☺♠♤▪▫∴∵☜☞♫♬◊♦►◁∈∋◘◙♀♂♩♪☼￥〒￠￡※↔↕♨卍◈§♭＿ˍ▁▂▃▄▅▆▇█▏▎▍▌▋▊▉◢◣◥◤►◄▣▤▥▦▧▨▩▒░㊣㊟㊕㊗㊡㊝①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩１２３４５６７８９０〡〢〣〤〥〦〧〨〩十卄卅ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩανξοπρστυφχψωクラピカマニアチェックあなたのテスト≠〃てたこれまでキャンプシーズにかけるかがきいレャズンをえたコンパやすうなどすそビジネられていアウドアやにびせだも来つリビをしたとにオはわゅうごりよろしくそうまムペㄱㄲㄳㄴㄵㄶㄷㄸㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅃㅄㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅥㅦㅧㅨㅩㅪㅫㅬㅭㅮㅯㅰㅱㅲㅳㅴㅵㅶㅷㅸㅹㅺㅻㅼㅽㅾㅿㆀㆁㆂㆃㆄㆅㆆㆇㆈㆉㆊ╳＋﹢－×÷＝≠≒∞ˇ±√⊥∠∟⊿㏒㏑∫∮∵∴ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩ˙ˊˇˋÄÃÇÊËÎÏÐÑÕÖÛÜãäêëîïõöŸŴŽŤŘŇĩħąčĤ",

    /**
     * 同時查詢資料的上限
     * @type Number
     */
    linked_data_proxy_request_max: 200000,

    /**
     * 一次傳送的字句
     * @type Number
     */
    batch_check: 100
};<|endoftext|>