<commit_before>define([
    '/common/rpc.js',
    '/bower_components/tweetnacl/nacl-fast.min.js'
], function (Rpc) {
    var Nacl = window.nacl;

    var create = function (network, proxy, cb) {
        if (!network) { return void cb('INVALID_NETWORK'); }
        if (!proxy) { return void cb('INVALID_PROXY'); }

        var edPrivate = proxy.edPrivate;
        var edPublic = proxy.edPublic;

        if (!(edPrivate && edPublic)) { return void cb('INVALID_KEYS'); }

        Rpc.create(network, edPrivate, edPublic, function (e, rpc) {
            if (e) { return void cb(e); }

            var exp = {};

            // expose the supplied publicKey as an identifier
            exp.publicKey = edPublic;

            // expose the RPC module's raw 'send' command
            exp.send = rpc.send;

            // you can ask the server to pin a particular channel for you
            exp.pin = function (channels, cb) {
                rpc.send('PIN', channels, cb);
            };

            // you can also ask to unpin a particular channel
            exp.unpin = function (channels, cb) {
                rpc.send('UNPIN', channels, cb);
            };

            // This implementation must match that on the server
            // it's used for a checksum
            exp.hashChannelList = function (list) {
                return Nacl.util.encodeBase64(Nacl.hash(Nacl.util
                    .decodeUTF8(JSON.stringify(list))));
            };

            // ask the server what it thinks your hash is
            exp.getServerHash = function (cb) {
                rpc.send('GET_HASH', edPublic, function (e, hash) {
                    if (!(hash && hash[0])) {
                        return void cb('NO_HASH_RETURNED');
                    }
                    cb(e, hash[0]);
                });
            };

            // if local and remote hashes don't match, send a reset
            exp.reset = function (list, cb) {
                rpc.send('RESET', list, function (e, response) {
                    cb(e, response[0]);
                });
            };

            // get the total stored size of a channel's patches (in bytes)
            exp.getFileSize = function (file, cb) {
                rpc.send('GET_FILE_SIZE', file, cb);
            };

            // get the combined size of all channels (in bytes) for all the
            // channels which the server has pinned for your publicKey
            exp.getFileListSize = function (cb) {
                rpc.send('GET_TOTAL_SIZE', undefined, cb);
            };

            cb(e, exp);
        });
    };

    return { create: create };
});
<commit_msg>pinpad.create should always be async<commit_after>define([
    '/common/rpc.js',
    '/bower_components/tweetnacl/nacl-fast.min.js'
], function (Rpc) {
    var Nacl = window.nacl;

    var create = function (network, proxy, cb) {
        if (!network) {
            window.setTimeout(function () {
                cb('INVALID_NETWORK');
            });
            return;
        }
        if (!proxy) {
            window.setTimeout(function () {
                cb('INVALID_PROXY');
            });
            return;
        }

        var edPrivate = proxy.edPrivate;
        var edPublic = proxy.edPublic;

        if (!(edPrivate && edPublic)) {
            window.setTimeout(function () {
                cb('INVALID_KEYS');
            });
            return;
        }

        Rpc.create(network, edPrivate, edPublic, function (e, rpc) {
            if (e) { return void cb(e); }

            var exp = {};

            // expose the supplied publicKey as an identifier
            exp.publicKey = edPublic;

            // expose the RPC module's raw 'send' command
            exp.send = rpc.send;

            // you can ask the server to pin a particular channel for you
            exp.pin = function (channels, cb) {
                rpc.send('PIN', channels, cb);
            };

            // you can also ask to unpin a particular channel
            exp.unpin = function (channels, cb) {
                rpc.send('UNPIN', channels, cb);
            };

            // This implementation must match that on the server
            // it's used for a checksum
            exp.hashChannelList = function (list) {
                return Nacl.util.encodeBase64(Nacl.hash(Nacl.util
                    .decodeUTF8(JSON.stringify(list))));
            };

            // ask the server what it thinks your hash is
            exp.getServerHash = function (cb) {
                rpc.send('GET_HASH', edPublic, function (e, hash) {
                    if (!(hash && hash[0])) {
                        return void cb('NO_HASH_RETURNED');
                    }
                    cb(e, hash[0]);
                });
            };

            // if local and remote hashes don't match, send a reset
            exp.reset = function (list, cb) {
                rpc.send('RESET', list, function (e, response) {
                    cb(e, response[0]);
                });
            };

            // get the total stored size of a channel's patches (in bytes)
            exp.getFileSize = function (file, cb) {
                rpc.send('GET_FILE_SIZE', file, cb);
            };

            // get the combined size of all channels (in bytes) for all the
            // channels which the server has pinned for your publicKey
            exp.getFileListSize = function (cb) {
                rpc.send('GET_TOTAL_SIZE', undefined, cb);
            };

            cb(e, exp);
        });
    };

    return { create: create };
});
<|endoftext|>


<commit_before>/**
* JS Terminal
* Version 1.1.4
* Author: Pedro Laxe <pedro@phpsec.com.br>
* Contributor: Gabriel Takashi Katakura <gt.katakura@gmail.com>
**/

