<commit_before>function setup() {
    createCanvas(displayWidth, displayHeight);

    word = 'SEVENTYFIVE'

    words = [
        'UNITED STATES',
        'MEXICO',
        'BRAZIL',
        'IRAN',
        'ISLAMIC REPUBLIC',
        'TURKEY',
        'EGYPT',
        'NIGERIA',
        'CONGO',
        // 'DEMOCRATIC REPUBLIC',
        'ETHIOPIA',
        'TANZANIA',
        'CHINA',
        'PAKISTAN',
        'PHILLIPPINES',
        'VIETNAM',
        'INDONESIA',
        'THAILAND',
        'MYANMAR',
        'BANGLADESH',
        // 'RUSSIAN FEDERATION'
        'RUSSIA',
        'RURAL',
        'LOW INCOME',
        'ELDERLY',
        'ILLITERATE',
        'FEMALE',
        'INCENTIVES',
        'AFFORDABILITY',
        'USER CAPABILITY',
        'INFRASTRUCTURE'
    ];

    letterWordRepeat = 2;

    letterCount = 0;
    wordCount = 0;

    wordDuration = 75;

    titleDuration = 12500;
    titleLetterDuration = 500;
    captionDuration = 1000;

    currentLetter = '';
    currentWord = '';

    ended = false;

    titleHeight = width * .125
    titleBottomMargin = titleHeight * .1;

    captionHeight = max(width * .015, 14)
    captionLineHeight = captionHeight + captionHeight * .5;

    textFont('Helvetica Neue, Helvetica, Arial, sans-serif')
    textStyle(BOLD)
    textSize(titleHeight)

    noStroke();

    backgroundColor = 255;

    setupSequence();
}

function setupSequence() {
    MOTION.removeAll();

    titleLetters = []

    titleLettersSequence = new MOTION.Sequence();

    titleLettersSequence.add(new MOTION.Tween(captionDuration)
        .add('captionColor', [0, 255])
        .add('titleColor', [0, 255]))

    titleLettersSequence.add(new MOTION(titleDuration))

    titleLettersSequence
        .onStart(function() {
            backgroundTween = new MOTION.Tween('backgroundColor', [0, 255], this.duration()).play()
        }).onEnd(function() {
            ended = false;
            lettersSequence.play()
        })

    letters = [];
    letters.offset = textWidth(word) / 2;

    letters.x = width / 2 - letters.offset;
    letters.y = height / 2;

    for (var i = 0; i < word.length; i++) {
        var letter = word.charAt(i);
        var letterWords = [];

        for (var j in words)
            for (var k in words[j])
                if (words[j][k] === letter)
                    for (var l = 0; l < letterWordRepeat; l++)
                        letterWords.push({
                            word: words[j],
                            index: k,
                            offset: textWidth(words[j].substring(0, k))
                        })

        letters.push({
            letter: letter,
            offset: textWidth(word.substring(0, i)),
            words: shuffle(letterWords)
        })
    }

    lettersSequence = new MOTION.Sequence();

    for (var i in letters) {
        for (var j in letters[i].words) {
            var m = new MOTION(wordDuration).onStart(function() {
                currentLetter = this.letter;
                currentWord = this.word;
            });
            m.letter = letters[i];
            m.word = letters[i].words[j];

            lettersSequence.add(m)
        }
    }

    lettersSequence
        .onStart(function() {
            backgroundTween = new MOTION.Tween('backgroundColor', [255, 0], this.duration()).play()
        })
        .onEnd(function() {
            ended = true;
            titleLettersSequence.play();
        })
        .play()

    // titleLettersSequence.play().onEnd(function() {});
}

function draw() {
    MOTION.update(millis());

    background(backgroundColor);

    if (!ended) {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(lettersSequence.position() * 255)
        text(currentWord.word, letters.x + currentLetter.offset - currentWord.offset, letters.y)

        fill(255)
        text(currentLetter.letter, letters.x + currentLetter.offset, letters.y)
    } else {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(word, letters.x, letters.y)

        textSize(captionHeight)
        textAlign(CENTER);
        fill(captionColor)
        text('percent of the 4.4 billion people offline worldwide are in 20 countries', width / 2, letters.y + titleBottomMargin + captionLineHeight)
        text('including the U.S., which has 50 million; 1 out of 6 people...', width / 2, letters.y + titleBottomMargin + captionLineHeight * 2)
    }
}

function pause() {
    lettersSequence.pause();
    backgroundTween.pause();
}

function resume() {
    if (!lettersSequence.isPlaying()) {
        lettersSequence.resume();
        backgroundTween.resume();
    }
}

function mouseMoved() {
    if (ended) return false;

    if (e.clientY > height / 2 - titleHeight && e.clientY < height / 2)
        pause();
    else
        resume();
}

function touchStarted() {
    pause();
}

function touchEnded() {
    resume();
}

function shuffle(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}
<commit_msg>changed canvas sizing<commit_after>function setup() {
    createCanvas(windowWidth, windowHeight);

    word = 'SEVENTYFIVE'

    words = [
        'UNITED STATES',
        'MEXICO',
        'BRAZIL',
        'IRAN',
        'ISLAMIC REPUBLIC',
        'TURKEY',
        'EGYPT',
        'NIGERIA',
        'CONGO',
        // 'DEMOCRATIC REPUBLIC',
        'ETHIOPIA',
        'TANZANIA',
        'CHINA',
        'PAKISTAN',
        'PHILLIPPINES',
        'VIETNAM',
        'INDONESIA',
        'THAILAND',
        'MYANMAR',
        'BANGLADESH',
        // 'RUSSIAN FEDERATION'
        'RUSSIA',
        'RURAL',
        'LOW INCOME',
        'ELDERLY',
        'ILLITERATE',
        'FEMALE',
        'INCENTIVES',
        'AFFORDABILITY',
        'USER CAPABILITY',
        'INFRASTRUCTURE'
    ];

    letterWordRepeat = 2;

    letterCount = 0;
    wordCount = 0;

    wordDuration = 75;

    titleDuration = 12500;
    titleLetterDuration = 500;
    captionDuration = 1000;

    currentLetter = '';
    currentWord = '';

    ended = false;

    titleHeight = width * .125
    titleBottomMargin = titleHeight * .1;

    captionHeight = max(width * .015, 14)
    captionLineHeight = captionHeight + captionHeight * .5;

    textFont('Helvetica Neue, Helvetica, Arial, sans-serif')
    textStyle(BOLD)
    textSize(titleHeight)

    noStroke();

    backgroundColor = 255;

    setupSequence();
}

function setupSequence() {
    MOTION.removeAll();

    titleLetters = []

    titleLettersSequence = new MOTION.Sequence();

    titleLettersSequence.add(new MOTION.Tween(captionDuration)
        .add('captionColor', [0, 255])
        .add('titleColor', [0, 255]))

    titleLettersSequence.add(new MOTION(titleDuration))

    titleLettersSequence
        .onStart(function() {
            backgroundTween = new MOTION.Tween('backgroundColor', [0, 255], this.duration()).play()
        }).onEnd(function() {
            ended = false;
            lettersSequence.play()
        })

    letters = [];
    letters.offset = textWidth(word) / 2;

    letters.x = width / 2 - letters.offset;
    letters.y = height / 2;

    for (var i = 0; i < word.length; i++) {
        var letter = word.charAt(i);
        var letterWords = [];

        for (var j in words)
            for (var k in words[j])
                if (words[j][k] === letter)
                    for (var l = 0; l < letterWordRepeat; l++)
                        letterWords.push({
                            word: words[j],
                            index: k,
                            offset: textWidth(words[j].substring(0, k))
                        })

        letters.push({
            letter: letter,
            offset: textWidth(word.substring(0, i)),
            words: shuffle(letterWords)
        })
    }

    lettersSequence = new MOTION.Sequence();

    for (var i in letters) {
        for (var j in letters[i].words) {
            var m = new MOTION(wordDuration).onStart(function() {
                currentLetter = this.letter;
                currentWord = this.word;
            });
            m.letter = letters[i];
            m.word = letters[i].words[j];

            lettersSequence.add(m)
        }
    }

    lettersSequence
        .onStart(function() {
            backgroundTween = new MOTION.Tween('backgroundColor', [255, 0], this.duration()).play()
        })
        .onEnd(function() {
            ended = true;
            titleLettersSequence.play();
        })
        .play()

    // titleLettersSequence.play().onEnd(function() {});
}

function draw() {
    MOTION.update(millis());

    background(backgroundColor);

    if (!ended) {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(lettersSequence.position() * 255)
        text(currentWord.word, letters.x + currentLetter.offset - currentWord.offset, letters.y)

        fill(255)
        text(currentLetter.letter, letters.x + currentLetter.offset, letters.y)
    } else {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(word, letters.x, letters.y)

        textSize(captionHeight)
        textAlign(CENTER);
        fill(captionColor)
        text('percent of the 4.4 billion people offline worldwide are in 20 countries', width / 2, letters.y + titleBottomMargin + captionLineHeight)
        text('including the U.S., which has 50 million; 1 out of 6 people...', width / 2, letters.y + titleBottomMargin + captionLineHeight * 2)
    }
}

function pause() {
    lettersSequence.pause();
    backgroundTween.pause();
}

function resume() {
    if (!lettersSequence.isPlaying()) {
        lettersSequence.resume();
        backgroundTween.resume();
    }
}

function mouseMoved() {
    if (ended) return false;

    if (e.clientY > height / 2 - titleHeight && e.clientY < height / 2)
        pause();
    else
        resume();
}

function touchStarted() {
    pause();
}

function touchEnded() {
    resume();
}

function shuffle(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}
<|endoftext|>


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

var igvxhr = (function (igvxhr) {

    // Compression types
    const NONE = 0;
    const GZIP = 1;
    const BGZF = 2;

    igvxhr.isReachable = function (url, continuation) {

        var request = new XMLHttpRequest();

        request.open("HEAD", url, false);

        request.onload = function (event) {

            if (0 === request.status) {
                console.log("igvxhr.isReachable - onload - failure - status " + request.status);
                continuation(false, request.status);
            }
            else if (request.status >= 200 && request.status <= 300) {
                console.log("igvxhr.isReachable - onload - success - status " + request.status);
                continuation(true, request.status);
            }
            else {
                console.log("igvxhr.isReachable - onload - failure - status " + request.status);
                continuation(false, request.status);
            }

        };

        request.onerror = function (event) {
            console.log("igvxhr.isReachable - onerror - status " + request.status);
            continuation(false, request.status);
        };

        request.ontimeout = function (event) {
            console.log("igvxhr.isReachable - ontimeout - status " + request.status);
            continuation(false, request.status);
        };

        request.onabort = function (event) {
            console.log("igvxhr.isReachable - onabort - status " + request.status);
            continuation(false, request.status);
        };

        console.log("igvxhr.isReachable - send - before");
        request.send(null);
        console.log("igvxhr.isReachable - send - after");

    };

    igvxhr.loadArrayBuffer = function (url, options) {
        options.responseType = "arraybuffer";
        igvxhr.load(url, options);
    }

    igvxhr.loadJson = function (url, options) {

        var success = options.success;

        options.contentType = "application/json";
        options.success = function (result) {
            if (result) {
                success(JSON.parse(result));
            }
            else {
                success(null);
            }
        };

        igvxhr.load(url, options);

    }

    /**
     * Load a "raw" string.
     */
    igvxhr.loadString = function (url, options) {

        var success = options.success,
            compression, result;

        if (options.bgz) {
            compression = BGZF;
        }
        else if (url.endsWith(".gz")) {

            compression = GZIP;
        }
        else {
            compression = NONE;
        }

        if (compression === NONE) {

            options.mimeType = 'text/plain; charset=x-user-defined';
            igvxhr.load(url, options);
        }
        else {
            options.responseType = "arraybuffer";
            options.success = function (data) {
                var result = igv.arrayBufferToString(data, compression);
                success(result);
            };
            igvxhr.load(url, options);

        }

    }

    igvxhr.load = function (url, options) {

        var xhr = new XMLHttpRequest(),
            sendData = options.sendData,
            method = options.method || (sendData ? "POST" : "GET"),
            success = options.success,
            error = options.error || success,
            abort = options.abort || error,
            timeout = options.timeout || error,
            task = options.task,
            range = options.range,
            responseType = options.responseType,
            contentType = options.contentType,
            mimeType = options.mimeType,
            headers = options.headers,
            header_keys, key, value, i;

        if (task) task.xhrRequest = xhr;

        xhr.open(method, url);

        if (range) {
            var rangeEnd = range.start + range.size - 1;
            xhr.setRequestHeader("Range", "bytes=" + range.start + "-" + rangeEnd);
            xhr.setRequestHeader("Cache-control", "no-cache");
            xhr.setRequestHeader("If-None-Match", Math.random().toString(36));  // For nasty safari bug https://bugs.webkit.org/show_bug.cgi?id=82672
        }
        if (contentType) {
            xhr.setRequestHeader("Content-Type", contentType);
        }
        if (mimeType) {
            xhr.overrideMimeType(mimeType);
        }
        if (responseType) {
            xhr.responseType = responseType;
        }
        if (headers) {
            header_keys = Object.keys(headers);
            for (i = 0; i < header_keys.length; i++) {
                key = header_keys[i];
                value = headers[key];
                console.log("Adding to header: " + key + "=" + value);
                xhr.setRequestHeader(key, value);
            }
        }

        xhr.onload = function (event) {
            // when the url points to a local file, the status is 0 but that is no error
            if (xhr.status == 0 || (xhr.status >= 200 && xhr.status <= 300)) {
                success(xhr.response, xhr);
            }
            else {
                error(null, xhr);
            }

        };

        xhr.onerror = function (event) {

            if (isCrossDomain(url) && url) {
                // Try the proxy, if it exists.  Presumably this is a php file
                if (igv.browser.crossDomainProxy && url != igv.browser.crossDomainProxy) {

                    options.sendData = "url=" + url;

                    igvxhr.load(igv.browser.crossDomainProxy, options);
                    return;
                }
            }
            error(null, xhr);
        };

        xhr.ontimeout = function (event) {
            console.log("Aborted");
            timeout(null, xhr);
        };

        xhr.onabort = function (event) {
            console.log("Aborted");
            abort(null, xhr);
        };

        xhr.send(sendData);

    };

    igvxhr.loadHeader = function (url, options) {

        var xhr = new XMLHttpRequest(),
            method = "HEAD",
            success = options.success,
            error = options.error || success,
            timeout = options.timeout || error,
            headers = options.headers,
            header_keys,
            key,
            value,
            i;

        if (headers) {
            header_keys = Object.keys(headers);
            for (i = 0; i < header_keys.length; i++) {
                key = header_keys[i];
                value = headers[key];
                console.log("Adding to header: " + key + "=" + value);
                xhr.setRequestHeader(key, value);
            }
        }

        xhr.open(method, url);

        xhr.onload = function (event) {

            var headerStr = xhr.getAllResponseHeaders();
            var headerDictionary = parseResponseHeaders(headerStr);
            success(headerDictionary);
        }

        xhr.onerror = function (event) {
            error(null, xhr);
        }

        xhr.ontimeout = function (event) {
            timeout(null);
        }

        xhr.send();

        /**
         * XmlHttpRequest's getAllResponseHeaders() method returns a string of response
         * headers according to the format described here:
         * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method
         * This method parses that string into a user-friendly key/value pair object.
         */
        function parseResponseHeaders(headerStr) {
            var headers = {};
            if (!headerStr) {
                return headers;
            }
            var headerPairs = headerStr.split('\u000d\u000a');
            for (var i = 0, len = headerPairs.length; i < len; i++) {
                var headerPair = headerPairs[i];
                var index = headerPair.indexOf('\u003a\u0020');
                if (index > 0) {
                    var key = headerPair.substring(0, index);
                    var val = headerPair.substring(index + 2);
                    headers[key] = val;
                }
            }
            return headers;
        }

    }

    igvxhr.getContentLength = function (url, options) {

        var continuation = options.success;

        if (!options.error) {
            options.error = function () {
                continuation(-1);
            }
        }

        options.success = function (header) {
            var contentLengthString = header ? header["Content-Length"] : null;
            if (contentLengthString) {
                continuation(parseInt(contentLengthString));
            }
            else {
                continuation(-1);
            }

        }

        igvxhr.loadHeader(url, options);
    }

    igvxhr.loadStringFromFile = function (localfile, options) {

        var fileReader = new FileReader(),
            success = options.success,
            error = options.error || options.success,
            abort = options.abort || options.error,
            timeout = options.timeout || options.error,
            range = options.range;

        fileReader.onload = function (e) {

            var compression, result;

            if (options.bgz) {
                compression = BGZF;
            }
            else if (localfile.name.endsWith(".gz")) {

                compression = GZIP;
            }
            else {
                compression = NONE;
            }

            result = igv.arrayBufferToString(fileReader.result, compression);

            success(result, localfile);

        };

        fileReader.onerror = function (e) {
            console.log("error uploading local file " + localfile.name);
            error(null, fileReader);
        };

        fileReader.readAsArrayBuffer(localfile);

    }

    function isCrossDomain(url) {

        var origin = window.location.origin;

        return !url.startsWith(origin);

    }

    igv.arrayBufferToString = function (arraybuffer, compression) {

        var plain, inflate;

        if (compression === GZIP) {
            inflate = new Zlib.Gunzip(new Uint8Array(arraybuffer));
            plain = inflate.decompress();
        }
        else if (compression === BGZF) {
            plain = new Uint8Array(igv.unbgzf(arraybuffer));
        }
        else {
            plain = new Uint8Array(arraybuffer);
        }

        var result = "";
        for (var i = 0, len = plain.length; i < len; i++) {
            result = result + String.fromCharCode(plain[i]);
        }
        return result;
    }

    return igvxhr;

})(igvxhr || {});