(function(global) {
    var Terminal = {
        _resolveCommands: function() {
            return Object.keys(this.commands).map(function(key) {
                return Terminal.CommandDecorator.decorate(Terminal.commands[key]);
            });
        },
        start: function() {
            var resolvedCommands = this._resolveCommands();
            this.CommandRepository.register(resolvedCommands);
        },
        commands: {},
        create: function(options) {
            var results = options.results,
                textInput = options.textInput;

            return {
                _addTextToResults: function(text) {
                    results.innerHTML += '
' + text + '
';
                },
                _clearInput: function() {
                    textInput.value = '';
                },
                _scrollToBottomOfResults: function() {
                    results.scrollTop = results.scrollHeight;
                },
                focus: function() {
                    textInput.focus();
                    this._scrollToBottomOfResults();
                },
                enter: function() {
                    var commandText = textInput.value.trim(),
                        command = Terminal.CommandRepository.findByCommandText(commandText.toLowerCase()),
                        parameter = '',
                        response = '';

                    this._addTextToResults('
> ' + commandText + '
');

                    if (command) {
                        parameter = commandText.replace(command.name, '').trim();
                        response = command.execute(parameter);
                    }
                    else {
                        response = '
The command ' + commandText + ' was not found. Type Help to see all commands.
';
                    }

                    this._addTextToResults(response);
                    this._clearInput();
                    this._scrollToBottomOfResults();
                }
            };
        }
    };

    global.Terminal = Terminal;
})(window);
(function(Terminal) {
    var emptyFunction = function() {},
        isArray = function(arg) {
            return Object.prototype.toString.call(arg) === '[object Array]';
        };

    Terminal.CommandDecorator = {
        _transformToFunction: function(response) {
            if (isArray(response)) {
                response = response.join('
');
            }

            if (typeof response === 'string') {
                return function() {
                    return response;
                };
            }

            return response || emptyFunction;
        },
        decorate: function(command) {
            var name = command.name || '',
                aliases = command.aliases || [],
                execute = command.execute || this._transformToFunction(command.response);

            return {
                name: name,
                aliases: aliases,
                aliasesAndName: aliases.concat([ name ]),
                parameter: command.parameter || null,
                execute: function(param) {
                    if (param === '' && this.parameter) {
                        return this.parameter.messageIfMissing;
                    }

                    return execute(param);
                }
            };
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.CommandRepository = {
        _data: [],
        register: function(commands) {
            for (var i = 0, ii = commands.length; i < ii; i++) {
                this._data.push(commands[i]);
            }
        },
        findByCommandText: function(commandText) {
            return this._data.find(function(command, index, obj) {
                var aliasesAndName = command.aliasesAndName;

                if (command.parameter) {
                    return !!aliasesAndName.find(function(aliasOrName) {
                        return commandText.indexOf(aliasOrName) === 0;
                    });
                }

                return aliasesAndName.indexOf(commandText) !== -1;
            });
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.TerminalFactory = {
        create: function() {
            return Terminal.create({
                results: document.getElementById('terminalReslutsCont'),
                textInput: document.getElementById('terminalTextInput')
            });
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.openWindowCommand = {
        name: 'open',
        parameter: {
            name: 'link',
            messageIfMissing: 'Type open + something to navigate.'
        },
        execute: function(link) {
            window.open('http://' + link.toLowerCase(), '_blank');
            return 'The URL ' + link + ' should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToCreatorCommand = {
        name: 'creators',
        response: 'My Creator is Pedro Laxe with cooperation of Gabriel Takashi Katakura.'
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToDateCommand = {
        name: 'date',
        response: function() {
            var timeAndDate = new Date(),
                dateDay = timeAndDate.getDate(),
                dateMonth = timeAndDate.getMonth() + 1,
                dateYear = timeAndDate.getFullYear();

            console.log(dateDay);

            return dateDay + '/' + dateMonth + '/' + dateYear;
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToGitCommand = {
        name: 'git',
        response: [
            'git push origin master',
            'you can check this project\'s repo on GitHub: https://github.com/pedrolaxe/js-terminal'
        ]
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToGitPushOriginMasterCommand = {
        name: 'git push origin master',
        response: 'Push me baby!' // \o/
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToGitStatusCommand = {
        name: 'git status',
        response: 'nothing to commit, working directory clean.'
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToHelloCommand = {
        name: 'hello',
        aliases: [ 'hi', 'hola', 'oi' ],
        response: 'Hello, it\'s me... I was wondering if after all these years you\'d like to meet...'
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToHelpCommand = {
        name: 'help',
        aliases: [ '?' ],
        response: [
            '- Open + website URL to open it in the browser (ex. open phpsec.com.br)',
            '- Google + keyword to search directly in Google (ex. google phpsec)',
            '- Yahoo + keyword to search directly in Yahoo (ex. yahoo dogs)',
            '- iiissa + keyword to search directly in IIISSA (ex. iiissa pedro)',
            '- YouTube + keyword to search directly in YouTube (ex. youtube fora pt)',
            '- Wiki + keyword to search directly in Wikipedia (ex. wiki javascript)',
            '- \'Time\' will display the current time.',
            '- \'Date\' will display the current date.',
            '- \'creators\' show the creators names.',
            '* There are more keywords that you have to discover by yourself.'
        ]
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToLoveYouCommand = {
        name: 'love you',
        aliases: [ 'i love you', 'love' ],
        response: 'Aww! That\'s so sweet. Here\'s some love for you too ❤ ❤ ❤ !'
    };
})(window.Terminal);
(function(Terminal) {
    function padLeft(value, totalWidth, paddingChar){
        return Array(totalWidth - value.toString().length + 1).join(paddingChar || '0') + value;
    }

    Terminal.commands.replyToTimeCommand = {
        name: 'time',
        response: function() {
            var timeAndDate = new Date(),
                timeHours = padLeft(timeAndDate.getHours(), 2),
                timeMinutes = padLeft(timeAndDate.getMinutes(), 2);

            console.log(timeAndDate.getDate());

            return timeHours + ":" + timeMinutes;
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOnGoogleCommand = {
        name: 'google',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type google + something to search for.'
        },
        execute: function(search) {
            window.open('https://www.google.com.br/search?q=' + search, '_blank');
            return 'I\'ve searched on Google for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOnWikiCommand = {
        name: 'wiki',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type wiki + something to search for.'
        },
        execute: function(search) {
            window.open('https://pt.wikipedia.org/w/index.php?search=' + search, '_blank');
            return 'I\'ve searched on Wikipedia for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOnYahooCommand = {
        name: 'yahoo',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type yahoo + something to search for.'
        },
        execute: function(search) {
            window.open('https://br.search.yahoo.com/search?p=' + search, '_blank');
            return 'I\'ve searched on Yahoo for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOniiissaCommand = {
        name: 'iiissa',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type iiissa + something to search for.'
        },
        execute: function(search) {
            window.open('https://iiissa.com.br/buscar?q=' + search + '&tipo=emp', '_blank');
            return 'I\'ve searched on IIISSA for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);

(function(Terminal) {
    Terminal.commands.searchOnYoutubeCommand = {
        name: 'youtube',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type youtube + something to search for.'
        },
        execute: function(search) {
            window.open('https://www.youtube.com/results?search_query=' + search, '_blank');
            return 'I\'ve searched on YouTube for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);

(function(Terminal) {
    Terminal.start();

    document.addEventListener('DOMContentLoaded', function() {
        var terminal = Terminal.TerminalFactory.create();
        terminal.focus();

        document.getElementsByTagName('form')[0].onsubmit = function(evt) {
            evt.preventDefault();
            terminal.enter();
            window.scrollTo(0, 150);
            console.log("JS Terminal Loaded");
        };
    });
})(window.Terminal);
<commit_msg>update version<commit_after>/**
* JS Terminal
* Version 1.2.3
* Author: Pedro Laxe <pedro@phpsec.com.br>
* Contributor: Gabriel Takashi Katakura <gt.katakura@gmail.com>
**/

(function(global) {
    var Terminal = {
        _resolveCommands: function() {
            return Object.keys(this.commands).map(function(key) {
                return Terminal.CommandDecorator.decorate(Terminal.commands[key]);
            });
        },
        start: function() {
            var resolvedCommands = this._resolveCommands();
            this.CommandRepository.register(resolvedCommands);
        },
        commands: {},
        create: function(options) {
            var results = options.results,
                textInput = options.textInput;

            return {
                _addTextToResults: function(text) {
                    results.innerHTML += '
' + text + '
';
                },
                _clearInput: function() {
                    textInput.value = '';
                },
                _scrollToBottomOfResults: function() {
                    results.scrollTop = results.scrollHeight;
                },
                focus: function() {
                    textInput.focus();
                    this._scrollToBottomOfResults();
                },
                enter: function() {
                    var commandText = textInput.value.trim(),
                        command = Terminal.CommandRepository.findByCommandText(commandText.toLowerCase()),
                        parameter = '',
                        response = '';

                    this._addTextToResults('
> ' + commandText + '
');

                    if (command) {
                        parameter = commandText.replace(command.name, '').trim();
                        response = command.execute(parameter);
                    }
                    else {
                        response = '
The command ' + commandText + ' was not found. Type Help to see all commands.
';
                    }

                    this._addTextToResults(response);
                    this._clearInput();
                    this._scrollToBottomOfResults();
                }
            };
        }
    };

    global.Terminal = Terminal;
})(window);
(function(Terminal) {
    var emptyFunction = function() {},
        isArray = function(arg) {
            return Object.prototype.toString.call(arg) === '[object Array]';
        };

    Terminal.CommandDecorator = {
        _transformToFunction: function(response) {
            if (isArray(response)) {
                response = response.join('
');
            }

            if (typeof response === 'string') {
                return function() {
                    return response;
                };
            }

            return response || emptyFunction;
        },
        decorate: function(command) {
            var name = command.name || '',
                aliases = command.aliases || [],
                execute = command.execute || this._transformToFunction(command.response);

            return {
                name: name,
                aliases: aliases,
                aliasesAndName: aliases.concat([ name ]),
                parameter: command.parameter || null,
                execute: function(param) {
                    if (param === '' && this.parameter) {
                        return this.parameter.messageIfMissing;
                    }

                    return execute(param);
                }
            };
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.CommandRepository = {
        _data: [],
        register: function(commands) {
            for (var i = 0, ii = commands.length; i < ii; i++) {
                this._data.push(commands[i]);
            }
        },
        findByCommandText: function(commandText) {
            return this._data.find(function(command, index, obj) {
                var aliasesAndName = command.aliasesAndName;

                if (command.parameter) {
                    return !!aliasesAndName.find(function(aliasOrName) {
                        return commandText.indexOf(aliasOrName) === 0;
                    });
                }

                return aliasesAndName.indexOf(commandText) !== -1;
            });
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.TerminalFactory = {
        create: function() {
            return Terminal.create({
                results: document.getElementById('terminalReslutsCont'),
                textInput: document.getElementById('terminalTextInput')
            });
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.openWindowCommand = {
        name: 'open',
        parameter: {
            name: 'link',
            messageIfMissing: 'Type open + something to navigate.'
        },
        execute: function(link) {
            window.open('http://' + link.toLowerCase(), '_blank');
            return 'The URL ' + link + ' should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToCreatorCommand = {
        name: 'creators',
        response: 'My Creator is Pedro Laxe with cooperation of Gabriel Takashi Katakura.'
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToDateCommand = {
        name: 'date',
        response: function() {
            var timeAndDate = new Date(),
                dateDay = timeAndDate.getDate(),
                dateMonth = timeAndDate.getMonth() + 1,
                dateYear = timeAndDate.getFullYear();

            console.log(dateDay);

            return dateDay + '/' + dateMonth + '/' + dateYear;
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToGitCommand = {
        name: 'git',
        response: [
            'git push origin master',
            'you can check this project\'s repo on GitHub: https://github.com/pedrolaxe/js-terminal'
        ]
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToGitPushOriginMasterCommand = {
        name: 'git push origin master',
        response: 'Push me baby!' // \o/
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToGitStatusCommand = {
        name: 'git status',
        response: 'nothing to commit, working directory clean.'
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToHelloCommand = {
        name: 'hello',
        aliases: [ 'hi', 'hola', 'oi' ],
        response: 'Hello, it\'s me... I was wondering if after all these years you\'d like to meet...'
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToHelpCommand = {
        name: 'help',
        aliases: [ '?' ],
        response: [
            '- Open + website URL to open it in the browser (ex. open phpsec.com.br)',
            '- Google + keyword to search directly in Google (ex. google phpsec)',
            '- Yahoo + keyword to search directly in Yahoo (ex. yahoo dogs)',
            '- iiissa + keyword to search directly in IIISSA (ex. iiissa pedro)',
            '- YouTube + keyword to search directly in YouTube (ex. youtube fora pt)',
            '- Wiki + keyword to search directly in Wikipedia (ex. wiki javascript)',
            '- \'Time\' will display the current time.',
            '- \'Date\' will display the current date.',
            '- \'creators\' show the creators names.',
            '* There are more keywords that you have to discover by yourself.'
        ]
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.replyToLoveYouCommand = {
        name: 'love you',
        aliases: [ 'i love you', 'love' ],
        response: 'Aww! That\'s so sweet. Here\'s some love for you too ❤ ❤ ❤ !'
    };
})(window.Terminal);
(function(Terminal) {
    function padLeft(value, totalWidth, paddingChar){
        return Array(totalWidth - value.toString().length + 1).join(paddingChar || '0') + value;
    }

    Terminal.commands.replyToTimeCommand = {
        name: 'time',
        response: function() {
            var timeAndDate = new Date(),
                timeHours = padLeft(timeAndDate.getHours(), 2),
                timeMinutes = padLeft(timeAndDate.getMinutes(), 2);

            console.log(timeAndDate.getDate());

            return timeHours + ":" + timeMinutes;
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOnGoogleCommand = {
        name: 'google',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type google + something to search for.'
        },
        execute: function(search) {
            window.open('https://www.google.com.br/search?q=' + search, '_blank');
            return 'I\'ve searched on Google for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOnWikiCommand = {
        name: 'wiki',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type wiki + something to search for.'
        },
        execute: function(search) {
            window.open('https://pt.wikipedia.org/w/index.php?search=' + search, '_blank');
            return 'I\'ve searched on Wikipedia for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOnYahooCommand = {
        name: 'yahoo',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type yahoo + something to search for.'
        },
        execute: function(search) {
            window.open('https://br.search.yahoo.com/search?p=' + search, '_blank');
            return 'I\'ve searched on Yahoo for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);
(function(Terminal) {
    Terminal.commands.searchOniiissaCommand = {
        name: 'iiissa',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type iiissa + something to search for.'
        },
        execute: function(search) {
            window.open('https://iiissa.com.br/buscar?q=' + search + '&tipo=emp', '_blank');
            return 'I\'ve searched on IIISSA for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);

(function(Terminal) {
    Terminal.commands.searchOnYoutubeCommand = {
        name: 'youtube',
        parameter: {
            name: 'search',
            messageIfMissing: 'Type youtube + something to search for.'
        },
        execute: function(search) {
            window.open('https://www.youtube.com/results?search_query=' + search, '_blank');
            return 'I\'ve searched on YouTube for ' + search + ' it should be opened now.';
        }
    };
})(window.Terminal);

(function(Terminal) {
    Terminal.start();

    document.addEventListener('DOMContentLoaded', function() {
        var terminal = Terminal.TerminalFactory.create();
        terminal.focus();

        document.getElementsByTagName('form')[0].onsubmit = function(evt) {
            evt.preventDefault();
            terminal.enter();
            window.scrollTo(0, 150);
            console.log("JS Terminal Loaded");
        };
    });
})(window.Terminal);
<|endoftext|>


<commit_before>/*  Snowfall pure js
        ====================================================================
        LICENSE
        ====================================================================
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        ====================================================================

        1.0
        Wanted to rewrite my snow plugin to use pure JS so you werent necessarily tied to using a framework.
        Does not include a selector engine or anything, just pass elements to it using standard JS selectors.

        Does not clear snow currently. Collection portion removed just for ease of testing will add back in next version

        Theres a few ways to call the snow you could do it the following way by directly passing the selector,

                snowFall.snow(document.getElementsByTagName("body"), {options});

        or you could save the selector results to a variable, and then call it

                var elements = document.getElementsByClassName('yourclass');
                snowFall.snow(elements, {options});

        Options are all the same as the plugin except clear, and collection

        values for snow options are

        flakeCount,
        flakeColor,
        flakeIndex,
        minSize,
        maxSize,
        minSpeed,
        maxSpeed,
        round,                 true or false, makes the snowflakes rounded if the browser supports it.
        shadow                true or false, gives the snowflakes a shadow if the browser supports it.

*/

// Paul Irish requestAnimationFrame polyfill
(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

var snowFall = (function(){
	var fixed = false;
        function jSnow(){
                // local methods
                var        defaults = {
                        flakeCount : 35,
                        flakeColor : '#ffffff',
                        flakeIndex: 999999,
                        minSize : 1,
                        maxSize : 2,
                        minSpeed : 1,
                        maxSpeed : 5,
                        round : false,
                        shadow : false,
                        collection : false,
                        image : false,
                        collectionHeight : 40
                        },
                        element = {},
                        flakes = [],
                        flakeId = 0,
                        elHeight = 0,
                        elWidth = 0,
                        elTop = 0,
                        elLeft = 0,
                        widthOffset = 0,
                        snowTimeout = 0,
                        // For extending the default object with properties
                        extend = function(obj, extObj){
                                for(var i in extObj){
                                        if(obj.hasOwnProperty(i)){
                                                obj[i] = extObj[i];
                                        }
                                }
                        },
                        // random between range
                        random = function random(min, max){
                                return Math.round(min + Math.random()*(max-min));
                        },
                        // Set multiple styles at once.
                        setStyle = function(element, props)
                        {
                                for (var property in props){
                                        element.style[property] = props[property] + ((property == 'width' || property == 'height') ? 'px' : '');
                                }
                        },
                        // snowflake
						subDiv = document.createElement("div");
						subDiv.id = "snowfall";
						document.body.appendChild(subDiv);
                        flake = function(_x, _y, _size, _speed, _id)
                        {
                                // Flake properties
                                this.id = _id;
                                this.x  = _x + elLeft;
                                this.y  = _y + elTop;
                                this.size = _size;
                                this.speed = _speed;
                                this.step = 0;
                                this.stepSize = random(1,10) / 100;

                                if(defaults.collection){
                                        this.target = canvasCollection[random(0,canvasCollection.length-1)];
                                }

                                var flakeObj = null;

                                if(defaults.image){
                                        flakeObj = new Image();
                                        flakeObj.src = defaults.image;
                                }else{
                                        flakeObj = document.createElement("div");
                                        setStyle(flakeObj, {'background' : defaults.flakeColor});
                                }

                                flakeObj.className = 'snowfall-flakes';
                                flakeObj.setAttribute('id','flake-' + this.id);
                                setStyle(flakeObj, {'width' : this.size, 'height' : this.size, 'position' : (fixed ? 'fixed' : 'absolute'),
								'top' : this.y, 'left' : this.x, 'fontSize' : 0, 'zIndex' : defaults.flakeIndex});

                                // This adds the style to make the snowflakes round via border radius property
                                if(defaults.round){
                                        setStyle(flakeObj,{'-moz-border-radius' : ~~(defaults.maxSize) + 'px',
										'-webkit-border-radius' : ~~(defaults.maxSize) + 'px', 'borderRadius' : ~~(defaults.maxSize) + 'px'});
                                }

                                // This adds shadows just below the snowflake so they pop a bit on lighter colored web pages
                                if(defaults.shadow){
                                        setStyle(flakeObj,{'-moz-box-shadow' : '1px 1px 1px #555', '-webkit-box-shadow' : '1px 1px 1px #555',
										'boxShadow' : '1px 1px 1px #555'});
                                }

                                subDiv.appendChild(flakeObj);

                                this.element = flakeObj;

                                // Update function, used to update the snow flakes, and checks current snowflake against bounds
                                this.update = function(){
                                        this.y += this.speed;

                                        if(this.y > (elTop + elHeight) - (this.size - 2) || this.x <= elLeft || this.x >= elLeft + elWidth - 1){
                                                this.reset();
                                        }

                                        this.element.style.top = this.y + 'px';
                                        this.element.style.left = ~~this.x + 'px';

                                        this.step += this.stepSize;
                                        this.x += Math.cos(this.step);

                                        if(this.x > (elLeft + elWidth) - widthOffset || this.x < widthOffset){
                                                this.reset();
                                        }
                                }

                                // Resets the snowflake once it reaches one of the bounds set
                                this.reset = function(){
                                        this.y = elTop;
                                        this.x = elLeft + random(widthOffset, elWidth - widthOffset);
                                        this.stepSize = random(1,10) / 100;
                                        this.size = random((defaults.minSize * 100), (defaults.maxSize * 100)) / 100;
                                        this.speed = random(defaults.minSpeed, defaults.maxSpeed);
                                }
                        },
                        // this controls flow of the updating snow
                        animateSnow = function(){
                                for(var i = 0; i < flakes.length; i += 1){
                                        flakes[i].update();
                                }
                                snowTimeout = requestAnimationFrame(function(){animateSnow()});
                        }
                return{
                        snow : function(_element, _options){
                                extend(defaults, _options);

                                //init the element vars
                                element = _element;
                                elHeight = element.clientHeight,
                                elWidth = element.offsetWidth;
                                elTop = element.offsetTop;
                                elLeft = element.offsetLeft;

                                element.snow = this;

                                // if this is the body the offset is a little different
                                if(element.tagName.toLowerCase() === 'body'){
                                        widthOffset = 25;
                                }

                                // Bind the window resize event so we can get the innerHeight again
                                window.onresize = function(){
                                        elHeight = element.clientHeight;
                                        elWidth = element.offsetWidth;
                                        elTop = element.offsetTop;
                                        elLeft = element.offsetLeft;
                                }

                                // initialize the flakes
                                for(i = 0; i < defaults.flakeCount; i+=1){
                                        flakeId = flakes.length;
                                        flakes.push(new flake(random(widthOffset,elWidth - widthOffset), random(0, elHeight),
										random((defaults.minSize * 100), (defaults.maxSize * 100)) / 100,
										random(defaults.minSpeed, defaults.maxSpeed), flakeId));
                                }
                                // start the snow
                                animateSnow();
                        },
                        clear : function(){
                                var flakeChildren = null;

                                if(!element.getElementsByClassName){
                                        flakeChildren = element.querySelectorAll('.snowfall-flakes');
                                }else{
                                        flakeChildren = element.getElementsByClassName('snowfall-flakes');
                                }

                                var flakeChilLen = flakeChildren.length;
                                while(flakeChilLen--){
                                        element.removeChild(flakeChildren[flakeChilLen]);
                                }

                                flakes = [];
                                cancelAnimationFrame(snowTimeout);
                        }
                }
        };
        return{
                snow : function(elements, options){
					if (elements.css("position") == "fixed")
						fixed = true;
                        if(typeof(options) == "string"){
                                if(elements.length > 0){
                                        for(var i = 0; i < elements.length; i++){
                                                if(elements[i].snow){
                                                        elements[i].snow.clear();
                                                }
                                        }
                                }else{
                                        elements.snow.clear();
                                }
                        }else{
                                if(elements.length > 0){
                                        for(var i = 0; i < elements.length; i++){
                                                new jSnow().snow(elements[i], options);
                                        }
                                }else{
                                        new jSnow().snow(elements, options);
                                }
                        }
                }
        }
})();<commit_msg>Remove snowfall.js<commit_after><|endoftext|>


<commit_before>var light_block_emit = new Buffer(256),
    light_block_stop = new Buffer(256);

light_block_emit.fill(0);
light_block_stop.fill(15);

light_block_emit[0x0a] = 15;
light_block_emit[0x0b] = 15;
light_block_emit[0x27] = 1;
light_block_emit[0x32] = 14;
light_block_emit[0x33] = 15;
light_block_emit[0x3e] = 14;
light_block_emit[0x4a] = 9;
light_block_emit[0x4c] = 7;
light_block_emit[0x59] = 15;
light_block_emit[0x5a] = 11;
light_block_emit[0x5b] = 15;

light_block_stop[0x00] = 0;
light_block_stop[0x06] = 0;
light_block_stop[0x08] = 2;
light_block_stop[0x09] = 2;
light_block_stop[0x12] = 2;
light_block_stop[0x14] = 0;
light_block_stop[0x25] = 0;
light_block_stop[0x26] = 0;
light_block_stop[0x27] = 0;
light_block_stop[0x28] = 0;
light_block_stop[0x32] = 0;
light_block_stop[0x33] = 0;
light_block_stop[0x34] = 0;
light_block_stop[0x35] = 0;
light_block_stop[0x37] = 0;
light_block_stop[0x40] = 0;
light_block_stop[0x41] = 0;
light_block_stop[0x42] = 0;
light_block_stop[0x43] = 0;
light_block_stop[0x47] = 0;
light_block_stop[0x4b] = 0;
light_block_stop[0x4c] = 0;
light_block_stop[0x4e] = 0;
light_block_stop[0x4f] = 2;
light_block_stop[0x55] = 0;
light_block_stop[0x5a] = 0;
light_block_stop[0x5b] = 0;

var async = require("async");

var Chunk = require("./chunk");

var Map = module.exports = function Map(generators) {
  this.chunks = {};

  this.generators = generators || [];
};

Map.prototype.add_generator = function add_generator(fn) {
  this.generators.push(fn);
};

Map.prototype.make_key = function make_key(x, z) {
  return x.toString(36) + ":" + z.toString(36);
};

Map.prototype.get_abs_chunk = function get_abs_chunk(block_x, block_z, cb) {
  return this.get_chunk(block_x >> 4, block_z >> 4, cb);
};

Map.prototype.get_chunk = function get_chunk(chunk_x, chunk_z, cb) {
  var key = this.make_key(chunk_x, chunk_z);

  if (this.chunks[key]) {
    return cb(null, this.chunks[key]);
  }

  var chunk = this.chunks[key] = new Chunk(chunk_x, chunk_z);
  async.waterfall([function initial(cb) { cb(null, chunk); }].concat(this.generators), function(err, chunk) {
    return cb(err, chunk);
  }, function(err, chunk) {
    this.calculate_light(chunk);

    return cb(err, chunk);
  });
};

Map.prototype.calculate_light = function calculate_light(chunk) {
  chunk.data.fill(0, 98304, 163840);

  var spread_sky = this.initial_light_sky(chunk),
      spread_block = this.initial_light_block(chunk);

  // spread light from other chunk edges
  for (var y = 0; y < 256; ++y) {
    for (var i = 0; i < 16; ++i) {
      spread_sky.push(  [((chunk.x << 4) + i),      ((chunk.z + 1) << 4),      y]);
      spread_sky.push(  [((chunk.x << 4) + i),      ((chunk.z - 1) << 4) + 15, y]);
      spread_sky.push(  [((chunk.x + 1) << 4),      ((chunk.z << 4) + i),      y]);
      spread_sky.push(  [((chunk.x - 1) << 4) + 15, ((chunk.z << 4) + i),      y]);
      spread_block.push([((chunk.x << 4) + i),      ((chunk.z + 1) << 4),      y]);
      spread_block.push([((chunk.x << 4) + i),      ((chunk.z - 1) << 4) + 15, y]);
      spread_block.push([((chunk.x + 1) << 4),      ((chunk.z << 4) + i),      y]);
      spread_block.push([((chunk.x - 1) << 4) + 15, ((chunk.z << 4) + i),      y]);
    }
  }

  while (spread_sky.length) {
    var job = spread_sky.shift();
    this.spread_light_sky(job[0], job[1], job[2], spread_sky, chunk.x, chunk.z, chunk);
  }

  while (spread_block.length) {
    var job = spread_block.shift();
    this.spread_light_block(job[0], job[1], job[2], spread_block, chunk.x, chunk.z, chunk);
  }
};

Map.prototype.initial_light_sky = function initial_light_sky(chunk) {
  var jobs = [];

  var light;

  for (var x = 0; x < 16; ++x) {
    for (var z = 0; z < 16; ++z) {
      light = 15;

      for (var y = 255; y >= 0; --y) {
        light -= light_block_stop[chunk.get_block_type(x, z, y)];

        if (light <= 0) {
          break;
        }

        chunk.set_light_sky(x, z, y, light);
        jobs.push([(chunk.x << 4) + x, (chunk.z << 4) + z, y]);
      }
    }
  }

  return jobs;
};

Map.prototype.spread_light_sky = function spread_light_sky(abs_x, abs_z, y, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var s = chunk.get_light_sky(x, z, y);

  this.spread_light_sky_apply(abs_x - 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_sky_apply(abs_x + 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_sky_apply(abs_x,     abs_z - 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_sky_apply(abs_x,     abs_z + 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  if (y >   0) { this.spread_light_sky_apply(abs_x,     abs_z,     y - 1, s, jobs, chunk_x, chunk_z, chunk); }
  if (y < 255) { this.spread_light_sky_apply(abs_x,     abs_z,     y + 1, s, jobs, chunk_x, chunk_z, chunk); }
};

Map.prototype.spread_light_sky_apply = function spread_light_sky_apply(abs_x, abs_z, y, s, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var reduction = light_block_stop[chunk.get_block_type(x, z, y)] + 1,
      result = Math.max(s - reduction, 0);

  var t = chunk.get_light_sky(x, z, y);

  if (t < result) {
    chunk.set_light_sky(x, z, y, result);
    jobs.push([abs_x, abs_z, y]);
  }
};

Map.prototype.initial_light_block = function initial_light_block(chunk) {
  var jobs = [];

  for (var x = 0; x < 16; ++x) {
    for (var z = 0; z < 16; ++z) {
      for (var y = 0; y < 256; ++y) {
        var light = light_block_emit[chunk.get_block_type(x, z, y)];
        if (!light) { continue; }
        chunk.set_light_block(x, z, y, light);
        jobs.push([(chunk.x << 4) + x, (chunk.z << 4) + z, y]);
      }
    }
  }

  return jobs;
};

Map.prototype.spread_light_block = function spread_light_block(abs_x, abs_z, y, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var s = chunk.get_light_block(x, z, y);

  this.spread_light_block_apply(abs_x - 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_block_apply(abs_x + 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_block_apply(abs_x,     abs_z - 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_block_apply(abs_x,     abs_z + 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  if (y >   0) { this.spread_light_block_apply(abs_x,     abs_z,     y - 1, s, jobs, chunk_x, chunk_z, chunk); }
  if (y < 255) { this.spread_light_block_apply(abs_x,     abs_z,     y + 1, s, jobs, chunk_x, chunk_z, chunk); }
};

Map.prototype.spread_light_block_apply = function spread_light_block_apply(abs_x, abs_z, y, s, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var reduction = light_block_stop[chunk.get_block_type(x, z, y)] + 1,
      result = Math.max(s - reduction, 0);

  var t = chunk.get_light_block(x, z, y);

  if (t < result) {
    chunk.set_light_block(x, z, y, result);
    jobs.push([abs_x, abs_z, y]);
  }
};
<commit_msg>calculate_light -> initial_light, async<commit_after>var light_block_emit = new Buffer(256),
    light_block_stop = new Buffer(256);

light_block_emit.fill(0);
light_block_stop.fill(15);

light_block_emit[0x0a] = 15;
light_block_emit[0x0b] = 15;
light_block_emit[0x27] = 1;
light_block_emit[0x32] = 14;
light_block_emit[0x33] = 15;
light_block_emit[0x3e] = 14;
light_block_emit[0x4a] = 9;
light_block_emit[0x4c] = 7;
light_block_emit[0x59] = 15;
light_block_emit[0x5a] = 11;
light_block_emit[0x5b] = 15;

light_block_stop[0x00] = 0;
light_block_stop[0x06] = 0;
light_block_stop[0x08] = 2;
light_block_stop[0x09] = 2;
light_block_stop[0x12] = 2;
light_block_stop[0x14] = 0;
light_block_stop[0x25] = 0;
light_block_stop[0x26] = 0;
light_block_stop[0x27] = 0;
light_block_stop[0x28] = 0;
light_block_stop[0x32] = 0;
light_block_stop[0x33] = 0;
light_block_stop[0x34] = 0;
light_block_stop[0x35] = 0;
light_block_stop[0x37] = 0;
light_block_stop[0x40] = 0;
light_block_stop[0x41] = 0;
light_block_stop[0x42] = 0;
light_block_stop[0x43] = 0;
light_block_stop[0x47] = 0;
light_block_stop[0x4b] = 0;
light_block_stop[0x4c] = 0;
light_block_stop[0x4e] = 0;
light_block_stop[0x4f] = 2;
light_block_stop[0x55] = 0;
light_block_stop[0x5a] = 0;
light_block_stop[0x5b] = 0;

var async = require("async");

var Chunk = require("./chunk");

var Map = module.exports = function Map(generators) {
  this.chunks = {};

  this.generators = generators || [];
};

Map.prototype.add_generator = function add_generator(fn) {
  this.generators.push(fn);
};

Map.prototype.make_key = function make_key(x, z) {
  return x.toString(36) + ":" + z.toString(36);
};

Map.prototype.get_abs_chunk = function get_abs_chunk(block_x, block_z, cb) {
  return this.get_chunk(block_x >> 4, block_z >> 4, cb);
};

Map.prototype.get_chunk = function get_chunk(chunk_x, chunk_z, cb) {
  var key = this.make_key(chunk_x, chunk_z);

  if (this.chunks[key]) {
    return cb(null, this.chunks[key]);
  }

  var chunk = this.chunks[key] = new Chunk(chunk_x, chunk_z);
  async.waterfall([function initial(cb) { cb(null, chunk); }].concat(this.generators), function(err, chunk) {
    this.initial_light(chunk, function(err, chunk) {
      return cb(err, chunk);
    });
  }.bind(this));
};

Map.prototype.initial_light = function initial_light(chunk, cb) {
  chunk.data.fill(0, 98304, 163840);

  var spread_sky = this.initial_light_sky(chunk),
      spread_block = this.initial_light_block(chunk);

  // spread light from other chunk edges
  for (var y = 0; y < 256; ++y) {
    for (var i = 0; i < 16; ++i) {
      spread_sky.push(  [((chunk.x << 4) + i),      ((chunk.z + 1) << 4),      y]);
      spread_sky.push(  [((chunk.x << 4) + i),      ((chunk.z - 1) << 4) + 15, y]);
      spread_sky.push(  [((chunk.x + 1) << 4),      ((chunk.z << 4) + i),      y]);
      spread_sky.push(  [((chunk.x - 1) << 4) + 15, ((chunk.z << 4) + i),      y]);
      spread_block.push([((chunk.x << 4) + i),      ((chunk.z + 1) << 4),      y]);
      spread_block.push([((chunk.x << 4) + i),      ((chunk.z - 1) << 4) + 15, y]);
      spread_block.push([((chunk.x + 1) << 4),      ((chunk.z << 4) + i),      y]);
      spread_block.push([((chunk.x - 1) << 4) + 15, ((chunk.z << 4) + i),      y]);
    }
  }

  while (spread_sky.length) {
    var job = spread_sky.shift();
    this.spread_light_sky(job[0], job[1], job[2], spread_sky, chunk.x, chunk.z, chunk);
  }

  while (spread_block.length) {
    var job = spread_block.shift();
    this.spread_light_block(job[0], job[1], job[2], spread_block, chunk.x, chunk.z, chunk);
  }

  return cb(null, chunk);
};

Map.prototype.initial_light_sky = function initial_light_sky(chunk) {
  var jobs = [];

  var light;

  for (var x = 0; x < 16; ++x) {
    for (var z = 0; z < 16; ++z) {
      light = 15;

      for (var y = 255; y >= 0; --y) {
        light -= light_block_stop[chunk.get_block_type(x, z, y)];

        if (light <= 0) {
          break;
        }

        chunk.set_light_sky(x, z, y, light);
        jobs.push([(chunk.x << 4) + x, (chunk.z << 4) + z, y]);
      }
    }
  }

  return jobs;
};

Map.prototype.spread_light_sky = function spread_light_sky(abs_x, abs_z, y, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var s = chunk.get_light_sky(x, z, y);

  this.spread_light_sky_apply(abs_x - 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_sky_apply(abs_x + 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_sky_apply(abs_x,     abs_z - 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_sky_apply(abs_x,     abs_z + 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  if (y >   0) { this.spread_light_sky_apply(abs_x,     abs_z,     y - 1, s, jobs, chunk_x, chunk_z, chunk); }
  if (y < 255) { this.spread_light_sky_apply(abs_x,     abs_z,     y + 1, s, jobs, chunk_x, chunk_z, chunk); }
};

Map.prototype.spread_light_sky_apply = function spread_light_sky_apply(abs_x, abs_z, y, s, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var reduction = light_block_stop[chunk.get_block_type(x, z, y)] + 1,
      result = Math.max(s - reduction, 0);

  var t = chunk.get_light_sky(x, z, y);

  if (t < result) {
    chunk.set_light_sky(x, z, y, result);
    jobs.push([abs_x, abs_z, y]);
  }
};

Map.prototype.initial_light_block = function initial_light_block(chunk) {
  var jobs = [];

  for (var x = 0; x < 16; ++x) {
    for (var z = 0; z < 16; ++z) {
      for (var y = 0; y < 256; ++y) {
        var light = light_block_emit[chunk.get_block_type(x, z, y)];
        if (!light) { continue; }
        chunk.set_light_block(x, z, y, light);
        jobs.push([(chunk.x << 4) + x, (chunk.z << 4) + z, y]);
      }
    }
  }

  return jobs;
};

Map.prototype.spread_light_block = function spread_light_block(abs_x, abs_z, y, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var s = chunk.get_light_block(x, z, y);

  this.spread_light_block_apply(abs_x - 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_block_apply(abs_x + 1, abs_z,     y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_block_apply(abs_x,     abs_z - 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  this.spread_light_block_apply(abs_x,     abs_z + 1, y,     s, jobs, chunk_x, chunk_z, chunk);
  if (y >   0) { this.spread_light_block_apply(abs_x,     abs_z,     y - 1, s, jobs, chunk_x, chunk_z, chunk); }
  if (y < 255) { this.spread_light_block_apply(abs_x,     abs_z,     y + 1, s, jobs, chunk_x, chunk_z, chunk); }
};

Map.prototype.spread_light_block_apply = function spread_light_block_apply(abs_x, abs_z, y, s, jobs, chunk_x, chunk_z, chunk) {
  if ((abs_x >> 4) !== chunk_x || (abs_z >> 4) !== chunk_z) {
    chunk_x = abs_x >> 4;
    chunk_z = abs_z >> 4;
    chunk = this.chunks[this.make_key(chunk_x, chunk_z)];
  }
  if (!chunk) {
    return;
  }

  var x = abs_x & 0x0f,
      z = abs_z & 0x0f;

  var reduction = light_block_stop[chunk.get_block_type(x, z, y)] + 1,
      result = Math.max(s - reduction, 0);

  var t = chunk.get_light_block(x, z, y);

  if (t < result) {
    chunk.set_light_block(x, z, y, result);
    jobs.push([abs_x, abs_z, y]);
  }
};
<|endoftext|>


<commit_before>/*global
 define
 */
/*jslint
 browser: true,
 white: true
 */
define([], function () {
    'use strict';
    var eventsPendingAttachment = [],
        eventsAttached = [];

    // DOM EVENTS
    function addEvent(type, handler, id, data) {
        if (!id) {
            id = html.genId();
        }
        var event = {
            type: type,
            selector: '#' + id,
            nodeId: id,
            handler: handler
        };
        eventsPendingAttachment.push(event);
        return id;
    }
    function attachEvents() {
        eventsPendingAttachment.forEach(function (event) {
            event.node = dom.nodeForId(event.nodeId);
            event.listener = event.node.addEventListener(event.type, event.handler);
            eventsAttached.push(event);
        });
        eventsPendingAttachment = [];
    }
    function detachEvents() {
        eventsAttached.forEach(function (event) {
            if (event.listener) {
                event.node.removeEventListener(event.type, event.handler);
                delete event.listener;
            }
        });
        eventsAttached = [];
    }

    function createElement(name) {
        return document.createElement(name);
    }
    function appendRoot(child) {
        document.appendChild(child);
    }
    function append(parent, child) {
        return parent.appendChild(child);
    }
    function remove(parent, child) {
        return parent.removeChild(child);
    }
    function findById(id) {
        return document.getElementById(id);
    }
    function nodeForId(id) {
        return document.getElementById(id);
    }
    function qs(selector) {
        return document.querySelector(selector);
    }
    function setHtml(nodeOrSelector, content) {
        var node;
        if (typeof nodeOrSelector === 'string') {
            node = qs(nodeOrSelector);
            if (node === null) {
                throw new Error('No node found for selector "' + nodeOrSelector + '"');
            }
        } else {
            node = nodeOrSelector;
        }
        node.innerHTML = content;
        return node;
    }

    return Object.freeze({
        createElement: createElement,
        appendRoot: appendRoot,
        append: append,
        remove: remove,
        setHTML: setHtml,
        setHtml: setHtml,
        findById: findById,
        nodeForId: nodeForId,
        getById: findById,
        qs: qs,
        addEvent: addEvent,
        attachEvents: attachEvents,
        detachEvents: detachEvents
    });
});<commit_msg>never mind<commit_after>/*global
 define
 */
/*jslint
 browser: true,
 white: true
 */
define([], function () {
    'use strict';
    function createElement(name) {
        return document.createElement(name);
    }
    function appendRoot(child) {
        document.appendChild(child);
    }
    function append(parent, child) {
        return parent.appendChild(child);
    }
    function remove(parent, child) {
        return parent.removeChild(child);
    }
    function findById(id) {
        return document.getElementById(id);
    }
    function nodeForId(id) {
        return document.getElementById(id);
    }
    function qs(selector) {
        return document.querySelector(selector);
    }
    function setHtml(nodeOrSelector, content) {
        var node;
        if (typeof nodeOrSelector === 'string') {
            node = qs(nodeOrSelector);
            if (node === null) {
                throw new Error('No node found for selector "'+nodeOrSelector+'"');
            }
        } else {
            node = nodeOrSelector;
        }
        node.innerHTML = content;
        return node;
    }

    return {
        createElement: createElement,
        appendRoot: appendRoot,
        append: append,
        remove: remove,
        setHTML: setHtml,
        setHtml: setHtml,
        findById: findById,
        nodeForId: nodeForId,
        getById: findById,
        qs: qs
    };
});<|endoftext|>


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

	var Fn        = window.Fn;
	var mount     = window.mount;

	var debug     = Fn.debug;
	var getPath   = Fn.getPath;
	var id        = Fn.id;
	var isDefined = Fn.isDefined;
	var overload  = Fn.overload;
	var nothing   = Fn.nothing;
	var noop      = Fn.noop;
	var curry     = Fn.curry;
	var apply     = Fn.apply;
	var get       = Fn.get;
	var set       = Fn.set;
	var each      = Fn.each;

	var assign = Object.assign;

	var settings = {
		rtokens: /(\{\[)\s*(.*?)(?:\s*\|\s*(.*?))?\s*(\]\})/g,

		mount: function mount(child) {
			if (!dom.attribute('data-fn', child)) { return; }

			var sparky = Sparky(child);

			return {
				path: '',
				token: 'Sparky',
				getValue: id,
				render: sparky.push
			};
		}
	};

	function resolveFn(node, fn, ctrl, instream) {
		// The ctrl list can be a space-separated string of ctrl paths,
		return typeof fn === 'string' ? makeFn(fn, ctrl, instream) :
			// a function,
			typeof fn === 'function' ? makeDistributeFn([fn], instream) :
			// an array of functions,
			typeof fn === 'object' ? makeDistributeFn(fn, instream) :
			// or defined in the data-fn attribute
			node.getAttribute && makeFn(node.getAttribute('data-fn'), ctrl, instream) ;
	}

	function makeDistributeFn(list, instream) {
		return function distributeFn(node) {
			// Distributor controller
			var l = list.length;
			var n = -1;
			var result;
			var flag = false;

			// TODO: This is exposes solely so that ctrl
			// 'observe-selected' can function in sound.io.
			// Really naff. Find a better way.
			this.ctrls = list;

			this.interrupt = function interrupt() {
				flag = true;
				return list.slice(n + 1);
			};

			while (++n < l) {
				// Call the list of ctrls, in order.
				result = list[n].call(this, node, instream);

				// Returning false interrupts the fn calls.
				if (flag) { return false; }

				// Returning an object sets that object to
				// be used as scope.
				if (result !== undefined) {
					instream = result.each ? result : Fn.of(result) ;
				}
			}

			return instream;
		};
	}

	function makeDistributeFnFromPaths(paths, ctrls, instream) {
		var list = [];
		var l = paths.length;
		var n = -1;
		var ctrl;

		while (++n < l) {
			ctrl = Fn.getPath(paths[n], ctrls);
			if (!ctrl) {
				throw new Error('Sparky: data-fn "' + paths[n] + '" not found in sparky.fn');
			}

			list.push(ctrl);
		}

		return makeDistributeFn(list, instream);
	}

	function makeFn(string, ctrls, instream) {
		if (!isDefined(string)) {
			return function() { return instream; };
		}
		var paths = string.trim().split(Sparky.rspaces);
		return makeDistributeFnFromPaths(paths, ctrls, instream);
	}

	function Sparky(node, data) {
		if (!Sparky.prototype.isPrototypeOf(this)) {
			return new Sparky(node);
		}

		var instream = Stream.of();
		var fns      = Sparky.fn;
		var dataFn   = dom.attribute('data-fn', node);
		var fn       = makeFn(dataFn, fns, instream);

		// If fn is to be called and a stream is returned, we use that.
		var outstream = fn.call(this, node);

		settings.transforms = Sparky.transforms;

		var update = mount(node, settings);

		if (instream === outstream) {
			this.push = instream.push;
		}

		outstream.each(update);
	}

	assign(Sparky.prototype, {
		push: noop
	});

	assign(Sparky, {
		mount:      mount,

		transforms: {},

		fn:         {}
	});

	Object.defineProperties(Sparky, {
		rtokens: {
			get: function() { return settings.rtokens; },
			enumerable: true,
			configurable: true
		}
	});

	window.Sparky = Sparky;

})(this);<commit_msg>Format<commit_after>(function(window) {
	"use strict";

	var Fn        = window.Fn;
	var mount     = window.mount;

	var debug     = Fn.debug;
	var getPath   = Fn.getPath;
	var id        = Fn.id;
	var isDefined = Fn.isDefined;
	var overload  = Fn.overload;
	var nothing   = Fn.nothing;
	var noop      = Fn.noop;
	var curry     = Fn.curry;
	var apply     = Fn.apply;
	var get       = Fn.get;
	var set       = Fn.set;
	var each      = Fn.each;

	var assign = Object.assign;

	var settings = {
		rtokens: /(\{\[)\s*(.*?)(?:\s*\|\s*(.*?))?\s*(\]\})/g,

		mount: function mount(child) {
			if (!dom.attribute('data-fn', child)) { return; }

			var sparky = Sparky(child);

			return {
				path: '',
				token: 'Sparky',
				getValue: id,
				render: sparky.push
			};
		}
	};

	function resolveFn(node, fn, ctrl, instream) {
		// The ctrl list can be a space-separated string of ctrl paths,
		return typeof fn === 'string' ? makeFn(fn, ctrl, instream) :
			// a function,
			typeof fn === 'function' ? makeDistributeFn([fn], instream) :
			// an array of functions,
			typeof fn === 'object' ? makeDistributeFn(fn, instream) :
			// or defined in the data-fn attribute
			node.getAttribute && makeFn(node.getAttribute('data-fn'), ctrl, instream) ;
	}

	function makeDistributeFn(list, instream) {
		return function distributeFn(node) {
			// Distributor controller
			var l = list.length;
			var n = -1;
			var result;
			var flag = false;

			// TODO: This is exposes solely so that ctrl
			// 'observe-selected' can function in sound.io.
			// Really naff. Find a better way.
			this.ctrls = list;

			this.interrupt = function interrupt() {
				flag = true;
				return list.slice(n + 1);
			};

			while (++n < l) {
				// Call the list of ctrls, in order.
				result = list[n].call(this, node, instream);

				// Returning false interrupts the fn calls.
				if (flag) { return false; }

				// Returning an object sets that object to
				// be used as scope.
				if (result !== undefined) {
					instream = result.each ? result : Fn.of(result) ;
				}
			}

			return instream;
		};
	}

	function makeDistributeFnFromPaths(paths, ctrls, instream) {
		var list = [];
		var l = paths.length;
		var n = -1;
		var ctrl;

		while (++n < l) {
			ctrl = Fn.getPath(paths[n], ctrls);
			if (!ctrl) {
				throw new Error('Sparky: data-fn "' + paths[n] + '" not found in sparky.fn');
			}

			list.push(ctrl);
		}

		return makeDistributeFn(list, instream);
	}

	function makeFn(string, ctrls, instream) {
		if (!isDefined(string)) {
			return function() { return instream; };
		}
		var paths = string.trim().split(Sparky.rspaces);
		return makeDistributeFnFromPaths(paths, ctrls, instream);
	}

	function Sparky(node, data) {
		if (!Sparky.prototype.isPrototypeOf(this)) {
			return new Sparky(node);
		}

		var instream = Stream.of();
		var fns      = Sparky.fn;
		var dataFn   = dom.attribute('data-fn', node);
		var fn       = makeFn(dataFn, fns, instream);

		// If fn is to be called and a stream is returned, we use that.
		var outstream = fn.call(this, node);

		if (instream === outstream) {
			this.push = instream.push;
		}

		settings.transforms = Sparky.transforms;
		var update = mount(node, settings);
		outstream.each(update);
	}

	assign(Sparky.prototype, {
		push: noop
	});

	assign(Sparky, {
		mount:      mount,

		transforms: {},

		fn:         {}
	});

	Object.defineProperties(Sparky, {
		rtokens: {
			get: function() { return settings.rtokens; },
			enumerable: true,
			configurable: true
		}
	});

	window.Sparky = Sparky;

})(this);<|endoftext|>


<commit_before>export default function(title, body) {
  return `<!doctype html>

  <link href='https://fonts.googleapis.com/css?family=Raleway:400,100,200,300,500,600,700,800,900|Open+Sans:400,600,300,300italic,400italic,600italic,700italic,800italic,800,700|Merriweather:400,300,700,300italic,900italic,700italic,400italic,900' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="public/app.css">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
  <title>${title}</title>

+

BGA Wrap Up: Jets at Texans

For all the changes the Jets made this offseason, yesterday's loss and the struggles over the past few weeks had a familiar feel to them.

However, if I told you at the start of the season that the Jets would be without Nick Mangold, Sheldon Richardson and Darrelle Revis during a November road game against a team leading their division, would you really have expected anything better than a competitive loss?

Right now, the Jets are victims of their own early-season success because the 4-1 start placed unrealistic expectations on the team. At the same time, they're not as bad as this 1-4 stretch would suggest either.

5 Comments

M

                Marcus

Post Comment

· · ·

B

              14 minutes ago

              Brendan

I think one of the more frustrating aspects of the Jets recent slump over the last five games is made more alarming by the recurring pattern behind it. Team gets off to a sluggish start, looks unprepared. At least one unit... it varies week to week... seems totally lost in space and the others cannot compensate for it.

That fragility, or lack of mental toughness, surfaces, and the team falls behind early.

Reply

A

                10 minutes ago

                a57se

You're a lying liar from liarville and I can't even read this without throwing up.

Reply

L

                  3 minutes ago

                  levi

That's a little rude, don't you think? We're here to talk about the Jets, ya'know.

Reply

T

                5 minutes ago

                tsjc68

Insert witty gif here.

Reply

M

              12 minutes ago

              Marcus

This is my incredibly insightful reply to your comment.

Reply

B

              15 minutes ago

              Bent

I hope you like my BGA!

Reply

`;
}
<commit_msg>Adding more comments<commit_after>export default function(title, body) {
  return `<!doctype html>

  <link href='https://fonts.googleapis.com/css?family=Raleway:400,100,200,300,500,600,700,800,900|Open+Sans:400,600,300,300italic,400italic,600italic,700italic,800italic,800,700|Merriweather:400,300,700,300italic,900italic,700italic,400italic,900' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="public/app.css">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
  <title>${title}</title>

+

BGA Wrap Up: Jets at Texans

For all the changes the Jets made this offseason, yesterday's loss and the struggles over the past few weeks had a familiar feel to them.

However, if I told you at the start of the season that the Jets would be without Nick Mangold, Sheldon Richardson and Darrelle Revis during a November road game against a team leading their division, would you really have expected anything better than a competitive loss?

Right now, the Jets are victims of their own early-season success because the 4-1 start placed unrealistic expectations on the team. At the same time, they're not as bad as this 1-4 stretch would suggest either.

5 Comments

M

                Marcus

Post Comment

· · ·

B

              14 minutes ago

              Brendan

I think one of the more frustrating aspects of the Jets recent slump over the last five games is made more alarming by the recurring pattern behind it. Team gets off to a sluggish start, looks unprepared. At least one unit... it varies week to week... seems totally lost in space and the others cannot compensate for it.

That fragility, or lack of mental toughness, surfaces, and the team falls behind early.

Reply

A

                10 minutes ago

                a57se

You're a lying liar from liarville and I can't even read this without throwing up.

Reply

L

                  3 minutes ago

                  levi

That's a little rude, don't you think? We're here to talk about the Jets, ya'know.

Reply

B

                    1 minute ago

                    Brendan

Eh, it's cool. Sunday's game made me puke too.

Reply

A

                  2 minutes ago

                  a57se

Fair enough. Fitzpatrick is the best QB of all time.

Reply

T

                5 minutes ago

                tsjc68

Insert witty gif here.

Reply

M

              12 minutes ago

              Marcus

This is my incredibly insightful reply to your comment.

Reply

B

              15 minutes ago

              Bent

I hope you like my BGA!

Reply

`;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * This script applies SKU when it's missing equal to current name of the upload
 */

/* eslint-disable no-console */

const argv = require('yargs')
  .describe('user', 'user to scan')
  .describe('confirm', 'whether to perform update or not, defaults to dry run')
  .boolean(['confirm'])
  .demand(['user'])
  .help('h')
  .argv;

// Deps
const Promise = require('bluebird');
const Files = require('../lib/index');
const AMQPTransport = require('ms-amqp-transport');
const omit = require('lodash/omit');
const merge = require('lodash/merge');
const configOverride = require('ms-conf').get('/');

// Configuration
const config = merge({}, Files.defaultOpts, configOverride);
const amqpConfig = omit(config.amqp.transport, ['queue', 'listen', 'neck', 'onComplete']);
const prefix = config.router.routes.prefix;
const iterator = {
  offset: 0,
  limit: 20,
  owner: argv.user,
  fitler: {
    alias: {
      isempty: true,
    },
  },
  without: ['files'],
};

// App level code
const getTransport = () => {
  console.info('establishing connection to amqp with %j', amqpConfig);
  return AMQPTransport.connect(amqpConfig).disposer(amqp => amqp.close());
};

// perform update
const performUpdate = (amqp, file) => {
  const { name, uploadId } = file;

  if (argv.confirm !== true) {
    console.info('[dry-run] set alias for %s to %s', uploadId, name);
    return null;
  }

  return amqp
    .publishAndWait(`${prefix}.update`, { uploadId, username: argv.user, meta: { alias: name } }, { timeout: 5000 })
    .then(() => {
      console.log('set alias for %s to %s', uploadId, name);
      return null;
    })
    .catch((e) => {
      console.warn('[warn] failed to set alias to %s for %s: %s', name, uploadId, e.message);
    });
};

// performs listing of files, which contain no SKU
const listAndUpdate = (amqp) => {
  console.info('requesting %d files on the page %d', iterator.limit, (iterator.offset / iterator.limit) + 1);

  return amqp
    .publishAndWait(`${prefix}.list`, iterator, { timeout: 5000 })
    .tap((data) => {
      if (iterator.offset === 0) {
        console.info('pages found: %d', data.pages);
      }
    })
    .tap(data => Promise.map(data.files, file => performUpdate(amqp, file)))
    .tap((data) => {
      // recursively work on the next page
      if (data.page < data.pages) {
        iterator.offset = data.cursor;
        return listAndUpdate(amqp);
      }

      return null;
    });
};

Promise.using(getTransport(), listAndUpdate);
<commit_msg>fix: typo<commit_after>#!/usr/bin/env node

/**
 * This script applies SKU when it's missing equal to current name of the upload
 */

/* eslint-disable no-console */

const argv = require('yargs')
  .describe('user', 'user to scan')
  .describe('confirm', 'whether to perform update or not, defaults to dry run')
  .boolean(['confirm'])
  .demand(['user'])
  .help('h')
  .argv;

// Deps
const Promise = require('bluebird');
const Files = require('../lib/index');
const AMQPTransport = require('ms-amqp-transport');
const omit = require('lodash/omit');
const merge = require('lodash/merge');
const configOverride = require('ms-conf').get('/');

// Configuration
const config = merge({}, Files.defaultOpts, configOverride);
const amqpConfig = omit(config.amqp.transport, ['queue', 'listen', 'neck', 'onComplete']);
const prefix = config.router.routes.prefix;
const iterator = {
  offset: 0,
  limit: 20,
  owner: argv.user,
  filter: {
    alias: {
      isempty: true,
    },
  },
  without: ['files'],
};

// App level code
const getTransport = () => {
  console.info('establishing connection to amqp with %j', amqpConfig);
  return AMQPTransport.connect(amqpConfig).disposer(amqp => amqp.close());
};

// perform update
const performUpdate = (amqp, file) => {
  const { name, uploadId } = file;

  if (argv.confirm !== true) {
    console.info('[dry-run] set alias for %s to %s', uploadId, name);
    return null;
  }

  return amqp
    .publishAndWait(`${prefix}.update`, { uploadId, username: argv.user, meta: { alias: name } }, { timeout: 5000 })
    .then(() => {
      console.log('set alias for %s to %s', uploadId, name);
      return null;
    })
    .catch((e) => {
      console.warn('[warn] failed to set alias to %s for %s: %s', name, uploadId, e.message);
    });
};

// performs listing of files, which contain no SKU
const listAndUpdate = (amqp) => {
  console.info('requesting %d files on the page %d', iterator.limit, (iterator.offset / iterator.limit) + 1);

  return amqp
    .publishAndWait(`${prefix}.list`, iterator, { timeout: 5000 })
    .tap((data) => {
      if (iterator.offset === 0) {
        console.info('pages found: %d', data.pages);
      }
    })
    .tap(data => Promise.map(data.files, file => performUpdate(amqp, file)))
    .tap((data) => {
      // recursively work on the next page
      if (data.page < data.pages) {
        iterator.offset = data.cursor;
        return listAndUpdate(amqp);
      }

      return null;
    });
};

Promise.using(getTransport(), listAndUpdate);
<|endoftext|>


<commit_before>$(function(){

    $(window).on("hashchange", function(){
      location.reload();
    });

    var ua = navigator.userAgent;

    // 板名取得
    var ds = milkcocoa.dataStore('fusen');
    var room = "";
    if(location.hash) room = location.hash.slice(1);
    if(room != "") ds = ds.child(room);

    var curClr = "one";
    var canvas = $("#canvas");
    var fusenBuilder = new FusenBuilder(canvas, ds);

    var device = "pc";
    if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0) {
        device = "mobile";
    }else{
        device = "pc";
    }

    // 板タイトルについて
    $("#title").val(room);

    function pad (num) { return ("0" + num).substr(-2,2) };
    var today = {
      m: pad( (new Date()).getMonth()+1 ),
      d: pad( (new Date()).getDate() )
    }

    $("#title").attr("placeholder", "例) <your name>_"+today.m+today.d+"_todo")

    // titleの場所で板移動
    $("#title").keypress(function(e){
      if(e.which == 13){
        location.hash = "#"+$(this).val();
      }
    });

    /*
    * 同時接続数を取得するロジック
    */
    var ds_connection = milkcocoa.dataStore("connection_count").child(room);

    // milkcocoaインスタンス生成後、コネクションデータを送信し、その後レンダリングやリスナー設置
    ds_connection.push({}, function(){
      // コネクション数のレンダリングと、コネクション増加時のカウントアップ
      ds_connection.stream().size(999).next(function(err, data) {
        // 堆積したコネクションを削除
        var limit = 1000*45;
        data = data.filter(function(datum){
          var isFresh = (datum.timestamp > data[data.length-1].timestamp - limit);
          if(!isFresh) ds_connection.remove(datum.id);
          return isFresh;
        });

        // 部屋とコネクションを記録
        var _room;
        if(room != "") _room = room;
        else _room = "__root__";

        var ds_room = milkcocoa.dataStore("rooms");
          ds_room.get(_room, function(err, room_data){
            if(err == "not found") room_data = { value : { access: 0 }  };
            room_data.value.access++;
            ds_room.set(_room, {connection: data.length, access: room_data.value.access, updated_at: Date.now()},
              function(err, datum){
                // 成功時
              },
              function(err, datum){
                // セキュリティや制限のエラー
                toast.error("セキュリティおよび負荷の理由で接続に失敗しました");
              }
            );
          });

        // コネクションを表示
        var pushed_count = 0;
        $("title").text("Wowoo("+data.length+")");

        // 他者が接続したらリアルタイム更新
        ds_connection.on("push", function(err, datum){
          pushed_count++;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });

        // 他者が離脱したらリアルタイム更新
        ds_connection.on("remove", function(err, datum){
          pushed_count--;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });
      });

      // ユーザーのアクティブ取得
      var timeout_ids = [];
      ds_connection.stream().size(999).next(function(err, data) {
        var first = data.shift();
        var oldest_count = (first) ? first : {id:""};

        // 常に最新のtimeoutだけが有効になっている
        $(document).on("keypress mousemove click", function(e){
          e.stopPropagation();
          var past_id = timeout_ids.shift();
          clearTimeout(past_id);
          var current_id = setTimeout(function(){
            disconnect_current_connection();
          }, 30000);
          timeout_ids.push(current_id);
        });

        // 画面から離れる際にカウントダウン
        $(window).on("beforeunload", function(e){
          disconnect_current_connection();
        });

        function disconnect_current_connection(){ ds_connection.remove(oldest_count.id); }
      });

    });
    // ここまで

    // select color
    $(".p-colorlist__item").click(function(e){
        curClr = $(this).attr("id");
        $(".p-colorlist__item").each(function(){
            $(this).removeClass("is-active");
        });
        $(this).addClass("is-active");
        e.stopPropagation();
    });

    ds.stream().size(999).sort('desc').next(function(err, datas) {
        var fusens = [];
        for(var i=0;i < datas.length;i++) {
            var fusen = fusenBuilder.render(datas[i].id, datas[i].value.x, datas[i].value.y, datas[i].value.text, datas[i].value.color);
            fusens.push(fusen);
        }

        // 付箋設置後に、スマホならズーム
        //if(device == "mobile") fusen_util.zoomIn(2.0);
        // ズームすると確かに使いやすいが、移動や投稿の照準が定まらない

        for(var i=0;i < fusens.length;i++) {
          var fusen = fusens[i];
		      fusen.setAllListeners();
        }
    });
    ds.on("push", function(pushed) {
        fusenBuilder.renderWithListener(pushed.id, pushed.value.x, pushed.value.y, pushed.value.text, pushed.value.color);
    });

    ds.on("set", function(setted) {
        var fusen = fusenBuilder.getFusen(setted.id);
        fusen.setPos(setted.value.x, setted.value.y);
        fusen.setText(setted.value.text);
    });

    ds.on("remove", function(_removed) {
        var removed = _removed;
        fusenBuilder.getFusen(removed.id).removeSelf();
    });

    canvas.click(function(e) {
        var $self = $(this);
        e.stopPropagation();

        var offset_x = e.offsetX;
        var offset_y = e.offsetY;
        var page_x = e.pageX;
        var page_y = e.pageY;

        generateBalloon(function(text){
          // zoom時の縮尺調整が必要
  				var zoom = ($('.body-zoom').css('zoom')) ? $('.body-zoom').css('zoom') : 1;
  				var factor = (1 / zoom);

          // Originalデータを保存しつつ、zoom合わせて縮小したデータを表示する
          ds.push({
              x : page_x*factor,
              y : page_y*factor,
              text : text,
              color : curClr
          }, function(e){
            if(device == "pc") fusen_util.removeBalloon();
          });
        });

        function generateBalloon(cb){
          var text = "";
          if(device == "mobile"){
            text = prompt("メモを入力してください");
            if(!text) {
              toastr.error("Blank text🐶");
              return;
            }
            cb(text);
          } else {
            $(".posting-balloon").remove();
            $self.append('
<input type="text" />
');

            var $input = $(".posting-balloon > input");
            $input.focus();
            $input.off("keypress").on("keypress", function(e){
              if(e.which === 13){
                text = $(this).val();
                if(!text) {
                  toastr.error("Blank text🐶");
                  return;
                }
                cb(text);
              }
            });

            // 吹き出しを消す
            fusen_util.removeBalloonOnESC()
          }
        }
    });

    $("#replay").click(function(e){
      fusenBuilder.replay(function(fusensByOrder){
        setInterval(function(){
          var fusen = fusensByOrder.shift();
          fusenBuilder.renderWithListener(fusen.id, fusen.pos.x, fusen.pos.y, fusen.text, fusen.color);
        }, 750);
      });
    });

    window.fusen_util = {
        getDevice : function() {
            return device;
        },
        htmlEscape : function(s) {
            s=s.replace(/&/g,'&');
            s=s.replace(/>/g,'>');
            s=s.replace(/</g,'<');
            return s;
        },
        copy : function (text){
          // clipboard.jsを使う
          // promptを使わない
          /*
          document.addEventListener('copy', function(e) {
            e.preventDefault();
            if (e.clipboardData) {
              e.preventDefault();
              e.clipboardData.setData('text/plain', "Hello");
            }
            if (window.clipboardData) {
              e.returnValue = false;
              window.clipboardData.setData('text/plain', "World");
            }
          }, false);

          */
          $(document).trigger("copy");
        },
        userAgent : function(){
          return window.navigator.userAgent.toLowerCase();
        },
    		linknize : function (escapedText) {
    		  // とりあえず高階関数で実装
          var short_url_reg = /^(?!https?:\/\/)([A-Za-z0-9][A-Za-z0-9\-]{1,61}[A-Za-z0-9]\.)+[A-Za-z]+\/?[A-Za-z0-9\-_]*/;
    			var http_regexp = /https?:\/\/.+(\ |$)/;

          // スペース区切りでチェックしていく
    			var linkedText = escapedText.split(" ").map(function(_t){
            var short_url_matched = escapedText.match(short_url_reg);
            var short_url = (short_url_matched != null) ? short_url_matched[0] : null;
            if(short_url != null){
              _t = _t.replace(short_url_reg, "http://"+short_url);
            }

    				var found = _t.match(http_regexp);
    				if (found) {
    					var url = found[0];
    					var short_url = url.split(/\/\//)[url.split(/\/\//).length - 1];
    					var _t = _t.replace(http_regexp, ""+short_url+"" ) ;
    				}
    				return _t;
    			}).join(" ");

    			linkedText = hashnize(linkedText);
    			return linkedText;

    			function hashnize(linkedText) {
    				// hashをリンク化
    				var hash_regexp = /^#.+/;
    				var hashedText = linkedText.split(" ").map(function(_t){
    					if ( _t.match(hash_regexp) ) {
    						var url = location.href + _t;
    						_t = _t.replace(hash_regexp, ""+_t+"");
    					}
    					return _t;
    				}).join(" ");
    				return hashedText;
    			}
    		},
        removeBalloonOnESC : function (){
          $(document).off("keyup").on("keyup", function(e) {
             if (e.keyCode == 27) fusen_util.removeBalloon();
          });
        },
        removeBalloon : function (){
          $(".posting-balloon").remove();
        },
        zoomIn : function (zoomLev) {
            if (zoomLev > 1) {
                if (typeof (document.body.style.zoom) != "undefined") {
                    //$(document.body).css('zoom', zoomLev);
                    $('body').addClass("body-zoom");
                }else {
                    // Mozilla doesn't support zoom, use -moz-transform to scale and compensate for lost width
                    $('#divWrap').css({
                        "-moz-transform": 'scale(" + zoomLev + ")',
                        width: $(window).width() / zoomLev
                    });
                }
            }
        }
    }

});
<commit_msg>t.co activate<commit_after>$(function(){

    $(window).on("hashchange", function(){
      location.reload();
    });

    var ua = navigator.userAgent;

    // 板名取得
    var ds = milkcocoa.dataStore('fusen');
    var room = "";
    if(location.hash) room = location.hash.slice(1);
    if(room != "") ds = ds.child(room);

    var curClr = "one";
    var canvas = $("#canvas");
    var fusenBuilder = new FusenBuilder(canvas, ds);

    var device = "pc";
    if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0) {
        device = "mobile";
    }else{
        device = "pc";
    }

    // 板タイトルについて
    $("#title").val(room);

    function pad (num) { return ("0" + num).substr(-2,2) };
    var today = {
      m: pad( (new Date()).getMonth()+1 ),
      d: pad( (new Date()).getDate() )
    }

    $("#title").attr("placeholder", "例) <your name>_"+today.m+today.d+"_todo")

    // titleの場所で板移動
    $("#title").keypress(function(e){
      if(e.which == 13){
        location.hash = "#"+$(this).val();
      }
    });

    /*
    * 同時接続数を取得するロジック
    */
    var ds_connection = milkcocoa.dataStore("connection_count").child(room);

    // milkcocoaインスタンス生成後、コネクションデータを送信し、その後レンダリングやリスナー設置
    ds_connection.push({}, function(){
      // コネクション数のレンダリングと、コネクション増加時のカウントアップ
      ds_connection.stream().size(999).next(function(err, data) {
        // 堆積したコネクションを削除
        var limit = 1000*45;
        data = data.filter(function(datum){
          var isFresh = (datum.timestamp > data[data.length-1].timestamp - limit);
          if(!isFresh) ds_connection.remove(datum.id);
          return isFresh;
        });

        // 部屋とコネクションを記録
        var _room;
        if(room != "") _room = room;
        else _room = "__root__";

        var ds_room = milkcocoa.dataStore("rooms");
          ds_room.get(_room, function(err, room_data){
            if(err == "not found") room_data = { value : { access: 0 }  };
            room_data.value.access++;
            ds_room.set(_room, {connection: data.length, access: room_data.value.access, updated_at: Date.now()},
              function(err, datum){
                // 成功時
              },
              function(err, datum){
                // セキュリティや制限のエラー
                toast.error("セキュリティおよび負荷の理由で接続に失敗しました");
              }
            );
          });

        // コネクションを表示
        var pushed_count = 0;
        $("title").text("Wowoo("+data.length+")");

        // 他者が接続したらリアルタイム更新
        ds_connection.on("push", function(err, datum){
          pushed_count++;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });

        // 他者が離脱したらリアルタイム更新
        ds_connection.on("remove", function(err, datum){
          pushed_count--;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });
      });

      // ユーザーのアクティブ取得
      var timeout_ids = [];
      ds_connection.stream().size(999).next(function(err, data) {
        var first = data.shift();
        var oldest_count = (first) ? first : {id:""};

        // 常に最新のtimeoutだけが有効になっている
        $(document).on("keypress mousemove click", function(e){
          e.stopPropagation();
          var past_id = timeout_ids.shift();
          clearTimeout(past_id);
          var current_id = setTimeout(function(){
            disconnect_current_connection();
          }, 30000);
          timeout_ids.push(current_id);
        });

        // 画面から離れる際にカウントダウン
        $(window).on("beforeunload", function(e){
          disconnect_current_connection();
        });

        function disconnect_current_connection(){ ds_connection.remove(oldest_count.id); }
      });

    });
    // ここまで

    // select color
    $(".p-colorlist__item").click(function(e){
        curClr = $(this).attr("id");
        $(".p-colorlist__item").each(function(){
            $(this).removeClass("is-active");
        });
        $(this).addClass("is-active");
        e.stopPropagation();
    });

    ds.stream().size(999).sort('desc').next(function(err, datas) {
        var fusens = [];
        for(var i=0;i < datas.length;i++) {
            var fusen = fusenBuilder.render(datas[i].id, datas[i].value.x, datas[i].value.y, datas[i].value.text, datas[i].value.color);
            fusens.push(fusen);
        }

        // 付箋設置後に、スマホならズーム
        //if(device == "mobile") fusen_util.zoomIn(2.0);
        // ズームすると確かに使いやすいが、移動や投稿の照準が定まらない

        for(var i=0;i < fusens.length;i++) {
          var fusen = fusens[i];
		      fusen.setAllListeners();
        }
    });
    ds.on("push", function(pushed) {
        fusenBuilder.renderWithListener(pushed.id, pushed.value.x, pushed.value.y, pushed.value.text, pushed.value.color);
    });

    ds.on("set", function(setted) {
        var fusen = fusenBuilder.getFusen(setted.id);
        fusen.setPos(setted.value.x, setted.value.y);
        fusen.setText(setted.value.text);
    });

    ds.on("remove", function(_removed) {
        var removed = _removed;
        fusenBuilder.getFusen(removed.id).removeSelf();
    });

    canvas.click(function(e) {
        var $self = $(this);
        e.stopPropagation();

        var offset_x = e.offsetX;
        var offset_y = e.offsetY;
        var page_x = e.pageX;
        var page_y = e.pageY;

        generateBalloon(function(text){
          // zoom時の縮尺調整が必要
  				var zoom = ($('.body-zoom').css('zoom')) ? $('.body-zoom').css('zoom') : 1;
  				var factor = (1 / zoom);

          // Originalデータを保存しつつ、zoom合わせて縮小したデータを表示する
          ds.push({
              x : page_x*factor,
              y : page_y*factor,
              text : text,
              color : curClr
          }, function(e){
            if(device == "pc") fusen_util.removeBalloon();
          });
        });

        function generateBalloon(cb){
          var text = "";
          if(device == "mobile"){
            text = prompt("メモを入力してください");
            if(!text) {
              toastr.error("Blank text🐶");
              return;
            }
            cb(text);
          } else {
            $(".posting-balloon").remove();
            $self.append('
<input type="text" />
');

            var $input = $(".posting-balloon > input");
            $input.focus();
            $input.off("keypress").on("keypress", function(e){
              if(e.which === 13){
                text = $(this).val();
                if(!text) {
                  toastr.error("Blank text🐶");
                  return;
                }
                cb(text);
              }
            });

            // 吹き出しを消す
            fusen_util.removeBalloonOnESC()
          }
        }
    });

    $("#replay").click(function(e){
      fusenBuilder.replay(function(fusensByOrder){
        setInterval(function(){
          var fusen = fusensByOrder.shift();
          fusenBuilder.renderWithListener(fusen.id, fusen.pos.x, fusen.pos.y, fusen.text, fusen.color);
        }, 750);
      });
    });

    window.fusen_util = {
        getDevice : function() {
            return device;
        },
        htmlEscape : function(s) {
            s=s.replace(/&/g,'&');
            s=s.replace(/>/g,'>');
            s=s.replace(/</g,'<');
            return s;
        },
        copy : function (text){
          // clipboard.jsを使う
          // promptを使わない
          /*
          document.addEventListener('copy', function(e) {
            e.preventDefault();
            if (e.clipboardData) {
              e.preventDefault();
              e.clipboardData.setData('text/plain', "Hello");
            }
            if (window.clipboardData) {
              e.returnValue = false;
              window.clipboardData.setData('text/plain', "World");
            }
          }, false);

          */
          $(document).trigger("copy");
        },
        userAgent : function(){
          return window.navigator.userAgent.toLowerCase();
        },
    		linknize : function (escapedText) {
    		  // とりあえず高階関数で実装
          var short_url_reg = /^(?!https?:\/\/)([A-Za-z0-9\-]{0,61}[A-Za-z0-9]\.)+[A-Za-z]+\/?[A-Za-z0-9\-_]*/;
    			var http_regexp = /https?:\/\/.+(\ |$)/;

          // スペース区切りでチェックしていく
    			var linkedText = escapedText.split(" ").map(function(_t){
            var short_url_matched = escapedText.match(short_url_reg);
            var short_url = (short_url_matched != null) ? short_url_matched[0] : null;
            if(short_url != null){
              _t = _t.replace(short_url_reg, "http://"+short_url);
            }

    				var found = _t.match(http_regexp);
    				if (found) {
    					var url = found[0];
    					var short_url = url.split(/\/\//)[url.split(/\/\//).length - 1];
    					var _t = _t.replace(http_regexp, ""+short_url+"" ) ;
    				}
    				return _t;
    			}).join(" ");

    			linkedText = hashnize(linkedText);
    			return linkedText;

    			function hashnize(linkedText) {
    				// hashをリンク化
    				var hash_regexp = /^#.+/;
    				var hashedText = linkedText.split(" ").map(function(_t){
    					if ( _t.match(hash_regexp) ) {
    						var url = location.href + _t;
    						_t = _t.replace(hash_regexp, ""+_t+"");
    					}
    					return _t;
    				}).join(" ");
    				return hashedText;
    			}
    		},
        removeBalloonOnESC : function (){
          $(document).off("keyup").on("keyup", function(e) {
             if (e.keyCode == 27) fusen_util.removeBalloon();
          });
        },
        removeBalloon : function (){
          $(".posting-balloon").remove();
        },
        zoomIn : function (zoomLev) {
            if (zoomLev > 1) {
                if (typeof (document.body.style.zoom) != "undefined") {
                    //$(document.body).css('zoom', zoomLev);
                    $('body').addClass("body-zoom");
                }else {
                    // Mozilla doesn't support zoom, use -moz-transform to scale and compensate for lost width
                    $('#divWrap').css({
                        "-moz-transform": 'scale(" + zoomLev + ")',
                        width: $(window).width() / zoomLev
                    });
                }
            }
        }
    }

});
<|endoftext|>