<commit_msg>Function igvxhr.isReachable using async. Bogus domain now handled.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var igvxhr = (function (igvxhr) {

    // Compression types
    const NONE = 0;
    const GZIP = 1;
    const BGZF = 2;

    igvxhr.isReachable = function (url, continuation) {

        var request = new XMLHttpRequest();

        request.open("HEAD", url, true);

        request.onload = function (event) {

            if (0 === request.status) {
                console.log("igvxhr.isReachable - onload - failure - status " + request.status);
                continuation(false, request.status);
            }
            else if (request.status >= 200 && request.status <= 300) {
                console.log("igvxhr.isReachable - onload - success - status " + request.status);
                continuation(true, request.status);
            }
            else {
                console.log("igvxhr.isReachable - onload - failure - status " + request.status);
                continuation(false, request.status);
            }

        };

        request.onerror = function (event) {
            console.log("igvxhr.isReachable - onerror - status " + request.status);
            continuation(false, request.status);
        };

        request.ontimeout = function (event) {
            console.log("igvxhr.isReachable - ontimeout - status " + request.status);
            continuation(false, request.status);
        };

        request.onabort = function (event) {
            console.log("igvxhr.isReachable - onabort - status " + request.status);
            continuation(false, request.status);
        };

        console.log("igvxhr.isReachable - send - before");
        request.send(null);
        console.log("igvxhr.isReachable - send - after");

    };

    igvxhr.loadArrayBuffer = function (url, options) {
        options.responseType = "arraybuffer";
        igvxhr.load(url, options);
    }

    igvxhr.loadJson = function (url, options) {

        var success = options.success;

        options.contentType = "application/json";
        options.success = function (result) {
            if (result) {
                success(JSON.parse(result));
            }
            else {
                success(null);
            }
        };

        igvxhr.load(url, options);

    }

    /**
     * Load a "raw" string.
     */
    igvxhr.loadString = function (url, options) {

        var success = options.success,
            compression, result;

        if (options.bgz) {
            compression = BGZF;
        }
        else if (url.endsWith(".gz")) {

            compression = GZIP;
        }
        else {
            compression = NONE;
        }

        if (compression === NONE) {

            options.mimeType = 'text/plain; charset=x-user-defined';
            igvxhr.load(url, options);
        }
        else {
            options.responseType = "arraybuffer";
            options.success = function (data) {
                var result = igv.arrayBufferToString(data, compression);
                success(result);
            };
            igvxhr.load(url, options);

        }

    }

    igvxhr.load = function (url, options) {

        var xhr = new XMLHttpRequest(),
            sendData = options.sendData,
            method = options.method || (sendData ? "POST" : "GET"),
            success = options.success,
            error = options.error || success,
            abort = options.abort || error,
            timeout = options.timeout || error,
            task = options.task,
            range = options.range,
            responseType = options.responseType,
            contentType = options.contentType,
            mimeType = options.mimeType,
            headers = options.headers,
            header_keys, key, value, i;

        if (task) task.xhrRequest = xhr;

        xhr.open(method, url);

        if (range) {
            var rangeEnd = range.start + range.size - 1;
            xhr.setRequestHeader("Range", "bytes=" + range.start + "-" + rangeEnd);
            xhr.setRequestHeader("Cache-control", "no-cache");
            xhr.setRequestHeader("If-None-Match", Math.random().toString(36));  // For nasty safari bug https://bugs.webkit.org/show_bug.cgi?id=82672
        }
        if (contentType) {
            xhr.setRequestHeader("Content-Type", contentType);
        }
        if (mimeType) {
            xhr.overrideMimeType(mimeType);
        }
        if (responseType) {
            xhr.responseType = responseType;
        }
        if (headers) {
            header_keys = Object.keys(headers);
            for (i = 0; i < header_keys.length; i++) {
                key = header_keys[i];
                value = headers[key];
                console.log("Adding to header: " + key + "=" + value);
                xhr.setRequestHeader(key, value);
            }
        }

        xhr.onload = function (event) {
            // when the url points to a local file, the status is 0 but that is no error
            if (xhr.status == 0 || (xhr.status >= 200 && xhr.status <= 300)) {
                success(xhr.response, xhr);
            }
            else {
                error(null, xhr);
            }

        };

        xhr.onerror = function (event) {

            if (isCrossDomain(url) && url) {
                // Try the proxy, if it exists.  Presumably this is a php file
                if (igv.browser.crossDomainProxy && url != igv.browser.crossDomainProxy) {

                    options.sendData = "url=" + url;

                    igvxhr.load(igv.browser.crossDomainProxy, options);
                    return;
                }
            }
            error(null, xhr);
        };

        xhr.ontimeout = function (event) {
            console.log("Aborted");
            timeout(null, xhr);
        };

        xhr.onabort = function (event) {
            console.log("Aborted");
            abort(null, xhr);
        };

        xhr.send(sendData);

    };

    igvxhr.loadHeader = function (url, options) {

        var xhr = new XMLHttpRequest(),
            method = "HEAD",
            success = options.success,
            error = options.error || success,
            timeout = options.timeout || error,
            headers = options.headers,
            header_keys,
            key,
            value,
            i;

        if (headers) {
            header_keys = Object.keys(headers);
            for (i = 0; i < header_keys.length; i++) {
                key = header_keys[i];
                value = headers[key];
                console.log("Adding to header: " + key + "=" + value);
                xhr.setRequestHeader(key, value);
            }
        }

        xhr.open(method, url);

        xhr.onload = function (event) {

            var headerStr = xhr.getAllResponseHeaders();
            var headerDictionary = parseResponseHeaders(headerStr);
            success(headerDictionary);
        }

        xhr.onerror = function (event) {
            error(null, xhr);
        }

        xhr.ontimeout = function (event) {
            timeout(null);
        }

        xhr.send();

        /**
         * XmlHttpRequest's getAllResponseHeaders() method returns a string of response
         * headers according to the format described here:
         * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method
         * This method parses that string into a user-friendly key/value pair object.
         */
        function parseResponseHeaders(headerStr) {
            var headers = {};
            if (!headerStr) {
                return headers;
            }
            var headerPairs = headerStr.split('\u000d\u000a');
            for (var i = 0, len = headerPairs.length; i < len; i++) {
                var headerPair = headerPairs[i];
                var index = headerPair.indexOf('\u003a\u0020');
                if (index > 0) {
                    var key = headerPair.substring(0, index);
                    var val = headerPair.substring(index + 2);
                    headers[key] = val;
                }
            }
            return headers;
        }

    }

    igvxhr.getContentLength = function (url, options) {

        var continuation = options.success;

        if (!options.error) {
            options.error = function () {
                continuation(-1);
            }
        }

        options.success = function (header) {
            var contentLengthString = header ? header["Content-Length"] : null;
            if (contentLengthString) {
                continuation(parseInt(contentLengthString));
            }
            else {
                continuation(-1);
            }

        }

        igvxhr.loadHeader(url, options);
    }

    igvxhr.loadStringFromFile = function (localfile, options) {

        var fileReader = new FileReader(),
            success = options.success,
            error = options.error || options.success,
            abort = options.abort || options.error,
            timeout = options.timeout || options.error,
            range = options.range;

        fileReader.onload = function (e) {

            var compression, result;

            if (options.bgz) {
                compression = BGZF;
            }
            else if (localfile.name.endsWith(".gz")) {

                compression = GZIP;
            }
            else {
                compression = NONE;
            }

            result = igv.arrayBufferToString(fileReader.result, compression);

            success(result, localfile);

        };

        fileReader.onerror = function (e) {
            console.log("error uploading local file " + localfile.name);
            error(null, fileReader);
        };

        fileReader.readAsArrayBuffer(localfile);

    }

    function isCrossDomain(url) {

        var origin = window.location.origin;

        return !url.startsWith(origin);

    }

    igv.arrayBufferToString = function (arraybuffer, compression) {

        var plain, inflate;

        if (compression === GZIP) {
            inflate = new Zlib.Gunzip(new Uint8Array(arraybuffer));
            plain = inflate.decompress();
        }
        else if (compression === BGZF) {
            plain = new Uint8Array(igv.unbgzf(arraybuffer));
        }
        else {
            plain = new Uint8Array(arraybuffer);
        }

        var result = "";
        for (var i = 0, len = plain.length; i < len; i++) {
            result = result + String.fromCharCode(plain[i]);
        }
        return result;
    }

    return igvxhr;

})(igvxhr || {});

<|endoftext|>


<commit_before>import React, { Component, } from 'react';
import {
  Button,
  Col,
  Grid,
  MenuItem,
  Nav,
  Navbar,
  NavDropdown,
  NavItem,
  Row,
} from 'react-bootstrap';
import { LinkContainer, } from 'react-router-bootstrap';

import { imagePath, } from '../util/imagePath';

const navPages = [
  'Useful Links',
  'About',
];

const databasePages = [
  'Heroes',
  'Soulbound Weapons',
  'Weapons',
  'Skills',
  'Goddesses',
  'Bread',
  'Berries',
  'Interactions',
];

const toolsPages = [
  'Contract Pulling Simulator',
  'Sbw Forging Simulator',
  'Effective Attack Optimizer',
];

export default class Frame extends Component {
  renderItem = (i, isNavItem) => {
    return (
      <LinkContainer key={i} to={`/cqdb/${i.toLowerCase()}`}>
        {isNavItem ? <NavItem>{i}</NavItem> : <MenuItem>{i}</MenuItem>}
      </LinkContainer>
    );
  }

  renderNavDropdown = (pages, title) => {
    return (
      <NavDropdown id={title} key={title} title={title}>
        {pages.map(i => this.renderItem(i, false))}
      </NavDropdown>
    );
  }

  renderNavbar = () => {
    const pages = navPages.map(i => this.renderItem(i, true));
    pages.splice(0, 0, this.renderNavDropdown(toolsPages, 'Tools'));
    pages.splice(0, 0, this.renderNavDropdown(databasePages, 'Database'));

    return (
      <Navbar collapseOnSelect fixedTop inverse>
        <Navbar.Header>
          <LinkContainer to='/cqdb'>
            <Navbar.Brand>

              cqdb
            </Navbar.Brand>
          </LinkContainer>
          <Navbar.Toggle />
        </Navbar.Header>
        <Navbar.Collapse>
          {pages}
          <Navbar.Form pullRight style={{textAlign: 'center',}}>
            <Button bsStyle='primary' href='https://play.google.com/store/apps/details?id=com.nhnent.SKQUEST'>
              Android 3.10.6.KG
            </Button>

            <Button bsStyle='primary' href='https://itunes.apple.com/app/id901858272?mt=8'>
              iOS 3.10.5
            </Button>
          </Navbar.Form>
        </Navbar.Collapse>
      </Navbar>
    );
  }

  renderFooter = () => {
    return (
      <Row>
        <Col lg={12} md={12} sm={12} xs={12}>

            Made with ❤ by Peter

        </Col>
      </Row>
    );
  }

  render = () => {
    return (

        {this.renderNavbar()}

        <Grid fluid>

            {this.props.children}
            {this.renderFooter()}

        </Grid>

    );
  }
}<commit_msg>Update version<commit_after>import React, { Component, } from 'react';
import {
  Button,
  Col,
  Grid,
  MenuItem,
  Nav,
  Navbar,
  NavDropdown,
  NavItem,
  Row,
} from 'react-bootstrap';
import { LinkContainer, } from 'react-router-bootstrap';

import { imagePath, } from '../util/imagePath';

const navPages = [
  'Useful Links',
  'About',
];

const databasePages = [
  'Heroes',
  'Soulbound Weapons',
  'Weapons',
  'Skills',
  'Goddesses',
  'Bread',
  'Berries',
  'Interactions',
];

const toolsPages = [
  'Contract Pulling Simulator',
  'Sbw Forging Simulator',
  'Effective Attack Optimizer',
];

export default class Frame extends Component {
  renderItem = (i, isNavItem) => {
    return (
      <LinkContainer key={i} to={`/cqdb/${i.toLowerCase()}`}>
        {isNavItem ? <NavItem>{i}</NavItem> : <MenuItem>{i}</MenuItem>}
      </LinkContainer>
    );
  }

  renderNavDropdown = (pages, title) => {
    return (
      <NavDropdown id={title} key={title} title={title}>
        {pages.map(i => this.renderItem(i, false))}
      </NavDropdown>
    );
  }

  renderNavbar = () => {
    const pages = navPages.map(i => this.renderItem(i, true));
    pages.splice(0, 0, this.renderNavDropdown(toolsPages, 'Tools'));
    pages.splice(0, 0, this.renderNavDropdown(databasePages, 'Database'));

    return (
      <Navbar collapseOnSelect fixedTop inverse>
        <Navbar.Header>
          <LinkContainer to='/cqdb'>
            <Navbar.Brand>

              cqdb
            </Navbar.Brand>
          </LinkContainer>
          <Navbar.Toggle />
        </Navbar.Header>
        <Navbar.Collapse>
          {pages}
          <Navbar.Form pullRight style={{textAlign: 'center',}}>
            <Button bsStyle='primary' href='https://play.google.com/store/apps/details?id=com.nhnent.SKQUEST'>
              Android 3.11.6.KG
            </Button>

            <Button bsStyle='primary' href='https://itunes.apple.com/app/id901858272?mt=8'>
              iOS 3.11.4
            </Button>
          </Navbar.Form>
        </Navbar.Collapse>
      </Navbar>
    );
  }

  renderFooter = () => {
    return (
      <Row>
        <Col lg={12} md={12} sm={12} xs={12}>

            Made with ❤ by Peter

        </Col>
      </Row>
    );
  }

  render = () => {
    return (

        {this.renderNavbar()}

        <Grid fluid>

            {this.props.children}
            {this.renderFooter()}

        </Grid>

    );
  }
}<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Preflop stage active",

  /**
   * @returns false - если не префлоп
   *      1000 - если пара или больше или равно 10
   *      0 - если нужно сбросить карты
   */
  preflop_stage: function(game_state) {
    var player = game_state.players[game_state.in_action];

    if ( player.hole_cards.length != 2 ) {
      return false;
    }

    var card1 = player.hole_cards[0], card2 = player.hole_cards[1];

    if (
      card1.rank == card2.rank
    ) {
      return 1000;
    }

    if (
      (
        card1.rank == '10'
        || card1.rank == 'J'
        || card1.rank == 'Q'
        || card1.rank == 'K'
        || card1.rank == 'A'
      ) && (
        card2.rank == '10'
        || card2.rank == 'J'
        || card2.rank == 'Q'
        || card2.rank == 'K'
        || card2.rank == 'A'
      )
    ) {
      return 1000;
    }

    return 10;
  },

  flop_request: function(game_state) {
    return 1000;
  },

  turn_request: function(game_state) {
    return 1000;
  },

  river_request: function(game_state) {
    return 1000;
  }

  bet_request: function(game_state) {
    console.log('game_state_json', JSON.stringify(game_state));
    console.log("game_state !!!", game_state);

    var player = game_state.players[game_state.in_action];
    if ( player.hole_cards.length != 2 ) {
      return false;
    }
    var bet=0;

    if ( game_state.community_cards && game_state.community_cards.length == 0 ) {
      bet = preflop_stage(game_state);
    } else if ( game_state.community_cards && game_state.community_cards.length == 3 ) {
      bet = flop_request(game_state);
    } else ( game_state.community_cards && game_state.community_cards.length == 4 ) {
      bet = turn_request(game_state);
    } else ( game_state.community_cards && game_state.community_cards.length == 5 ) {
      bet = river_request(game_state);
    } else {
      return 0;
    }

    return bet;
  },

  // rank2Num: function(rank) {
  //   switch (rank) {
  //     case 'J': return 11;
  //     case 'Q': return 12;
  //     case 'K': return 13;
  //     case 'A': return 14;
  //     default: return rank;
  //   }
  // },

  showdown: function(game_state) {

  },

  should_bet_after_flop: function(cards) {

    return true;
  },

  any_cards_are_equal: function(cards) {
    for (var i = 0; i < cards.length-1; i++) {
      for (var j = i+1; j < cards.length; j++) {
        if (cards[i].rank == cards[j].rank)
          return true;
      }
    }
    return false;
  },

  get_player_cards: function(game_state) {
    var index = game_state.in_action;

    if (game_state.players[index]) {
      return game_state.players[index].hole_cards;
    }

    console.log("player not found", game_state);
  }

};
<commit_msg>add all stage<commit_after>
module.exports = {

  VERSION: "Preflop stage active",

  /**
   * @returns false - если не префлоп
   *      1000 - если пара или больше или равно 10
   *      0 - если нужно сбросить карты
   */
  preflop_stage: function(game_state) {
    var player = game_state.players[game_state.in_action];

    if ( player.hole_cards.length != 2 ) {
      return false;
    }

    var card1 = player.hole_cards[0], card2 = player.hole_cards[1];

    if (
      card1.rank == card2.rank
    ) {
      return 1000;
    }

    if (
      (
        card1.rank == '10'
        || card1.rank == 'J'
        || card1.rank == 'Q'
        || card1.rank == 'K'
        || card1.rank == 'A'
      ) && (
        card2.rank == '10'
        || card2.rank == 'J'
        || card2.rank == 'Q'
        || card2.rank == 'K'
        || card2.rank == 'A'
      )
    ) {
      return 1000;
    }

    return 10;
  },

  flop_request: function(game_state) {
    return 1000;
  },

  turn_request: function(game_state) {
    return 1000;
  },

  river_request: function(game_state) {
    return 1000;
  },

  bet_request: function(game_state) {
    console.log('game_state_json', JSON.stringify(game_state));
    console.log("game_state !!!", game_state);

    var player = game_state.players[game_state.in_action];
    if ( player.hole_cards.length != 2 ) {
      return false;
    }
    var bet=0;

    if ( game_state.community_cards && game_state.community_cards.length == 0 ) {
      bet = preflop_stage(game_state);
    } else if ( game_state.community_cards && game_state.community_cards.length == 3 ) {
      bet = flop_request(game_state);
    } else if ( game_state.community_cards && game_state.community_cards.length == 4 ) {
      bet = turn_request(game_state);
    } else if ( game_state.community_cards && game_state.community_cards.length == 5 ) {
      bet = river_request(game_state);
    } else {
      return 0;
    }

    return bet;
  },

  // rank2Num: function(rank) {
  //   switch (rank) {
  //     case 'J': return 11;
  //     case 'Q': return 12;
  //     case 'K': return 13;
  //     case 'A': return 14;
  //     default: return rank;
  //   }
  // },

  showdown: function(game_state) {

  },

  should_bet_after_flop: function(cards) {

    return true;
  },

  any_cards_are_equal: function(cards) {
    for (var i = 0; i < cards.length-1; i++) {
      for (var j = i+1; j < cards.length; j++) {
        if (cards[i].rank == cards[j].rank)
          return true;
      }
    }
    return false;
  },

  get_player_cards: function(game_state) {
    var index = game_state.in_action;

    if (game_state.players[index]) {
      return game_state.players[index].hole_cards;
    }

    console.log("player not found", game_state);
  }

};
<|endoftext|>


<commit_before>var _ = require("lodash");
var async = require("async");

var shlog = require(global.gBaseDir + "/src/shlog.js");
var sh = require(global.gBaseDir + "/src/shutil.js");
var reg = require(global.gBaseDir + "/functions/reg/reg.js");
var _w = require(global.gBaseDir + "/src/shcb.js")._w;

var user = exports;

user.desc = "utility functions for shelly modules";
user.functions = {
  get: {desc: "get current user object", params: {}, security: []},
  set: {desc: "set current user object", params: {user: {dtype: "object"}}, security: []},
  aget: {desc: "get any user object", params: {uid: {dtype: "string"}}, security: ["admin"]},
  aset: {desc: "set any user object", params: {uid: {dtype: "string"}, user: {dtype: "object"}}, security: ["admin"]},
  profiles: {desc: "get public user infoformation", params: {users : {dtype: "array"}}, security: []},
  find: {desc: "find a user based on email or token", params: {by : {dtype: "string"}, value: {dtype: "string"}}, security: ["admin"]}
};

user.get = function (req, res, cb) {
  res.add(sh.event("user.get", req.session.user.getData()));
  return cb(0);
};

user.set = function (req, res, cb) {
  var userData = req.body.user;

  // only admin can change roles
  if (!_.isUndefined(userData.roles)  && !req.session.user.hasRole("admin")) {
    res.add(sh.error("user-roles", "user does not have rights to alter roles"));
    return cb(1);
  }

  req.loader.exists("kUser", req.session.uid, _w(cb, function (err, user) {
    if (err) {
      res.add(sh.error("user-bad", "unable to load user", user));
      return cb(1);
    }
    var keyType = user.typeError(userData);
    if (keyType) {
      res.add(sh.error("user-data", "type mismatch in user data", keyType));
      return cb(1);
    }
    user.setData(userData);
    res.add(sh.event("user.set", user.getData()));
    return cb(0);
  }, {lock: true}));
};

user.aget = function (req, res, cb) {
  var uid = req.body.uid;

  req.loader.exists("kUser", uid, _w(cb, function (error, user) {
    if (error) {
      res.add(sh.error("user-aget", "user does not exist", user));
      return;
    }
    res.add(sh.event("user.get", user.getData()));
    return cb(0);
  }));
};

user.aset = function (req, res, cb) {
  var uid = req.body.uid;
  var newUser = req.body.user;

  req.loader.exists("kUser", uid, _w(cb, function (error, user) {
    if (error) {
      res.add(sh.error("user-aset", "user does not exist", user));
      return;
    }
    user.setData(newUser);
    res.add(sh.event("user.get", user.getData()));
    return cb(0);
  }, {lock: true}));
};

user.profiles = function (req, res, cb) {
  var userIds = req.body.users;
  sh.fillProfiles(req.loader, userIds, _w(cb, function (error, data) {
    if (error) {
      res.add(sh.error("profile-fill", "unable to fill in profile data", data));
      return cb(1);
    }
    res.add(sh.event("user.profiles", data));
    return cb(0);
  }));
};

user.find = function (req, res, cb) {
  if (req.body.by === "email") {
    reg.findUserByEmail(req.loader, req.body.value, _w(cb, function (err, data) {
      if (err) {
        res.add(sh.error("user-find-email", "unable to file user with this email", data));
        return cb(1);
      }
      res.add(sh.event("user.find", data.getData()));
      return cb(0);
    }));
    return;
  }
  if (req.body.by === "uid") {
    req.loader.exists("kUser", req.body.value, _w(cb, function (err, data) {
      if (err) {
        res.add(sh.error("user-find-uid", "unable to find user with uid", data));
        return cb(1);
      }
      res.add(sh.event("user.find", data.getData()));
      return cb(0);
    }));
    return;
  }
  if (req.body.by === "token") {
    reg.findUserByToken(req.loader, req.body.value, _w(cb, function (err, data) {
      if (err) {
        res.add(sh.error("user-find-token", "unable to find user with uid", data));
        return cb(1);
      }
      res.add(sh.event("user.find", data.getData()));
      return cb(0);
    }));
    return;
  }

  res.add(sh.error("user-find-unknown", "no way to find a user by this data type", {by: req.body.by}));
  return cb(1);
};
<commit_msg>fix missing cb on user not found in aget;<commit_after>var _ = require("lodash");
var async = require("async");

var shlog = require(global.gBaseDir + "/src/shlog.js");
var sh = require(global.gBaseDir + "/src/shutil.js");
var reg = require(global.gBaseDir + "/functions/reg/reg.js");
var _w = require(global.gBaseDir + "/src/shcb.js")._w;

var user = exports;

user.desc = "utility functions for shelly modules";
user.functions = {
  get: {desc: "get current user object", params: {}, security: []},
  set: {desc: "set current user object", params: {user: {dtype: "object"}}, security: []},
  aget: {desc: "get any user object", params: {uid: {dtype: "string"}}, security: ["admin"]},
  aset: {desc: "set any user object", params: {uid: {dtype: "string"}, user: {dtype: "object"}}, security: ["admin"]},
  profiles: {desc: "get public user infoformation", params: {users : {dtype: "array"}}, security: []},
  find: {desc: "find a user based on email or token", params: {by : {dtype: "string"}, value: {dtype: "string"}}, security: ["admin"]}
};

user.get = function (req, res, cb) {
  res.add(sh.event("user.get", req.session.user.getData()));
  return cb(0);
};

user.set = function (req, res, cb) {
  var userData = req.body.user;

  // only admin can change roles
  if (!_.isUndefined(userData.roles)  && !req.session.user.hasRole("admin")) {
    res.add(sh.error("user-roles", "user does not have rights to alter roles"));
    return cb(1);
  }

  req.loader.exists("kUser", req.session.uid, _w(cb, function (err, user) {
    if (err) {
      res.add(sh.error("user-bad", "unable to load user", user));
      return cb(1);
    }
    var keyType = user.typeError(userData);
    if (keyType) {
      res.add(sh.error("user-data", "type mismatch in user data", keyType));
      return cb(1);
    }
    user.setData(userData);
    res.add(sh.event("user.set", user.getData()));
    return cb(0);
  }, {lock: true}));
};

user.aget = function (req, res, cb) {
  var uid = req.body.uid;

  req.loader.exists("kUser", uid, _w(cb, function (error, user) {
    if (error) {
      res.add(sh.error("user-aget", "user does not exist", user));
      return cb(1);
    }
    res.add(sh.event("user.get", user.getData()));
    return cb(0);
  }));
};

user.aset = function (req, res, cb) {
  var uid = req.body.uid;
  var newUser = req.body.user;

  req.loader.exists("kUser", uid, _w(cb, function (error, user) {
    if (error) {
      res.add(sh.error("user-aset", "user does not exist", user));
      return;
    }
    user.setData(newUser);
    res.add(sh.event("user.get", user.getData()));
    return cb(0);
  }, {lock: true}));
};

user.profiles = function (req, res, cb) {
  var userIds = req.body.users;
  sh.fillProfiles(req.loader, userIds, _w(cb, function (error, data) {
    if (error) {
      res.add(sh.error("profile-fill", "unable to fill in profile data", data));
      return cb(1);
    }
    res.add(sh.event("user.profiles", data));
    return cb(0);
  }));
};

user.find = function (req, res, cb) {
  if (req.body.by === "email") {
    reg.findUserByEmail(req.loader, req.body.value, _w(cb, function (err, data) {
      if (err) {
        res.add(sh.error("user-find-email", "unable to file user with this email", data));
        return cb(1);
      }
      res.add(sh.event("user.find", data.getData()));
      return cb(0);
    }));
    return;
  }
  if (req.body.by === "uid") {
    req.loader.exists("kUser", req.body.value, _w(cb, function (err, data) {
      if (err) {
        res.add(sh.error("user-find-uid", "unable to find user with uid", data));
        return cb(1);
      }
      res.add(sh.event("user.find", data.getData()));
      return cb(0);
    }));
    return;
  }
  if (req.body.by === "token") {
    reg.findUserByToken(req.loader, req.body.value, _w(cb, function (err, data) {
      if (err) {
        res.add(sh.error("user-find-token", "unable to find user with uid", data));
        return cb(1);
      }
      res.add(sh.event("user.find", data.getData()));
      return cb(0);
    }));
    return;
  }

  res.add(sh.error("user-find-unknown", "no way to find a user by this data type", {by: req.body.by}));
  return cb(1);
};
<|endoftext|>


<commit_before>const appconfig = require('./appconfig.js');
/*
    Notifications
 */
function getTopic(tag,chatId) {
    return "/topics/"+tag+"."+chatId
}

async function getToken(){
    const messaging = firebase.messaging();
    return await messaging.getToken().then((currentToken) => {
        if (currentToken) {
            return currentToken;
        } else {
            console.log('No Instance ID token available. Request permission to generate one.');
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
    });
}

async function initNotifications() {
    const messaging = firebase.messaging();
    await messaging.requestPermission()
    .then(function () {
        console.log("Have permission");
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/firebase-messaging-sw.js')
            .then(function(registration) {
                console.log('Registration successful, scope is:', registration.scope);
            }).catch(function(err) {
                console.log('Service worker registration failed, error:', err);
            });
        }
    });
    subscribeToAllChats()
    messaging.onMessage((payload) => {
        console.log(payload)
        if (!((payload.data.tag==sessionStorage.activeChatTag)&&(payload.data.chatId==sessionStorage.activeChatId))){
            console.log("RECEIVED A MESSAGE FROM A NON-ACTIVE CHAT!");
            // TODO: Show in page popup or notification and update the chat preview for that chat here
        } else {
            // TODO: Update the DOM here? or leave where it currently is.
        }
    });
}
function subscribeToAllChats() {
    currentUid = firebase.auth().currentUser.uid;
    tagsRef = firebase.database().ref('/users/'+currentUid+'/allTags');
    tagsRef.once('value', function(snap) {
        if (snap.val()) {
            for (const [tag,chatId] of Object.entries(snap.val())) {
                subscribeToTagChatId(tag, chatId)
            }
        }
    });
}

async function unSubscribeFromAllChats() {
    currentUid = firebase.auth().currentUser.uid;
    tagsRef = firebase.database().ref('/users/'+currentUid+'/allTags');
    await tagsRef.once('value', async function(snap) {
        if (snap.val()) {
            for (const [tag,chatId] of Object.entries(snap.val())) {
                await unsubscribeFromTagChatId(tag, chatId)
            }
        }
    });
}

async function unsubscribeFromTagChatId(tag, chatId) {
    const token = await getToken();
    url = "https://iid.googleapis.com/iid/v1:batchRemove";
    payload = {
        "to": getTopic(tag,chatId),
        "registration_tokens": [token]
    }
    $.ajax({
        url: url,
        type: 'post',
        data: JSON.stringify(payload),
        dataType: 'json',
        headers: {
            "Content-Type": 'application/json',
            "Authorization": appconfig.serverKey
        }
    });
}

async function subscribeToTagChatId(tag, chatId) {
    const token = await getToken();
    url = "https://iid.googleapis.com/iid/v1/"+token+"/rel"+getTopic(tag,chatId);
    $.ajax({
        url: url,
        type: 'post',
        headers: {
            "Content-Type": 'application/json',
            "Authorization": appconfig.serverKey
        }
    });
}

function sendNotificationForChat(message) {
    console.log(message);
    const tag = sessionStorage.activeChatTag;
    const chatId = sessionStorage.activeChatId;
    const name = message.senderDisplay;
    notificationBody = name+' has sent a message:\n\n'+message.content
    console.log(message.timestamp);
    let payload = {
        "to": getTopic(tag,chatId),
        "notification": {
            "title": tag,
            "body": notificationBody,
            "icon": '/static/images/friendsChatting.png',
            "click_action": 'https://8080-9f73b32e-6ccb-426e-8d6e-c03d6f324666.us-west1.cloudshell.dev/static/chat.html'
        },
        "data":{
            "tag": tag,
            "chatId": chatId,
            "name" : name,
            "time" : message.timestamp
        }
    }
    $.ajax({
        url: 'https://fcm.googleapis.com/fcm/send',
        type: 'post',
        data: JSON.stringify(payload),
        dataType: 'json',
        headers: {
            "Content-Type": 'application/json',
            "Authorization": appconfig.serverKey
        },
        dataType: 'json'
    });
}

exports.initNotifications = initNotifications;
exports.subscribeToTagChatId = subscribeToTagChatId;
exports.unsubscribeFromTagChatId = unsubscribeFromTagChatId;
exports.sendNotificationForChat = sendNotificationForChat;
exports.unSubscribeFromAllChats = unSubscribeFromAllChats;
exports.getToken = getToken;<commit_msg>removes unread tag when user is looking at chat<commit_after>const appconfig = require('./appconfig.js');
/*
    Notifications
 */
function getTopic(tag,chatId) {
    return "/topics/"+tag+"."+chatId
}

async function getToken(){
    const messaging = firebase.messaging();
    return await messaging.getToken().then((currentToken) => {
        if (currentToken) {
            return currentToken;
        } else {
            console.log('No Instance ID token available. Request permission to generate one.');
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
    });
}

async function initNotifications() {
    const messaging = firebase.messaging();
    await messaging.requestPermission()
    .then(function () {
        console.log("Have permission");
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/firebase-messaging-sw.js')
            .then(function(registration) {
                console.log('Registration successful, scope is:', registration.scope);
            }).catch(function(err) {
                console.log('Service worker registration failed, error:', err);
            });
        }
    });
    subscribeToAllChats()
    messaging.onMessage((payload) => {
        console.log(payload)
        if (!((payload.data.tag==sessionStorage.activeChatTag)&&(payload.data.chatId==sessionStorage.activeChatId))){
            console.log("RECEIVED A MESSAGE FROM A NON-ACTIVE CHAT!");
            // TODO: Show in page popup or notification and update the chat preview for that chat here
        } else {
            // Removes the inevitably generated 'unread' marker if user is looking at page
            const unreadClasses = document.querySelectorAll('.unread');
            unreadClasses.forEach(unreadMarker => {
                unreadMarker.innerText = '';
            });
        }
    });
}
function subscribeToAllChats() {
    currentUid = firebase.auth().currentUser.uid;
    tagsRef = firebase.database().ref('/users/'+currentUid+'/allTags');
    tagsRef.once('value', function(snap) {
        if (snap.val()) {
            for (const [tag,chatId] of Object.entries(snap.val())) {
                subscribeToTagChatId(tag, chatId)
            }
        }
    });
}

async function unSubscribeFromAllChats() {
    currentUid = firebase.auth().currentUser.uid;
    tagsRef = firebase.database().ref('/users/'+currentUid+'/allTags');
    await tagsRef.once('value', async function(snap) {
        if (snap.val()) {
            for (const [tag,chatId] of Object.entries(snap.val())) {
                await unsubscribeFromTagChatId(tag, chatId)
            }
        }
    });
}

async function unsubscribeFromTagChatId(tag, chatId) {
    const token = await getToken();
    url = "https://iid.googleapis.com/iid/v1:batchRemove";
    payload = {
        "to": getTopic(tag,chatId),
        "registration_tokens": [token]
    }
    $.ajax({
        url: url,
        type: 'post',
        data: JSON.stringify(payload),
        dataType: 'json',
        headers: {
            "Content-Type": 'application/json',
            "Authorization": appconfig.serverKey
        }
    });
}

async function subscribeToTagChatId(tag, chatId) {
    const token = await getToken();
    url = "https://iid.googleapis.com/iid/v1/"+token+"/rel"+getTopic(tag,chatId);
    $.ajax({
        url: url,
        type: 'post',
        headers: {
            "Content-Type": 'application/json',
            "Authorization": appconfig.serverKey
        }
    });
}

function sendNotificationForChat(message) {
    console.log(message);
    const tag = sessionStorage.activeChatTag;
    const chatId = sessionStorage.activeChatId;
    const name = message.senderDisplay;
    notificationBody = name+' has sent a message:\n\n'+message.content
    console.log(message.timestamp);
    let payload = {
        "to": getTopic(tag,chatId),
        "notification": {
            "title": tag,
            "body": notificationBody,
            "icon": '/static/images/friendsChatting.png',
            "click_action": 'https://8080-9f73b32e-6ccb-426e-8d6e-c03d6f324666.us-west1.cloudshell.dev/static/chat.html'
        },
        "data":{
            "tag": tag,
            "chatId": chatId,
            "name" : name,
            "time" : message.timestamp
        }
    }
    $.ajax({
        url: 'https://fcm.googleapis.com/fcm/send',
        type: 'post',
        data: JSON.stringify(payload),
        dataType: 'json',
        headers: {
            "Content-Type": 'application/json',
            "Authorization": appconfig.serverKey
        },
        dataType: 'json'
    });
}

exports.initNotifications = initNotifications;
exports.subscribeToTagChatId = subscribeToTagChatId;
exports.unsubscribeFromTagChatId = unsubscribeFromTagChatId;
exports.sendNotificationForChat = sendNotificationForChat;
exports.unSubscribeFromAllChats = unSubscribeFromAllChats;
exports.getToken = getToken;<|endoftext|>


<commit_before><commit_msg>Updated module numbers<commit_after><|endoftext|>


<commit_before>'use strict';

class Player {
  constructor() {
    this.VERSION = "iPlayer 2.1";
  }

  bet_request(game_state) {
    var currentPlayer = game_state.players[game_state.in_action];

    var cards = [].concat(currentPlayer.hole_cards).concat(game_state.community_cards);

    var result = cards.reduce(function (previousValue, currentValue) {
      if (previousValue[currentValue.rank]) {
        previousValue[currentValue.rank]++;
      }
      else {
        previousValue[currentValue.rank] = 1;
      }

      return previousValue;
    }, {});

    var shouldAllIn = false;
    Object.keys(result).forEach(function (key) {
      if (result[key] > 1) {
        shouldAllIn = 1;
      }
    });

    if (game_state.community_cards.length === 0) {
      return game_state.current_buy_in - currentPlayer.bet;
    }

    if (shouldAllIn) {
      return 1000;
    }
    else {
      return 0;
    }
  }

  showdown(game_state) {

  }

}

module.exports = new Player();
<commit_msg>Real all in<commit_after>'use strict';

class Player {
  constructor() {
    this.VERSION = "iPlayer 2.1";
  }

  bet_request(game_state) {
    var currentPlayer = game_state.players[game_state.in_action];

    var cards = [].concat(currentPlayer.hole_cards).concat(game_state.community_cards);

    var result = cards.reduce(function (previousValue, currentValue) {
      if (previousValue[currentValue.rank]) {
        previousValue[currentValue.rank]++;
      }
      else {
        previousValue[currentValue.rank] = 1;
      }

      return previousValue;
    }, {});

    var shouldAllIn = false;
    Object.keys(result).forEach(function (key) {
      if (result[key] > 1) {
        shouldAllIn = 1;
      }
    });

    if (game_state.community_cards.length === 0) {
      return game_state.current_buy_in - currentPlayer.bet;
    }

    if (shouldAllIn) {
      return 5000;
    }
    else {
      return 0;
    }
  }

  showdown(game_state) {

  }

}

module.exports = new Player();
<|endoftext|>


<commit_before>(function(){
	'use strict';

	angular.module('demoApp')
	.controller('iconsCtrl', ['$scope', function($scope){
		$scope.contextSensIcons = [
			['plus', 'minus', 'check', 'cross', 'forbidden'],
			['error','warning','help'],
			["ellipsis", "list", "tree list", "blocks", "filter"],
			['lock', 'unlock'],
		];

		$scope.contextInsensIcons = [
			['attachment', 'files', "email", "phone", "notification", "camera", "settings", "sliders", "gallery","calendar", "clock", "timer", "pin", "location", "comment", "branch", "analytics"],
			["edit", "edit frame", "edit mini", "download", "upload", "outside", "send", "search", "trash", "refresh", "printer"],
			["user", "add user", "remove user", "to user"],
			["bookmark", "add bookmark", "remove bookmark"],
		];

		$scope.mouseIcons = [
			['drag', 'drag2'],
			['move','move horizontally','move vertically']
		];

		$scope.arrowIcons = [
			['north chevron','east chevron','south chevron','west chevron'],
			['north arrow','east arrow','south arrow','west arrow']
		];

		$scope.speIcons = [
			["breakfast", "coffee", "meal", "lunch", "diner", "drink"],
			["car", "clean car", "taxi", "bus", "subway", "truck", "train", "plane"],
			["euro toll", "dollar toll", "parking", "milestone", "mileage", "gasoline"],
			["journey", "luggage", "hotel", "postage"],
			["euro", "dollar", "quantity", "piggy bank", "bank card", "pricetag", "payment"],
			["computer", "computer mouse", "database"],
			["tools", "tiles", "iron", "roles", "jumping cc"]
		];
	}]);
})();
<commit_msg>Added new icons to lucca-ui demo<commit_after>(function(){
	'use strict';

	angular.module('demoApp')
	.controller('iconsCtrl', ['$scope', function($scope){
		$scope.contextSensIcons = [
			['plus', 'minus', 'check', 'cross', 'forbidden'],
			['thin plus', 'thin cross'],
			['error','warning','help', 'help outline', 'rejected', "completion pie", "flag"],
			["ellipsis", "list", "tree list", "mosaic", "nine tiles", "tiles", "org chart", "blocks", "filter", "fullscreen", "fullscreen exit"],
			['lock', 'unlock'],
		];

		$scope.contextInsensIcons = [
			['attachment', 'files', "email", "phone", "notification", "camera", "settings", "sliders", "gallery", "calendar", "key", "simple key", "history", "clock", "timer", "pin", "location", "comment", "branch", "analytics"],
			["edit", "edit frame", "edit mini", "customize", "download", "upload", "outside", "send", "search", "trash", "refresh", "printer"],
			["pristine imported item", "imported item", "synchronization"],
			["user", "add user", "remove user", "to user", "group", "roles"],
			["flash"],
			["bookmark", "add bookmark", "remove bookmark"],
			["watch", "unwatch"],
		];

		$scope.mouseIcons = [
			['drag', 'drag2'],
			['move','move horizontally','move vertically']
		];

		$scope.arrowIcons = [
			['north chevron','east chevron','south chevron','west chevron'],
			['north arrow','east arrow','south arrow','west arrow'],
			['thin north arrow','thin east arrow','thin south arrow','thin west arrow']
		];

		$scope.speIcons = [
			["breakfast", "coffee", "meal", "birthday", "lunch", "diner", "drink", "snack"],
			["car", "clean car", "taxi", "bus", "subway", "truck", "train", "plane"],
			["euro toll", "dollar toll", "parking", "milestone", "mileage", "gasoline"],
			["journey", "luggage", "hotel", "postage"],
			["euro", "dollar", "quantity", "piggy bank", "bank card", "pricetag", "payment", "import cb"],
			["heart", "broken heart", "star"],
			["computer", "computer mouse", "headphones", "database"],
			["tools", "iron", "jumping cc"],
		];
	}]);
})();
<|endoftext|>


<commit_before>import React from 'react'
import styled from 'styled-components'

const LINK_SIZE = '34px'

const LuckyDice = styled.button`
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: ${LINK_SIZE};
  height: ${LINK_SIZE};
  background-color: initial;
  box-shadow: none !important;
  margin-right: 0.5rem;
`

const LuckyLink = styled.a`
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: ${LINK_SIZE};
  height: ${LINK_SIZE};
  background-color: initial;
  box-shadow: none !important;
  margin-right: 0.5rem;
`

const Coupon = styled.div`
  position: absolute;
  width: 160px;
  top: 0;
  right: 0;
  font-size: 16px;

  a {
    box-shadow: none !important;
  }
`

const randomCoupons = [
  {
    link:
      'https://www.banggood.com/Foxeer-Micro-Falkor-1_8mm-1200TVL-16943-PALNTSC-Switchable-GWDR-FPV-Camera-for-RC-Drone-p-1375560.html?ID=521800&cur_warehouse=CN',
    coupon: 'BGFal',
  },
  {
    link:
      'https://www.banggood.com/URUAV-Lollipop-5_8GHz-2_3dBi-Super-Mini-Antenna-RHCP-SMA-Male-RP-SMA-Male-For-FPV-Racing-Drone-p-1420138.html?ID=224512670&cur_warehouse=CN',
    coupon: 'BGANTA',
  },
  {
    link:
      'https://www.banggood.com/Eachine-ROTG01-Pro-UVC-OTG-5_8G-150CH-Full-Channel-FPV-Receiver-WAudio-For-Android-Smartphone-p-1347396.html?akmClientCountry=CN&&ID=521800&cur_warehouse=CN',
    coupon: 'BGROTG01',
  },
  {
    link:
      'https://www.banggood.com/Caddx-Turbo-Micro-F2-13-CMOS-2_1mm-1200TVL-16943-NTSCPAL-Low-Latency-FPV-Camera-W-Microphone-p-1328481.html?akmClientCountry=CN&&ID=231530499&cur_warehouse=CN',
    coupon: 'BGTurbo',
  },
  {
    link:
      'https://www.banggood.com/RunCam-Nano-2-13-700TVL-1_8mm2_1mm-FOV-155170-Degree-CMOS-FPV-Camera-for-FPV-RC-Drone-p-1469656.html?akmClientCountry=CN&&ID=530889522009&cur_warehouse=CN',
    coupon: 'BGNano22',
  },
  {
    link:
      'https://www.banggood.com/Realacc-Fireproof-Waterproof-Lipo-Battery-Safety-Bag155x115x90mm-With-Luminous-Handle-p-1259311.html?akmClientCountry=CN&&cur_warehouse=CN',
    coupon: 'BGBag22',
  },
]

const affiliateParam = 'p=NY211410857261201705'

const Lucky = () => {
  const [showCoupon, setShowCoupon] = React.useState(false)
  const luckyDraw =
    randomCoupons[Math.floor(Math.random() * randomCoupons.length)]

  return (
    <>
      {showCoupon ? (

          <Coupon>
            Link:
            <a
              href={`${luckyDraw.link}&${affiliateParam}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Daily random coupon"
              title="I'm feeling lucky! (daily random coupon)"
            >
              🎁

              Coupon: {luckyDraw.coupon}

          </Coupon>

      ) : (
        <LuckyDice
          onClick={() => setShowCoupon(true)}
          target="_blank"
          rel="noopener noreferrer"
          aria-label="Daily random coupon"
          title="I'm feeling lucky! (daily random coupon)"
        >
          🎲
        </LuckyDice>
      )}
    </>
  )
}

export default Lucky
<commit_msg>Add new random coupon entry<commit_after>import React from 'react'
import styled from 'styled-components'

const LINK_SIZE = '34px'

const LuckyDice = styled.button`
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: ${LINK_SIZE};
  height: ${LINK_SIZE};
  background-color: initial;
  box-shadow: none !important;
  margin-right: 0.5rem;
`

const LuckyLink = styled.a`
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: ${LINK_SIZE};
  height: ${LINK_SIZE};
  background-color: initial;
  box-shadow: none !important;
  margin-right: 0.5rem;
`

const Coupon = styled.div`
  position: absolute;
  width: 160px;
  top: 0;
  right: 0;
  font-size: 16px;

  a {
    box-shadow: none !important;
  }
`

const randomCoupons = [
  {
    link:
      'https://www.banggood.com/Foxeer-Micro-Falkor-1_8mm-1200TVL-16943-PALNTSC-Switchable-GWDR-FPV-Camera-for-RC-Drone-p-1375560.html?ID=521800&cur_warehouse=CN',
    coupon: 'BGFal',
  },
  {
    link:
      'https://www.banggood.com/URUAV-Lollipop-5_8GHz-2_3dBi-Super-Mini-Antenna-RHCP-SMA-Male-RP-SMA-Male-For-FPV-Racing-Drone-p-1420138.html?ID=224512670&cur_warehouse=CN',
    coupon: 'BGANTA',
  },
  {
    link:
      'https://www.banggood.com/Eachine-ROTG01-Pro-UVC-OTG-5_8G-150CH-Full-Channel-FPV-Receiver-WAudio-For-Android-Smartphone-p-1347396.html?akmClientCountry=CN&&ID=521800&cur_warehouse=CN',
    coupon: 'BGROTG01',
  },
  {
    link:
      'https://www.banggood.com/Caddx-Turbo-Micro-F2-13-CMOS-2_1mm-1200TVL-16943-NTSCPAL-Low-Latency-FPV-Camera-W-Microphone-p-1328481.html?akmClientCountry=CN&&ID=231530499&cur_warehouse=CN',
    coupon: 'BGTurbo',
  },
  {
    link:
      'https://www.banggood.com/RunCam-Nano-2-13-700TVL-1_8mm2_1mm-FOV-155170-Degree-CMOS-FPV-Camera-for-FPV-RC-Drone-p-1469656.html?akmClientCountry=CN&&ID=530889522009&cur_warehouse=CN',
    coupon: 'BGNano22',
  },
  {
    link:
      'https://www.banggood.com/Realacc-Fireproof-Waterproof-Lipo-Battery-Safety-Bag155x115x90mm-With-Luminous-Handle-p-1259311.html?akmClientCountry=CN&&cur_warehouse=CN',
    coupon: 'BGBag22',
  },
  {
    link:
      'https://www.banggood.com/marketing-FPV-Racing-Drone-Multirotors-Clearance/tid-5415.html?bid=22225',
    coupon: '28rc',
  },
]

const affiliateParam = 'p=NY211410857261201705'

const Lucky = () => {
  const [showCoupon, setShowCoupon] = React.useState(false)
  const luckyDraw =
    randomCoupons[Math.floor(Math.random() * randomCoupons.length)]

  return (
    <>
      {showCoupon ? (

          <Coupon>
            Link:
            <a
              href={`${luckyDraw.link}&${affiliateParam}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Daily random coupon"
              title="I'm feeling lucky! (daily random coupon)"
            >
              🎁

              Coupon: {luckyDraw.coupon}

          </Coupon>

      ) : (
        <LuckyDice
          onClick={() => setShowCoupon(true)}
          target="_blank"
          rel="noopener noreferrer"
          aria-label="Daily random coupon"
          title="I'm feeling lucky! (daily random coupon)"
        >
          🎲
        </LuckyDice>
      )}
    </>
  )
}

export default Lucky
<|endoftext|>


<commit_before>// DATASHEET CONFIG
var DATASHEET = "nst_2011.csv";
var DATA_DIRECTORY = "data/";
var DATA = DATA_DIRECTORY + DATASHEET;
var USER_CSV; // holds object containing .csv file
var CSV_URL; // DOMString containing URL representing USER_CSV
var USER_SESSION_COOKIE;

var fields;
var states;

//Return usable object from CSV file
function getCSVFields(callback) {
  var dataset = Papa.parse(USER_CSV, {
    download: true,
    complete: function(results) {
      return parseFields(results.data, callback);
    }
  });
  CSV_URL = URL.createObjectURL(USER_CSV); // create URL representing USER_CSV
}

function generate_session_id(length) {
  var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  var result = '';
  for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
  return result;
}

function writeToServer(session_id, string_to_save){
  var data = new FormData();
  data.append("data" , string_to_save);
  data.append("name", session_id);
  var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
  xhr.open( 'post', 'php/import_settings.php', true );
  xhr.send(data);
}

function readFromServer(session_id){
  return $.get("php/export_settings.php", function(session_id){return session_id;}, "text");

  /*
  var data = new FormData();
  data.append("name", session_id);
  var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
  xhr.open( 'post', 'php/export_settings.php', true );
  xhr.send(data);
  */
}

//Send fields array back inside the called function
function parseFields(data, callback) {
  fields = [];
  fields.push({
    name: "None",
    id: "none"
  });
  for (var i = 0; i < data[0].length; i++) {
    var field = data[0][i];
    fields.push({
      name: field,
      id: field,
      key: field
    });
  }
  callback(fields);
}

//no idea what this does yet, to be honest. I'm assuming something on the browser side
function updateZoom() {
  var scale = zoom.scale();
  layer.attr("transform",
    "translate(" + zoom.translate() + ") " +
    "scale(" + [scale, scale] + ")");
}

//get  from the nitty gritty cartogram function in cartogram.js
function initTopo() {
  var features = carto.features(topology, geometries),
    path = d3.geo.path()
    .projection(proj); //d3.geo.path is d3's main drawing function
  states = states.data(features)
    .enter()
    .append("path")
    .attr("class", "state")
    .attr("id", function(d) {
      return d.properties.NAME;
    })
    .attr("fill", "#fff")
    .attr("d", path);

  states.append("title");

  parseHash();
}

/*
 * Original graph that is loaded
 */
function reset() {
  stat.text("");
  body.classed("updating", false);

  var features = carto.features(topology, geometries),
    path = d3.geo.path()
    .projection(proj);

  states.data(features)
    .transition()
    .duration(750)
    .ease("linear")
    .attr("fill", "#fff")
    .attr("d", path);

  states.select("title")
    .text(function(d) {
      return d.properties.NAME;
    });
}

function update() {
  var start = Date.now();
  //body.classed("updating", true);

  var key = field.key;
  var fmt = (typeof field.format === "function") ?
    field.format :
    d3.format(field.format || ","),
    value = function(d) {
      return +d.properties[key];
    },
    values = states.data()
    .map(value)
    .filter(function(n) {
      return !isNaN(n);
    })
    .sort(d3.ascending),
    lo = values[0],
    hi = values[values.length - 1];

  var color = d3.scale.linear()
    .range(colors)
    .domain(lo < 0 ? [lo, 0, hi] : [lo, d3.mean(values), hi]);

  // normalize the scale to positive numbers
  var scale = d3.scale.linear()
    .domain([lo, hi])
    .range([1, 1000]);

  // tell the cartogram to use the scaled values
  carto.value(function(d) {
    return scale(value(d));
  });

  // generate the new features, pre-projected
  var features = carto(topology, geometries).features;

  console.log("update", states);
  // update the data
  states.data(features)
    .select("title")
    .text(function(d) {
      return [d.properties.NAME, fmt(value(d))].join(": ");
    });

  states.transition()
    .duration(750)
    .ease("linear")
    .attr("fill", function(d) {
      return color(value(d));
    })
    .attr("d", carto.path);

  var delta = (Date.now() - start) / 1000;
  //stat.text(["calculated in", delta.toFixed(1), "seconds"].join(" "));
  console.log("Cartogram calculated in " + delta.toFixed(1) + " seconds");
  //$('select').material_select();
  //body.classed("updating", false);
}

function parseHash(fieldsById) {
  var parts = location.hash.substr(1).split("/"),
    desiredFieldId = parts[0],
    desiredYear = +parts[1];

  var field = fieldsById[desiredFieldId] || fields[0];
  //year = (years.indexOf(desiredYear) > -1) ? desiredYear : years[0];

  fieldSelect.property("selectedIndex", fields.indexOf(field));

  if (field.id === "none") {

    //yearSelect.attr("disabled", "disabled");
    reset();

  } else
    /*
            if (field.years) {
                if (field.yecs.indexOf(year) === -1) {
                    year = field.years[0];
                }
                yearSelect.selectAll("option")
                    .attr("disabled", function(y) {
                        return (field.years.indexOf(y) === -1) ? "disabled" : null;
                    });
            } else {
                yearSelect.selectAll("option")
                    .attr("disabled", null);
            }

            yearSelect
                .property("selectedIndex", years.indexOf(year))
                .attr("disabled", null);
    */
    deferredUpdate();
    location.replace("#" + field.id);

    hashish.attr("href", function(href) {
      return href + location.hash;
    });
  }

//Inital map setup
var map = d3.select("#map"),
  zoom = d3.behavior.zoom()
  .translate([-38, 32])
  .scale(.94)
  .scaleExtent([0.5, 10.0])
  .on("zoom", updateZoom),
  layer = map.append("g")
  .attr("id", "layer"),
  states = layer.append("g")
  .attr("id", "states")
  .selectAll("path");

updateZoom();
<commit_msg>reading file back from server as string<commit_after>// DATASHEET CONFIG
var DATASHEET = "nst_2011.csv";
var DATA_DIRECTORY = "data/";
var DATA = DATA_DIRECTORY + DATASHEET;
var USER_CSV; // holds object containing .csv file
var CSV_URL; // DOMString containing URL representing USER_CSV
var USER_SESSION_COOKIE;

var fields;
var states;

//Return usable object from CSV file
function getCSVFields(callback) {
  var dataset = Papa.parse(USER_CSV, {
    download: true,
    complete: function(results) {
      return parseFields(results.data, callback);
    }
  });
  CSV_URL = URL.createObjectURL(USER_CSV); // create URL representing USER_CSV
}

function generate_session_id(length) {
  var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  var result = '';
  for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
  return result;
}

function writeToServer(session_id, string_to_save){
  var data = new FormData();
  data.append("data" , string_to_save);
  data.append("name", session_id);
  var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
  xhr.open( 'post', 'php/import_settings.php', true );
  xhr.send(data);
}

function readFromServer(session_id){
  var return_string;
  $.get("php/export_settings.php", function(session_id){return_string = session_id;}, "text");
  return return_string;

  /*
  var data = new FormData();
  data.append("name", session_id);
  var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
  xhr.open( 'post', 'php/export_settings.php', true );
  xhr.send(data);
  */
}

//Send fields array back inside the called function
function parseFields(data, callback) {
  fields = [];
  fields.push({
    name: "None",
    id: "none"
  });
  for (var i = 0; i < data[0].length; i++) {
    var field = data[0][i];
    fields.push({
      name: field,
      id: field,
      key: field
    });
  }
  callback(fields);
}

//no idea what this does yet, to be honest. I'm assuming something on the browser side
function updateZoom() {
  var scale = zoom.scale();
  layer.attr("transform",
    "translate(" + zoom.translate() + ") " +
    "scale(" + [scale, scale] + ")");
}

//get  from the nitty gritty cartogram function in cartogram.js
function initTopo() {
  var features = carto.features(topology, geometries),
    path = d3.geo.path()
    .projection(proj); //d3.geo.path is d3's main drawing function
  states = states.data(features)
    .enter()
    .append("path")
    .attr("class", "state")
    .attr("id", function(d) {
      return d.properties.NAME;
    })
    .attr("fill", "#fff")
    .attr("d", path);

  states.append("title");

  parseHash();
}

/*
 * Original graph that is loaded
 */
function reset() {
  stat.text("");
  body.classed("updating", false);

  var features = carto.features(topology, geometries),
    path = d3.geo.path()
    .projection(proj);

  states.data(features)
    .transition()
    .duration(750)
    .ease("linear")
    .attr("fill", "#fff")
    .attr("d", path);

  states.select("title")
    .text(function(d) {
      return d.properties.NAME;
    });
}

function update() {
  var start = Date.now();
  //body.classed("updating", true);

  var key = field.key;
  var fmt = (typeof field.format === "function") ?
    field.format :
    d3.format(field.format || ","),
    value = function(d) {
      return +d.properties[key];
    },
    values = states.data()
    .map(value)
    .filter(function(n) {
      return !isNaN(n);
    })
    .sort(d3.ascending),
    lo = values[0],
    hi = values[values.length - 1];

  var color = d3.scale.linear()
    .range(colors)
    .domain(lo < 0 ? [lo, 0, hi] : [lo, d3.mean(values), hi]);

  // normalize the scale to positive numbers
  var scale = d3.scale.linear()
    .domain([lo, hi])
    .range([1, 1000]);

  // tell the cartogram to use the scaled values
  carto.value(function(d) {
    return scale(value(d));
  });

  // generate the new features, pre-projected
  var features = carto(topology, geometries).features;

  console.log("update", states);
  // update the data
  states.data(features)
    .select("title")
    .text(function(d) {
      return [d.properties.NAME, fmt(value(d))].join(": ");
    });

  states.transition()
    .duration(750)
    .ease("linear")
    .attr("fill", function(d) {
      return color(value(d));
    })
    .attr("d", carto.path);

  var delta = (Date.now() - start) / 1000;
  //stat.text(["calculated in", delta.toFixed(1), "seconds"].join(" "));
  console.log("Cartogram calculated in " + delta.toFixed(1) + " seconds");
  //$('select').material_select();
  //body.classed("updating", false);
}

function parseHash(fieldsById) {
  var parts = location.hash.substr(1).split("/"),
    desiredFieldId = parts[0],
    desiredYear = +parts[1];

  var field = fieldsById[desiredFieldId] || fields[0];
  //year = (years.indexOf(desiredYear) > -1) ? desiredYear : years[0];

  fieldSelect.property("selectedIndex", fields.indexOf(field));

  if (field.id === "none") {

    //yearSelect.attr("disabled", "disabled");
    reset();

  } else
    /*
            if (field.years) {
                if (field.yecs.indexOf(year) === -1) {
                    year = field.years[0];
                }
                yearSelect.selectAll("option")
                    .attr("disabled", function(y) {
                        return (field.years.indexOf(y) === -1) ? "disabled" : null;
                    });
            } else {
                yearSelect.selectAll("option")
                    .attr("disabled", null);
            }

            yearSelect
                .property("selectedIndex", years.indexOf(year))
                .attr("disabled", null);
    */
    deferredUpdate();
    location.replace("#" + field.id);

    hashish.attr("href", function(href) {
      return href + location.hash;
    });
  }

//Inital map setup
var map = d3.select("#map"),
  zoom = d3.behavior.zoom()
  .translate([-38, 32])
  .scale(.94)
  .scaleExtent([0.5, 10.0])
  .on("zoom", updateZoom),
  layer = map.append("g")
  .attr("id", "layer"),
  states = layer.append("g")
  .attr("id", "states")
  .selectAll("path");

updateZoom();
<|endoftext|>


<commit_before>var game=game||{};
game.resources = {};
game.tick = function() {
  for(var count=0;count<this.resources;count++) {
    this.resources[count].update();
  }
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
game.buttons = document.getElementsByTagName('body')[0];
game.labels = document.getElementsByTagName('body')[0];
function increase(event) {
 event = event || window.event;
 if(game.resources["gold"].value > 100*Math.pow(1.1,game.resources["house"].value)) {
    game.resources["gold"].decrease(100*Math.pow(1.1,game.resources["house"].value));
    game.resources["house"].increase();
    event.target.innerHTML = "Buy House: " + 100*Math.pow(1.1,game.resources["house"].value);
 }
}
function tick() {
  game.resources["gold"].value+=0.1*game.resources["house"].value+0.0001;
}
function add(){
  game.resources["gold"].value++;
}

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick?onClick:function(){};
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
  game.labels.appendChild(this.label);
  game.buttons.appendChild(this.button);
  game.resources[this.name] = this;
}
game.resource('gold',50,
              function(){ game.resources["gold"].value+=0.1*game.resources["house"].value+0.0001;},
              function(){ game.resources["gold"].value++;},
              'Mine gold')
game.resource('house',0,null, increase,'Buy House')
<commit_msg>Update game.js<commit_after>var game=game||{};
game.resources = {};
game.tick = function() {
  for(var count=0;count<this.resources;count++) {
    this.resources[count].update();
  }
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
game.buttons = document.getElementsByTagName('body')[0];
game.labels = document.getElementsByTagName('body')[0];
function increase(event) {
 event = event || window.event;
 if(game.resources["gold"].value > 100*Math.pow(1.1,game.resources["house"].value)) {
    game.resources["gold"].decrease(100*Math.pow(1.1,game.resources["house"].value));
    game.resources["house"].increase();
    event.target.innerHTML = "Buy House: " + 100*Math.pow(1.1,game.resources["house"].value);
 }
}

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick?onClick:function(){};
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
  game.labels.appendChild(this.label);
  game.buttons.appendChild(this.button);
  game.resources[this.name] = this;
}
game.resource('gold',50,
              function(){ game.resources["gold"].value+=0.1*game.resources["house"].value+0.0001;},
              function(){ game.resources["gold"].value++;},
              'Mine gold')
game.resource('house',0,null, increase,'Buy House')
<|endoftext|>