<commit_before>import { updateChatSession } from '../actionCreators';
import { tripDialogReply } from '../tripDialog';
import { extractEntities } from '../fuzzy';
import { WitDriver } from 'calamars';
const { getEntityValue, getEntityMeta } = WitDriver;

const placesConfidenceThreshold = 0.77;

const checkConfidences = ({ origin, destination, unknownPlace }) => {
    const hasDestination = (destination && destination.confidence >= placesConfidenceThreshold);
    const hasOrigin = (origin && origin.confidence >= placesConfidenceThreshold);
    const hasUnknownPlace = (
        unknownPlace && unknownPlace.confidence >= placesConfidenceThreshold
    );
    return { hasDestination, hasOrigin, hasUnknownPlace };
};

const routes = [[
    outcomes => {
        const hasTripIntent = getEntityValue(outcomes, 'trip') === 'info';
        const { origin, destination, unknownPlace } = extractEntities(outcomes);
        const {
            hasDestination, hasOrigin, hasUnknownPlace
        } = checkConfidences({
            origin, destination, unknownPlace
        });
        return hasTripIntent
            || hasDestination
            || hasOrigin
            || hasUnknownPlace;
    },
    (outcomes, { store, chat } = {}) => {
        const {
            origin,
            origins,
            originMeta,
            destination,
            destinationMeta,
            unknownPlace,
            unknownPlaces,
            timeFilter,
            busTypeFilters,
            priceFilter
        } = extractEntities(outcomes);
        const context = chat && chat.session ? chat.session : {};
        let nextContext = Object.assign({}, context);
        if (timeFilter) {
            nextContext.timeFilter = timeFilter;
        }
        if (busTypeFilters && busTypeFilters.length) {
            nextContext.busTypeFilters = busTypeFilters;
        }
        if (priceFilter) {
            nextContext.priceFilter = priceFilter;
        }
        if (destination && destination.confidence >= placesConfidenceThreshold) {
            nextContext.destination = destination.value;
            nextContext.destinationMeta = destinationMeta;
        }
        if (origin && origin.confidence >= placesConfidenceThreshold) {
            nextContext.origin = origin.value;
            nextContext.originMeta = originMeta;
            if (!destination) {
                if (
                    origins && origins.length > 1 &&
                    origins[1].confidence >= placesConfidenceThreshold
                ) {
                    nextContext.destination = origins[1].value;
                    nextContext.destinationMeta = getEntityMeta(origins[1]);
                } else if (unknownPlace) {
                    nextContext.destination = unknownPlace.value;
                    nextContext.destinationMeta = getEntityMeta(unknownPlace);
                }
            }
        }
        if (!origin && !destination && unknownPlaces && unknownPlaces.length > 1) {
            console.log('[issue #25]: 2 places and no role');
            nextContext.origin = unknownPlaces[0].value;
            nextContext.originMeta = getEntityMeta(unknownPlaces[0]);
            nextContext.destination = unknownPlaces[1].value;
            nextContext.destinationMeta = getEntityMeta(unknownPlaces[1]);
        }
        if (unknownPlaces && nextContext.destination && !nextContext.origin) {
            nextContext.origin = unknownPlaces[0].value;
            nextContext.originMeta = getEntityMeta(unknownPlaces[0]);
        }
        if (
            (unknownPlaces && nextContext.origin && !nextContext.destination)
            || (unknownPlaces && !nextContext.origin && !nextContext.destination)
        ) {
            nextContext.destination = unknownPlaces[0].value;
            nextContext.destinationMeta = getEntityMeta(unknownPlaces[0]);
        }
        if (store) {
            store.dispatch(updateChatSession({
                chat: { ...chat, session: nextContext }
            }));
        }
        return tripDialogReply(nextContext);
    }
], [
    outcomes => {
        const {
            unknownPlace,
            origin,
            destination,
            busTypeFilters,
            priceFilter,
            timeFilter
        } = extractEntities(outcomes);
        const {
            hasDestination, hasOrigin, hasUnknownPlace
        } = checkConfidences({
            origin, destination, unknownPlace
        });

        const result = (
            hasDestination ||
            hasOrigin ||
            hasUnknownPlace ||
            busTypeFilters ||
            priceFilter ||
            timeFilter
        );
        return result;
    },
    (outcomes, { store, chat } = {}) => {
        const context = chat && chat.session ? chat.session : {};
        const {
            unknownPlace,
            origin,
            destination,
            busTypeFilters,
            priceFilter,
            timeFilter
        } = extractEntities(outcomes);
        const {
            hasDestination, hasOrigin, hasUnknownPlace
        } = checkConfidences({
            origin, destination, unknownPlace
        });
        const unknownPlaceMeta = getEntityMeta(unknownPlace);
        let nextContext = Object.assign({}, context);
        if (timeFilter) {
            nextContext.timeFilter = timeFilter;
        }
        if (busTypeFilters && busTypeFilters.length) {
            nextContext.busTypeFilters = busTypeFilters;
        }
        if (priceFilter) {
            nextContext.priceFilter = priceFilter;
        }
        if (hasOrigin) {
            // console.log('1 origin', origin);
            if (hasUnknownPlace) {
                // console.log('1.1 origin + place', origin, unknownPlace);
                nextContext.origin = origin.value;
                nextContext.originMeta = getEntityMeta(origin);
                nextContext.destination = unknownPlace.value;
                nextContext.destinationMeta = getEntityMeta(unknownPlace);
            } else if (!context.destination && context.origin) {
                // console.log('2 origin with context missing destination', origin);
                nextContext.destination = origin.value;
                nextContext.destinationMeta = getEntityMeta(origin);
            } else {
                // console.log('3 origin ignoring what is already in context', origin);
                nextContext.origin = origin.value;
                nextContext.originMeta = getEntityMeta(origin);
            }
        } else {
            // console.log('4 not origin', destination, unknownPlace);
            if (hasUnknownPlace && hasDestination) {
                // console.log('5 not origin, destination and unknowPlace');
                nextContext.origin = unknownPlace.value;
                nextContext.originMeta = unknownPlaceMeta;
            }
            if (hasUnknownPlace && context.destination && !context.origin) {
                // console.log('6 not origin, unknowPlace and the context has only destination');
                nextContext.origin = unknownPlace.value;
                nextContext.originMeta = unknownPlaceMeta;
            }
        }
        if (hasDestination) {
            // console.log('7 destination', destination, destination.confidence);
            nextContext.destination = destination.value;
            nextContext.destinationMeta = getEntityMeta(destination);
        } else {
            // console.log('8 not destination, unknowPlace and the context has only destination');
            if (
                (hasUnknownPlace && !context.destination && context.origin) ||
                (hasUnknownPlace && !context.destination && !context.origin && !origin)
            ) {
                // console.log('9 not dest, unknowPlace and the context has nothing or only origin');
                nextContext.destination = unknownPlace.value;
                nextContext.destinationMeta = unknownPlaceMeta;
            }
        }
        // console.log('=====nextContext', nextContext);
        if (store) {
            store.dispatch(updateChatSession({
                chat: { ...chat, session: nextContext }
            }));
        }
        return tripDialogReply(nextContext);
    }
]];
export default routes;
<commit_msg>lower confidence threshold when there is partial filled context<commit_after>import { updateChatSession } from '../actionCreators';
import { tripDialogReply } from '../tripDialog';
import { extractEntities } from '../fuzzy';
import { WitDriver } from 'calamars';
const { getEntityValue, getEntityMeta } = WitDriver;

const confidence = 0.77;
const confidenceToFillContext = 0.7;

const checkConfidences = ({ origin, destination, unknownPlace }, context) => {
    const hasContext = context !== undefined;
    const destNotInContext = hasContext && !context.destination;
    const originNotInContext = hasContext && !context.origin;
    const placesNotInContext = hasContext && (
        context.origin && !context.destination ||
        context.destination && !context.origin
    );
    const destConfidence = destNotInContext ? confidenceToFillContext : confidence;
    const originConfidence = originNotInContext ? confidenceToFillContext : confidence;
    const placeConfidence = placesNotInContext ? confidenceToFillContext : confidence;
    const hasDestination = (destination && destination.confidence >= destConfidence);
    const hasOrigin = (origin && origin.confidence >= originConfidence);
    const hasUnknownPlace = (
        unknownPlace && unknownPlace.confidence >= placeConfidence
    );
    return { hasDestination, hasOrigin, hasUnknownPlace };
};

const routes = [[
    outcomes => {
        const hasTripIntent = getEntityValue(outcomes, 'trip') === 'info';
        const { origin, destination, unknownPlace } = extractEntities(outcomes);
        const {
            hasDestination, hasOrigin, hasUnknownPlace
        } = checkConfidences({
            origin, destination, unknownPlace
        });
        // console.log('no trip match function result', hasTripIntent, hasDestination, hasOrigin, hasUnknownPlace)
        return hasTripIntent
            || hasDestination
            || hasOrigin
            || hasUnknownPlace;
    },
    (outcomes, { store, chat } = {}) => {
        // console.log('---- trip intent ---');
        const {
            origin,
            origins,
            originMeta,
            destination,
            destinationMeta,
            unknownPlace,
            unknownPlaces,
            timeFilter,
            busTypeFilters,
            priceFilter
        } = extractEntities(outcomes);
        const context = chat && chat.session ? chat.session : {};
        let nextContext = Object.assign({}, context);
        if (timeFilter) {
            nextContext.timeFilter = timeFilter;
        }
        if (busTypeFilters && busTypeFilters.length) {
            nextContext.busTypeFilters = busTypeFilters;
        }
        if (priceFilter) {
            nextContext.priceFilter = priceFilter;
        }
        if (destination && destination.confidence >= confidence) {
            nextContext.destination = destination.value;
            nextContext.destinationMeta = destinationMeta;
        }
        if (origin && origin.confidence >= confidence) {
            nextContext.origin = origin.value;
            nextContext.originMeta = originMeta;
            if (!destination) {
                if (
                    origins && origins.length > 1 &&
                    origins[1].confidence >= confidence
                ) {
                    nextContext.destination = origins[1].value;
                    nextContext.destinationMeta = getEntityMeta(origins[1]);
                } else if (unknownPlace) {
                    nextContext.destination = unknownPlace.value;
                    nextContext.destinationMeta = getEntityMeta(unknownPlace);
                }
            }
        }
        if (!origin && !destination && unknownPlaces && unknownPlaces.length > 1) {
            // console.log('[issue #25]: 2 places and no role');
            nextContext.origin = unknownPlaces[0].value;
            nextContext.originMeta = getEntityMeta(unknownPlaces[0]);
            nextContext.destination = unknownPlaces[1].value;
            nextContext.destinationMeta = getEntityMeta(unknownPlaces[1]);
        }
        if (unknownPlaces && nextContext.destination && !nextContext.origin) {
            nextContext.origin = unknownPlaces[0].value;
            nextContext.originMeta = getEntityMeta(unknownPlaces[0]);
        }
        if (
            (unknownPlaces && nextContext.origin && !nextContext.destination)
            || (unknownPlaces && !nextContext.origin && !nextContext.destination)
        ) {
            nextContext.destination = unknownPlaces[0].value;
            nextContext.destinationMeta = getEntityMeta(unknownPlaces[0]);
        }
        if (store) {
            store.dispatch(updateChatSession({
                chat: { ...chat, session: nextContext }
            }));
        }
        return tripDialogReply(nextContext);
    }
], [
    (outcomes, { chat } = {}) => {
        const context = chat && chat.session ? chat.session : {};
        const {
            unknownPlace,
            origin,
            destination,
            busTypeFilters,
            priceFilter,
            timeFilter
        } = extractEntities(outcomes);
        const {
            hasDestination, hasOrigin, hasUnknownPlace
        } = checkConfidences({
            origin, destination, unknownPlace
        }, context);

        const result = (
            hasDestination ||
            hasOrigin ||
            hasUnknownPlace ||
            busTypeFilters ||
            priceFilter ||
            timeFilter
        );
        return result;
    },
    (outcomes, { store, chat } = {}) => {
        // console.log('---- no trip intent ---');
        const context = chat && chat.session ? chat.session : {};
        const {
            unknownPlace,
            origin,
            destination,
            busTypeFilters,
            priceFilter,
            timeFilter
        } = extractEntities(outcomes);
        const {
            hasDestination, hasOrigin, hasUnknownPlace
        } = checkConfidences({
            origin, destination, unknownPlace
        }, context);
        const unknownPlaceMeta = getEntityMeta(unknownPlace);
        let nextContext = Object.assign({}, context);
        if (timeFilter) {
            nextContext.timeFilter = timeFilter;
        }
        if (busTypeFilters && busTypeFilters.length) {
            nextContext.busTypeFilters = busTypeFilters;
        }
        if (priceFilter) {
            nextContext.priceFilter = priceFilter;
        }
        if (hasOrigin) {
            // console.log('1 origin', origin);
            if (hasUnknownPlace) {
                // console.log('1.1 origin + place', origin, unknownPlace);
                nextContext.origin = origin.value;
                nextContext.originMeta = getEntityMeta(origin);
                nextContext.destination = unknownPlace.value;
                nextContext.destinationMeta = getEntityMeta(unknownPlace);
            } else if (!context.destination && context.origin) {
                // console.log('2 origin with context missing destination', origin);
                nextContext.destination = origin.value;
                nextContext.destinationMeta = getEntityMeta(origin);
            } else {
                // console.log('3 origin ignoring what is already in context', origin);
                nextContext.origin = origin.value;
                nextContext.originMeta = getEntityMeta(origin);
            }
        } else {
            // console.log('4 not origin', destination, unknownPlace);
            if (hasUnknownPlace && hasDestination) {
                // console.log('5 not origin, destination and unknowPlace');
                nextContext.origin = unknownPlace.value;
                nextContext.originMeta = unknownPlaceMeta;
            }
            if (hasUnknownPlace && context.destination && !context.origin) {
                // console.log('6 not origin, unknowPlace and the context has only destination');
                nextContext.origin = unknownPlace.value;
                nextContext.originMeta = unknownPlaceMeta;
            }
        }
        if (hasDestination) {
            // console.log('7 destination', destination, destination.confidence);
            nextContext.destination = destination.value;
            nextContext.destinationMeta = getEntityMeta(destination);
        } else {
            // console.log('8 not destination, unknowPlace and the context has only destination');
            if (
                (hasUnknownPlace && !context.destination && context.origin) ||
                (hasUnknownPlace && !context.destination && !context.origin && !origin)
            ) {
                // console.log('9 not dest, unknowPlace and the context has nothing or only origin');
                nextContext.destination = unknownPlace.value;
                nextContext.destinationMeta = unknownPlaceMeta;
            }
        }
        // console.log('=====nextContext', nextContext);
        if (store) {
            store.dispatch(updateChatSession({
                chat: { ...chat, session: nextContext }
            }));
        }
        return tripDialogReply(nextContext);
    }
]];
export default routes;
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const CryptoJS = require ('crypto-js');

//  ---------------------------------------------------------------------------

module.exports = class coss extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'coss',
            'name': 'COSS',
            'country': [ 'SG', 'NL' ],
            'rateLimit': 1000,
            'version': '1',
            'comment': 'Certified exchange',
            'urls': {
                'logo': 'https://example.com/image.jpg',
                'api': 'https://coss.io/api/v1',
                'www': 'https://coss.io/',
                'doc': [
                    'https://api.coss.io/v1/spec',
                ],
            },
            'api': {
                'engine': {
                    'get': [
                        'dp',
                        'ht',
                    ],
                },
                'trade': {
                    'get': [
                        'exchange-info',
                        'account/balances',
                    ],
                },
            },
        });
    }

    async fetchMarkets () {
        return '';
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let pathArr = (this.urls['api'] + '/' + path).split ('/');
        if (api === 'trade') {
            pathArr[2] = 'trade.' + pathArr[2];
            pathArr.splice (3, 0, 'c');
        } else if (api === 'engine') {
            pathArr[2] = 'engine.' + pathArr[2];
        }
        path = pathArr.join ('/');
        let url = undefined;
        if (method === 'GET' && path.indexOf ('account') < 0) {
            url = path + '?' + this.urlencode (params);
        } else {
            let request = this.urlencode ({ 'timestamp': '10', 'recvWindow': '5000' });
            url = path + '?' + request;
            headers = {
                'Signature': this.hmac (request, CryptoJS.enc.Base64.parse (this.secret), 'sha256', 'hex'),
                'Authorization': this.apiKey,
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<commit_msg>latest<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const CryptoJS = require ('crypto-js');

//  ---------------------------------------------------------------------------

module.exports = class coss extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'coss',
            'name': 'COSS',
            'country': [ 'SG', 'NL' ],
            'rateLimit': 1000,
            'version': 'v1',
            'comment': 'Certified exchange',
            'urls': {
                'logo': 'https://example.com/image.jpg',
                'api': 'https://coss.io/api',
                'www': 'https://coss.io/',
                'doc': [
                    'https://api.coss.io/v1/spec',
                ],
            },
            'api': {
                'engine': {
                    'get': [
                        'dp',
                        'ht',
                    ],
                },
                'trade': {
                    'get': [
                        'exchange-info',
                        'account/balances',
                        'account/details',
                        'getmarketsummaries',
                        'market-price',
                    ],
                },
            },
        });
    }

    async fetchMarkets () {
        return '';
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let pathArray = (this.urls['api'] + '/' + this.version + '/' + path).split ('/');
        if (api === 'trade') {
            pathArray[2] = 'trade.' + pathArray[2];
            pathArray.splice (3, 0, 'c');
        } else if (api === 'engine') {
            pathArray[2] = 'engine.' + pathArray[2];
        }
        path = pathArray.join ('/');
        let url = undefined;
        if (method === 'GET' && path.indexOf ('account') < 0) {
            url = path + '?' + this.urlencode (params);
        } else {
            let request = this.urlencode ({ 'recvWindow': '5000', 'timestamp': this.nonce () });
            url = path + '?' + request;
            headers = {
                'Signature': this.hmac (request, this.secret, 'sha256', 'hex'),
                'Authorization': this.apiKey,
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<|endoftext|>


<commit_before>/*jslint plusplus: true */
"use strict";
var oNewsArticlePager = {
    template: '

@date

@content

',
    socialMediatemplate: "
@title

<svg viewBox='0 0 12 10' preserveAspectRatio='xMidYMid meet'><path class='svg-icon-path' d='M9.1,0.1V2H8C7.6,2,7.3,2.1,7.1,2.3C7,2.4,6.9,2.7,6.9,3v1.4H9L8.8,6.5H6.9V12H4.7V6.5H2.9V4.4h1.8V2.8 c0-0.9,0.3-1.6,0.7-2.1C6,0.2,6.6,0,7.5,0C8.2,0,8.7,0,9.1,0.1z'></path></svg>Share

",

    pageIndex: 0,
    pagesize: 6
}, id, highlightid, sClickedHighlightTitle, iClickedHighlightID,
iTotalNews = 0,
iIterator = 0,
iMaxPageIndex,
oNewsData = null,
oEntryData = null,
oNewsContainer = $("#LoadPageNews"),
oShareContainer = $(".post-header"),
sScrollElement = "body,html",
sLoadingClass = "Loading",
    oItalicBookName = [
                    "What I Did Not Learn in B-School: Insights for New Managers"
                    , "What I Did Not Learn at IIT: Transition from Campus to Workplace"
                    , "What I Did Not Learn at IIT - Transitioning from Campus to Workplace"
    ], iCount, iTotal = oItalicBookName.length, iTotalHighlight = 6, oNewsHighlightTitle = [iTotalHighlight], oHighlightNewsID = [iTotalHighlight];
var newsTitle, newsImageSource;

function readQueryParams() {
    if (/MSIE|Trident/.test(navigator.userAgent)) {
        newsTitle = location.search.split('title=')[1];
    }
    else {
        var params = (new URL(document.location)).searchParams;
        newsTitle = unescape(params.get("title"));
    }
    if (typeof newsTitle !== 'undefined' && newsTitle !== 'null' && newsTitle !== "" && newsTitle !== 'false') {
        loadNewsGrid();
    }
    else {
        window.location.href = "/news.html";
    }
}

window.onload = readQueryParams;

function loadNewsGrid() {
    var iTop;
    oNewsContainer.html("").addClass(sLoadingClass);
    $.ajax({
        url: 'https://www.blogger.com/feeds/2523158019509365490/posts/default/-/News',
        type: 'GET',
        dataType: 'jsonp',
        success: function (sResponse) {
            loadNews(sResponse);
        },
        complete: function () {
            oNewsContainer.removeClass(sLoadingClass);
        }
    });
}
function loadNews(sNewsData) {
    try {
        var parser = new DOMParser();
        var requiredNewsIndex;
        oNewsData = parser.parseFromString(sNewsData, "text/xml");
        oEntryData = oNewsData.getElementsByTagName('entry');
        iTotalNews = oEntryData.length;
        for (var iCount = 0; iCount < iTotalNews; iCount++) {
            if (newsTitle === oEntryData[iCount].getElementsByTagName('title')[0].textContent) {
                requiredNewsIndex = iCount;
                break;
            }
        }
        oEntryData = oEntryData[requiredNewsIndex];
        if (iTotalNews || oNewsData.getElementsByTagName('content')) {
            oNewsContainer.html("").addClass(sLoadingClass);
            renderNews();
        }
    } catch (ignore) {
    }
}
function renderNews() {
    var iStart, iEnd, entry1, sDate, oDatePart, oDate, sTitle, sContent, sRawTitle;
    if (iTotalNews) {

        entry1 = oEntryData;
        if (entry1) {
            sDate = entry1.getElementsByTagName('published')[0].childNodes[0].nodeValue.toLowerCase().split("t");
            oDatePart = [];
            if (sDate[0]) {
                oDatePart = sDate[0].split("-");
            }
            oDate = null;
            if (oDatePart.length === 3) {
                oDate = new Date(oDatePart[0], (oDatePart[1] - 1), oDatePart[2]);
            } else {
                oDate = new Date(sDate[0]);
            }
            oDate = oDate.format();
            sTitle = entry1.getElementsByTagName('title')[0].childNodes[0].nodeValue;
            sRawTitle = sTitle;
            sContent = entry1.getElementsByTagName('content')[0].childNodes[0].nodeValue;
            for (iCount = 0; iCount < iTotal; iCount++) {
                sTitle = sTitle.replace(oItalicBookName[iCount], "" + oItalicBookName[iCount] + "");
            }
            $("#bloggerContent").html(sContent);
            var bloggerContent = document.getElementById("bloggerContent");
            var imgs = bloggerContent.getElementsByTagName('img');
            var img, src = "";

            if (typeof imgs !== "undefined" && imgs.length > 0) {
                img = imgs[0];
                src = img.src;
                newsImageSource = src;
                img.parentNode.removeChild(img);
            }
            sContent = $("#bloggerContent").html();
            oNewsContainer.addClass(sLoadingClass);
            oNewsContainer.append(oNewsArticlePager.template.replace("@date", oDate).replace("@content", sContent).replace(/@newsimagesrc/g, src).replace("@tooltip", getFirstNWordsWithEllipses(sRawTitle, 4)));
            var pageURL = document.location.href;
            setTimeout(function () {
                $(".post-header").append(oNewsArticlePager.socialMediatemplate.replace(/@title/g, sTitle).replace(/@newsimagesrc/g, src).replace("@fbunewslink", pageURL).replace("@newslink", pageURL).replace("@twitternewslink", pageURL).replace("@linkedinnewslink", pageURL)

                                .replace("@lnurl", pageURL)
                                .replace("@linktitle", sRawTitle.substr(0, 200))
                                .replace("@lnsummary", sRawTitle.substr(0, 256))
                                .replace("@lntitle", sRawTitle)
                                .replace("@lnsource", "MAQ Software"));

                FB.XFBML.parse();
            }, 1000);

        }

        oNewsContainer.find("a").attr("target", "_blank");
        oNewsContainer.find("img").addClass("post - media");

        $('#LoadPageNewsArticle *').removeAttr('style');

    }
}

function sharefacebook() {
    shareOverrideOGMeta(newsTitle, newsImageSource);
};
function shareOverrideOGMeta(overrideTitle, overrideImage) {
    var params = (new URL(document.location)).searchParams;
    var newsTitleEnc = encodeURI(params.get("title"));
    FB.ui({
        method: 'share',
        href: "https://maqsoftware.com",
        redirect_uri: "https://maq-akshayak.github.io/news-article" + "?title=" + newsTitleEnc,
        action_type: 'og.shares',
        action_properties: JSON.stringify({
            object: {
                'og:url': "https://maq-akshayak.github.io/news-article" + "?title=" + newsTitleEnc,
                'og:title': overrideTitle,
                'og:image': overrideImage
            }
        })
    },
	function (response) {
	    // Action after response
	});
}

<commit_msg>IE handling for facebook share<commit_after>/*jslint plusplus: true */
"use strict";
var oNewsArticlePager = {
    template: '

@date

@content

',
    socialMediatemplate: "
@title

<svg viewBox='0 0 12 10' preserveAspectRatio='xMidYMid meet'><path class='svg-icon-path' d='M9.1,0.1V2H8C7.6,2,7.3,2.1,7.1,2.3C7,2.4,6.9,2.7,6.9,3v1.4H9L8.8,6.5H6.9V12H4.7V6.5H2.9V4.4h1.8V2.8 c0-0.9,0.3-1.6,0.7-2.1C6,0.2,6.6,0,7.5,0C8.2,0,8.7,0,9.1,0.1z'></path></svg>Share

",

    pageIndex: 0,
    pagesize: 6
}, id, highlightid, sClickedHighlightTitle, iClickedHighlightID,
iTotalNews = 0,
iIterator = 0,
iMaxPageIndex,
oNewsData = null,
oEntryData = null,
oNewsContainer = $("#LoadPageNews"),
oShareContainer = $(".post-header"),
sScrollElement = "body,html",
sLoadingClass = "Loading",
    oItalicBookName = [
                    "What I Did Not Learn in B-School: Insights for New Managers"
                    , "What I Did Not Learn at IIT: Transition from Campus to Workplace"
                    , "What I Did Not Learn at IIT - Transitioning from Campus to Workplace"
    ], iCount, iTotal = oItalicBookName.length, iTotalHighlight = 6, oNewsHighlightTitle = [iTotalHighlight], oHighlightNewsID = [iTotalHighlight];
var newsTitle, newsImageSource;

function readQueryParams() {
    if (/MSIE|Trident/.test(navigator.userAgent)) {
        newsTitle = location.search.split('title=')[1];
    }
    else {
        var params = (new URL(document.location)).searchParams;
        newsTitle = unescape(params.get("title"));
    }
    if (typeof newsTitle !== 'undefined' && newsTitle !== 'null' && newsTitle !== "" && newsTitle !== 'false') {
        loadNewsGrid();
    }
    else {
        window.location.href = "/news.html";
    }
}

window.onload = readQueryParams;

function loadNewsGrid() {
    var iTop;
    oNewsContainer.html("").addClass(sLoadingClass);
    $.ajax({
        url: 'https://www.blogger.com/feeds/2523158019509365490/posts/default/-/News',
        type: 'GET',
        dataType: 'jsonp',
        success: function (sResponse) {
            loadNews(sResponse);
        },
        complete: function () {
            oNewsContainer.removeClass(sLoadingClass);
        }
    });
}
function loadNews(sNewsData) {
    try {
        var parser = new DOMParser();
        var requiredNewsIndex;
        oNewsData = parser.parseFromString(sNewsData, "text/xml");
        oEntryData = oNewsData.getElementsByTagName('entry');
        iTotalNews = oEntryData.length;
        for (var iCount = 0; iCount < iTotalNews; iCount++) {
            if (newsTitle === oEntryData[iCount].getElementsByTagName('title')[0].textContent) {
                requiredNewsIndex = iCount;
                break;
            }
        }
        oEntryData = oEntryData[requiredNewsIndex];
        if (iTotalNews || oNewsData.getElementsByTagName('content')) {
            oNewsContainer.html("").addClass(sLoadingClass);
            renderNews();
        }
    } catch (ignore) {
    }
}
function renderNews() {
    var iStart, iEnd, entry1, sDate, oDatePart, oDate, sTitle, sContent, sRawTitle;
    if (iTotalNews) {

        entry1 = oEntryData;
        if (entry1) {
            sDate = entry1.getElementsByTagName('published')[0].childNodes[0].nodeValue.toLowerCase().split("t");
            oDatePart = [];
            if (sDate[0]) {
                oDatePart = sDate[0].split("-");
            }
            oDate = null;
            if (oDatePart.length === 3) {
                oDate = new Date(oDatePart[0], (oDatePart[1] - 1), oDatePart[2]);
            } else {
                oDate = new Date(sDate[0]);
            }
            oDate = oDate.format();
            sTitle = entry1.getElementsByTagName('title')[0].childNodes[0].nodeValue;
            sRawTitle = sTitle;
            sContent = entry1.getElementsByTagName('content')[0].childNodes[0].nodeValue;
            for (iCount = 0; iCount < iTotal; iCount++) {
                sTitle = sTitle.replace(oItalicBookName[iCount], "" + oItalicBookName[iCount] + "");
            }
            $("#bloggerContent").html(sContent);
            var bloggerContent = document.getElementById("bloggerContent");
            var imgs = bloggerContent.getElementsByTagName('img');
            var img, src = "";

            if (typeof imgs !== "undefined" && imgs.length > 0) {
                img = imgs[0];
                src = img.src;
                newsImageSource = src;
                img.parentNode.removeChild(img);
            }
            sContent = $("#bloggerContent").html();
            oNewsContainer.addClass(sLoadingClass);
            oNewsContainer.append(oNewsArticlePager.template.replace("@date", oDate).replace("@content", sContent).replace(/@newsimagesrc/g, src).replace("@tooltip", getFirstNWordsWithEllipses(sRawTitle, 4)));
            var pageURL = document.location.href;
            setTimeout(function () {
                $(".post-header").append(oNewsArticlePager.socialMediatemplate.replace(/@title/g, sTitle).replace(/@newsimagesrc/g, src).replace("@fbunewslink", pageURL).replace("@newslink", pageURL).replace("@twitternewslink", pageURL).replace("@linkedinnewslink", pageURL)

                                .replace("@lnurl", pageURL)
                                .replace("@linktitle", sRawTitle.substr(0, 200))
                                .replace("@lnsummary", sRawTitle.substr(0, 256))
                                .replace("@lntitle", sRawTitle)
                                .replace("@lnsource", "MAQ Software"));

                FB.XFBML.parse();
            }, 1000);

        }

        oNewsContainer.find("a").attr("target", "_blank");
        oNewsContainer.find("img").addClass("post - media");

        $('#LoadPageNewsArticle *').removeAttr('style');

    }
}

function sharefacebook() {
    shareOverrideOGMeta(newsTitle, newsImageSource);
};
function shareOverrideOGMeta(overrideTitle, overrideImage) {
    var newsTitleEnc;
    if (/MSIE|Trident/.test(navigator.userAgent)) {
        newsTitleEnc = encodeURI(location.search.split('title=')[1]);
    }
    else {
        var params = (new URL(document.location)).searchParams;
        newsTitleEnc = encodeURI(params.get("title"));
    }
    FB.ui({
        method: 'share',
        href: "https://maqsoftware.com",
        redirect_uri: "https://maq-akshayak.github.io/news-article" + "?title=" + newsTitleEnc,
        action_type: 'og.shares',
        action_properties: JSON.stringify({
            object: {
                'og:url': "https://maq-akshayak.github.io/news-article" + "?title=" + newsTitleEnc,
                'og:title': overrideTitle,
                'og:image': overrideImage
            }
        })
    },
	function (response) {
	    // Action after response
	});
}

<|endoftext|>


<commit_before>const algorithms = require('./algorithms');

module.exports = {
    algorithms
};<commit_msg>Add data_structures to index.js<commit_after>const algorithms = require('./algorithms');
const data_structures = require('./data_structures')

module.exports = {
    algorithms,
    data_structures
};<|endoftext|>


<commit_before>/**
 * Interpret, cache and merge player data.
 *
 * @author Bram Gotink (@bgotink)
 * @license MIT
 */

window.iidentity = window.iidentity || {};

(function (module, $) {
    'use strict';

    var exports = module.data = {},

        anomalies = [ '13magnus', 'recursion', 'interitus' ],
        mainPlayerData = ['name', 'nickname', 'oid', 'level'],

    // unexported helper functions and classes

        filterEmpty = function (obj) {
            var key;

            for (key in obj) {
                if (typeof obj[key] === 'object') {
                    filterEmpty(obj[key]);
                } else if (obj[key] === null || ('' + obj[key]).isBlank()) {
                    delete obj[key];
                }
            }
        },
        getExtraDataValueName = function (str) {
            var i = str.indexOf(':');

            if (i === -1) {
                return str.compact();
            } else {
                return str.to(i).trim();
            }
        },
        addToArray = function (src, dst) {
            if (!Array.isArray(src)) {
                src = [ src ];
            }

            var existing = [],
                name;

            dst.each(function (elem) {
                existing.push(getExtraDataValueName(elem));
            });

            src.each(function (elem) {
                name = getExtraDataValueName(elem);

                if (existing.indexOf(name) === -1) {
                    dst.push(elem);
                    existing.push(name);
                }
            });
        },
        merge_player = function () {
            if (arguments.length === 0) {
                return false;
            } else if (arguments.length == 1) {
                return arguments[0];
            }

            var target = arguments[0],
                src = arguments[1],
                newArguments,
                key,
                extraKey,
                tmp;

            if (!Object.isObject(target.extra)) {
                target.extra = {};
            }

            for (key in src) {
                if (key === 'err') {
                    if (Array.isArray(src.err)) {
                        if ('err' in target) {
                            if (Array.isArray(target.err)) {
                                target.err = target.err.join(src.err);
                            } else {
                                target.err = src.err;
                            }
                        } else {
                            target.err = src.err;
                        }
                    }
                } else if (key === 'extra') {
                    for (extraKey in src.extra) {
                        if (extraKey in target.extra) {
                            if (Array.isArray(target.extra[extraKey])) {
                                addToArray(
                                    src.extra[extraKey],
                                    target.extra[extraKey]
                                );
                            } else {
                                tmp = [ target.extra[extraKey] ];
                                addToArray(
                                    src.extra[extraKey],
                                    tmp
                                );

                                if (tmp.length > 1) {
                                    target.extra[extraKey] = tmp;
                                }
                            }
                        } else {
                            target.extra[extraKey] = src.extra[extraKey];
                        }
                    }
                } else {
                    target[key] = src[key];
                }
            }

            newArguments = Array.prototype.slice.call(arguments, 1);
            newArguments[0] = target;
            return merge_player.apply(null, newArguments);
        },

        PlayerSource = Class.extend({
            init: function (key, spreadsheet, data, players) {
                this.key = key;
                this.spreadsheet = spreadsheet;
                this.data = data;
                this.err = [];
                this.timestamp = +new Date();

                filterEmpty(data);

                if ('extratags' in data) {
                    try {
                        data.extratags = JSON.parse(data.extratags);
                    } catch (e) {
                        this.err.push('Invalid JSON in extratags: ' + e.message);
                        data.extratags = {};
                    }
                } else {
                    data.extratags = {};
                }

                if ('anomaly' in data.extratags) {
                    var anomaly = data.extratags.anomaly;

                    if (anomalies.indexOf(anomaly) === -1) {
                        this.err.push('Invalid anomaly: ' + anomaly);
                        delete data.extratags.anomaly;
                    }
                }

                if ('community' in data.extratags) {
                    var community = data.extratags.community;

                    if (community.indexOf(':') === -1) {
                        this.err.push('Invalid community: "' + community + '"');
                        delete data.extratags.community;
                    }
                }

                this.setPlayers(players);
            },

            setPlayers: function (players) {
                this.players = {};
                var newPlayers = this.players;
                players.each(function (player) {
                    if (!(Object.isNumber(player.oid) || Object.isString(player.oid))
                                || ('' + player.oid).match(/^9*$/)) {
                        return;
                    }

                    newPlayers[player.oid] = player;
                });
            },

            hasPlayer: function (oid) {
                return (oid in this.players);
            },
            getPlayer: function (oid) {
                if (!this.hasPlayer(oid)) {
                    return null;
                }

                var rawPlayer = this.players[oid],
                    player = {},
                    key;
                player.extra = {};

                for (key in rawPlayer) {
                    if (mainPlayerData.indexOf(key) !== -1) {
                        player[key] = rawPlayer[key];
                    } else {
                        player.extra[key] = rawPlayer[key];
                    }
                }

                filterEmpty(player);

                return $.extend(
                    true,
                    {
                        faction: this.data.faction,
                        extra: this.data.extratags
                    },
                    player
                );
            },

            getNbPlayers: function () {
                return Object.size(this.players);
            },

            getKey: function () {
                return this.key;
            },
            getTag: function () {
                return this.data.tag;
            },
            getVersion: function () {
                return this.data.lastupdated;
            },
            getFaction: function () {
                return this.data.faction;
            },

            getTimestamp: function () {
                return this.timestamp;
            },
            getUpdateInterval: function () {
                return Math.floor(this.data.refresh) * 60 * 60 * 1000;
            },

            isCombined: function () {
                return false;
            },

            shouldUpdate: function () {
                return (+new Date()) > (this.getTimestamp() + this.getUpdateInterval());
            },
            setUpdated: function () {
                this.timestamp = +new Date();
                return this;
            },
            update: function (callback) {
                var self = this;

                module.log.log('Updating source %s', this.getKey());
                this.spreadsheet.load(function (err, players) {
                    if (players) {
                        module.log.log('Had %d players, now %d', self.players.length, players.length);
                        self.setPlayers(players);
                        self.setUpdated();

                        if (err) {
                            err.forEach(module.log.warn);
                        }

                        callback(true);
                    } else {
                        err.forEach(module.log.error);

                        callback(false);
                    }
                });
            },

            hasErrors: function () {
                return this.err.length > 0;
            },
            getErrors: function () {
                return this.err;
            },

            getUrl: function () {
                return this.spreadsheet.getUrl();
            },

            hasExtra: function (tag, oid) {
                if (!(tag in this.data.extratags)
                        || !Object.isString(this.data.extratags[tag])) {
                    return false;
                }

                var i = this.data.extratags[tag].indexOf(':');

                return (i !== -1)
                    && (oid === this.data.extratags[tag].to(i).trim());
            },
        }),

        CombinedPlayerSource = Class.extend({
            init: function (sources, key, spreadsheet) {
                this.sources = sources;

                this.key = key || 0;
                this.spreadsheet = spreadsheet || null;

                this.cache = {};
                this.timestamp = +new Date;

                this.loadingErrors = null;
            },

            getKey: function () {
                return this.key;
            },

            hasPlayer: function (oid) {
                if (typeof this.cache[oid] !== 'undefined') {
                    return this.cache[oid] !== null;
                }

                return this.sources.some(function (source) {
                    return source.hasPlayer(oid);
                });
            },
            getPlayer: function (oid) {
                if (typeof this.cache[oid] !== 'undefined') {
                    return this.cache[oid];
                }

                var data = [ {} ],
                    result,
                    faction;

                this.sources.forEach(function (source) {
                    result = source.getPlayer(oid);

                    if (result !== null) {
                        data.push(result);
                    }
                });

                if (data.length < 2) {
                    return this.cache[oid] = null;
                }

                faction = data[1].faction;
                if (data.some(function (elem) {
                    return elem.faction && (elem.faction !== faction);
                })) {
                    data[0].err = ['Player ' + data[0].name + ' [' + data[0].nickname + '] has been registered as both enlightened and resistance'];
                }

                this.cache[oid] = merge_player.apply(null, data);

                return this.cache[oid];
            },

            getSources: function () {
                return this.sources;
            },
            getSource: function (key) {
                var sources = this.sources,
                    length = sources.length,
                    i;

                for (i = 0; i < length; i++) {
                    if (sources[i].getKey() == key) {
                        return sources[i];
                    }
                }

                return null;
            },

            isCombined: function () {
                return true;
            },

            invalidateCache: function () {
                this.getSources().each(function (source) {
                    if (source.isCombined()) {
                        source.invalidateCache();
                    }
                });

                this.cache = {};

                return this;
            },

            shouldUpdateRemote: function (remoteTimestamp) {
                return remoteTimestamp < this.timestamp;
            },
            shouldUpdate: function () {
                return true;
            },
            update: function (callback) {
                var origCallback = callback,
                    self = this;
                callback = function (updated) {
                    if (updated) {
                        self.timestamp = +new Date();
                    }

                    origCallback(updated);
                }

                if (this.spreadsheet) {
                    var source,
                        step,
                        length;

                    module.log.log('Updating manifest %s', this.key);
                    this.spreadsheet.load(function (err, data) {
                        length = data.length;

                        step = function (i, updated) {
                            if (i >= length) {
                                callback(updated);
                                return;
                            }

                            source = self.getSource(data[i].key);
                            if (source === null) {
                                loadSource(data[i], function (err, source) {
                                    if (source) {
                                        module.log.log('Adding new source sheet %s', data[i].key)
                                        self.sources.push(source);
                                        if (err) {
                                            err.forEach(module.log.warn);
                                        }

                                        step(i + 1, true);
                                    } else {
                                        module.log.error('Error occured while adding source');
                                        err.forEach(module.log.error);

                                        step(i + 1, updated);
                                    }
                                });
                            } else {
                                if (source.shouldUpdate()) {
                                    if (source.getVersion() !== data[i].lastupdated) {
                                        module.log.log('Updating source sheet %s from version %s to %s', data[i].key, source.getVersion(), data[i].lastupdated);
                                        source.data = data[i];
                                        source.update(function (u) {
                                            step(i + 1, updated || u);
                                        });
                                    } else {
                                        source.setUpdated();
                                        step(i + 1, updated);
                                    }
                                } else {
                                    step(i + 1, updated);
                                }
                            }
                        };
                        step(0, false);
                    });
                } else {
                    var sources = this.getSources(),
                        length = sources.length;

                    module.log.log('Updating collection of manifests');
                    step = function (i, updated) {
                        if (i >= length) {
                            callback(updated);
                            return;
                        }

                        if (sources[i].shouldUpdate()) {
                            sources[i].update(function (u) {
                                step(i + 1, updated || u);
                            });
                        } else {
                            step(i + 1, updated);
                        }
                    };
                    step(0, false);
                }

                return this;
            },

            hasErrors: function () {
                return this.getSources().some(function (source) {
                    return source.hasErrors();
                });
            },
            getErrors: function () {
                var errors = {};

                this.getSources().forEach(function (source) {
                    if (source.hasErrors()) {
                        errors[source.getKey()] = source.getErrors();
                    }
                });

                return $.extend(true, {}, errors, this.loadingErrors);
            },

            hasLoadingErrors: function () {
                return !!this.loadingErrors;
            },
            setLoadingErrors: function (err) {
                if (typeof err === 'undefined' || err === null) {
                    this.loadingErrors = null;
                    return;
                }
                if ((Array.isArray(err) ? err.length : Object.size(err)) === 0) {
                    this.loadingErrors = null;
                    return;
                }

                this.loadingErrors = err;
                return this;
            },

            getUrl: function () {
                return this.spreadsheet ? this.spreadsheet.getUrl() : null;
            },

            getSourcesForExtra: function (tag, oid) {
                var result = [];

                this.getSources().each(function (source) {
                    if (source.isCombined()) {
                        result.push(source.getSourcesForExtra(tag, oid));
                    } else if (source.hasExtra(tag, oid)) {
                        result.push([{
                            url: source.getUrl(),
                            key: source.getTag()
                        }]);
                    }
                });

                return result.reduce(function (res, elem) {
                    return res.concat(elem);
                }, []);
            },
        }),

        loadSource = function (data, callback) {
            var key = data.key,
                source = new module.spreadsheets.Source(key);
            delete data.key;

            source.load(function (err, players) {
                if (players === null) {
                    callback(err, null);
                    return;
                }

                callback(err, new PlayerSource(key, source, data, players));
            });
        },

        loadManifest = function (key, callback) {
            var manifest = new module.spreadsheets.Manifest(key),
                sources = [];

            manifest.load(function (merr, sourcesData) {
                module.log.log('Loaded manifest ', key, ', got ', sourcesData, 'err: ', merr);
                if (sourcesData === null) {
                    callback({ __errors: merr }, null);
                    return;
                }

                var err = {};
                if (merr !== null) {
                    err.__errors = merr;
                }

                var nbSources = sourcesData.length,
                    step = function (i) {
                        if (i >= nbSources) {
                            callback(
                                Object.size(err) > 0 ? err : null,
                                new CombinedPlayerSource(sources, key, manifest)
                            );
                            return;
                        }

                        var skey = sourcesData[i].key;

                        loadSource(sourcesData[i], function (err2, source) {
                            if (err2) {
                                err[skey] = err2;
                            }

                            if (source === null) {
                                callback(err, null);
                                return;
                            }

                            sources.push(source);

                            step(i + 1);
                        });
                    };

                step(0);
            });
        },

        loadManifests = function (keys, callback) {
            var nbKeys = keys.length,
                sources = [],
                err = {},
                step = function (i) {
                    if (i >= nbKeys) {
                        callback(
                            Object.size(err) > 0 ? err : null,
                            sources.length > 0 ? new CombinedPlayerSource(sources) : null
                        );
                        return;
                    }

                    loadManifest(keys[i], function (err2, manifest) {
                        if (err2) {
                            err[keys[i]] = err2;
                        }

                        if (manifest !== null) {
                            sources.push(manifest);
                        }

                        step(i + 1);
                    });
                };

            step(0);
        };

    // exported functions
    exports.loadManifests = loadManifests;
})(window.iidentity, window.jQuery);
<commit_msg>[backend] small change<commit_after>/**
 * Interpret, cache and merge player data.
 *
 * @author Bram Gotink (@bgotink)
 * @license MIT
 */

window.iidentity = window.iidentity || {};

(function (module, $) {
    'use strict';

    var exports = module.data = {},

        anomalies = [ '13magnus', 'recursion', 'interitus' ],
        mainPlayerData = ['name', 'nickname', 'oid', 'level'],

    // unexported helper functions and classes

        filterEmpty = function (obj) {
            var key;

            for (key in obj) {
                if (typeof obj[key] === 'object') {
                    filterEmpty(obj[key]);
                } else if (obj[key] === null || ('' + obj[key]).isBlank()) {
                    delete obj[key];
                }
            }
        },
        getExtraDataValueName = function (str) {
            var i = str.indexOf(':');

            if (i === -1) {
                return str.compact();
            } else {
                return str.to(i).trim();
            }
        },
        addToArray = function (src, dst) {
            if (!Array.isArray(src)) {
                src = [ src ];
            }

            var existing = [],
                name;

            dst.each(function (elem) {
                existing.push(getExtraDataValueName(elem));
            });

            src.each(function (elem) {
                name = getExtraDataValueName(elem);

                if (existing.indexOf(name) === -1) {
                    dst.push(elem);
                    existing.push(name);
                }
            });
        },
        merge_player = function () {
            if (arguments.length === 0) {
                return false;
            } else if (arguments.length == 1) {
                return arguments[0];
            }

            var target = arguments[0],
                src = arguments[1],
                newArguments,
                key,
                extraKey,
                tmp;

            if (!Object.isObject(target.extra)) {
                target.extra = {};
            }

            for (key in src) {
                if (key === 'err') {
                    if (Array.isArray(src.err)) {
                        if ('err' in target) {
                            if (Array.isArray(target.err)) {
                                target.err = target.err.join(src.err);
                            } else {
                                target.err = src.err;
                            }
                        } else {
                            target.err = src.err;
                        }
                    }
                } else if (key === 'extra') {
                    for (extraKey in src.extra) {
                        if (extraKey in target.extra) {
                            if (Array.isArray(target.extra[extraKey])) {
                                addToArray(
                                    src.extra[extraKey],
                                    target.extra[extraKey]
                                );
                            } else {
                                tmp = [ target.extra[extraKey] ];
                                addToArray(
                                    src.extra[extraKey],
                                    tmp
                                );

                                if (tmp.length > 1) {
                                    target.extra[extraKey] = tmp;
                                }
                            }
                        } else {
                            target.extra[extraKey] = src.extra[extraKey];
                        }
                    }
                } else {
                    target[key] = src[key];
                }
            }

            newArguments = Array.prototype.slice.call(arguments, 1);
            newArguments[0] = target;
            return merge_player.apply(null, newArguments);
        },
        checkValidAnomaly = function (data, key, err) {
            if (key in data) {
                var value = ('' + data[key]).trim();

                if (anomalies.indexOf(value) === -1) {
                    err.push('Invalid anomaly: ' + value);
                    delete data[key];
                }
            }
        },
        checkValidPageValue = function (data, key, err) {
            if (key in data) {
                var value = data[key];

                if (value.indexOf(':') === -1) {
                    err.push('Invalid ' + key + ': ' + value);
                    delete data[key];
                }
            }
        },

        PlayerSource = Class.extend({
            init: function (key, spreadsheet, data, players) {
                this.key = key;
                this.spreadsheet = spreadsheet;
                this.data = data;
                this.err = [];
                this.timestamp = +new Date();

                filterEmpty(data);

                if ('extratags' in data) {
                    try {
                        data.extratags = JSON.parse(data.extratags);
                    } catch (e) {
                        this.err.push('Invalid JSON in extratags: ' + e.message);
                        data.extratags = {};
                    }
                } else {
                    data.extratags = {};
                }

                checkValidAnomaly(data.extratags, 'anomaly', this.err);

                checkValidPageValue(data.extratags, 'community', this.err);
                checkValidPageValue(data.extratags, 'event', this.err);

                this.setPlayers(players);
            },

            setPlayers: function (players) {
                this.players = {};
                var newPlayers = this.players;
                players.each(function (player) {
                    if (!(Object.isNumber(player.oid) || Object.isString(player.oid))
                                || ('' + player.oid).match(/^9*$/)) {
                        return;
                    }

                    newPlayers[player.oid] = player;
                });
            },

            hasPlayer: function (oid) {
                return (oid in this.players);
            },
            getPlayer: function (oid) {
                if (!this.hasPlayer(oid)) {
                    return null;
                }

                var rawPlayer = this.players[oid],
                    player = {},
                    key;
                player.extra = {};

                for (key in rawPlayer) {
                    if (mainPlayerData.indexOf(key) !== -1) {
                        player[key] = rawPlayer[key];
                    } else {
                        player.extra[key] = rawPlayer[key];
                    }
                }

                filterEmpty(player);

                return $.extend(
                    true,
                    {
                        faction: this.data.faction,
                        extra: this.data.extratags
                    },
                    player
                );
            },

            getNbPlayers: function () {
                return Object.size(this.players);
            },

            getKey: function () {
                return this.key;
            },
            getTag: function () {
                return this.data.tag;
            },
            getVersion: function () {
                return this.data.lastupdated;
            },
            getFaction: function () {
                return this.data.faction;
            },

            getTimestamp: function () {
                return this.timestamp;
            },
            getUpdateInterval: function () {
                return Math.floor(this.data.refresh) * 60 * 60 * 1000;
            },

            isCombined: function () {
                return false;
            },

            shouldUpdate: function () {
                return (+new Date()) > (this.getTimestamp() + this.getUpdateInterval());
            },
            setUpdated: function () {
                this.timestamp = +new Date();
                return this;
            },
            update: function (callback) {
                var self = this;

                module.log.log('Updating source %s', this.getKey());
                this.spreadsheet.load(function (err, players) {
                    if (players) {
                        module.log.log('Had %d players, now %d', self.players.length, players.length);
                        self.setPlayers(players);
                        self.setUpdated();

                        if (err) {
                            err.forEach(module.log.warn);
                        }

                        callback(true);
                    } else {
                        err.forEach(module.log.error);

                        callback(false);
                    }
                });
            },

            hasErrors: function () {
                return this.err.length > 0;
            },
            getErrors: function () {
                return this.err;
            },

            getUrl: function () {
                return this.spreadsheet.getUrl();
            },

            hasExtra: function (tag, oid) {
                if (!(tag in this.data.extratags)
                        || !Object.isString(this.data.extratags[tag])) {
                    return false;
                }

                var i = this.data.extratags[tag].indexOf(':');

                return (i !== -1)
                    && (oid === this.data.extratags[tag].to(i).trim());
            },
        }),

        CombinedPlayerSource = Class.extend({
            init: function (sources, key, spreadsheet) {
                this.sources = sources;

                this.key = key || 0;
                this.spreadsheet = spreadsheet || null;

                this.cache = {};
                this.timestamp = +new Date;

                this.loadingErrors = null;
            },

            getKey: function () {
                return this.key;
            },

            hasPlayer: function (oid) {
                if (typeof this.cache[oid] !== 'undefined') {
                    return this.cache[oid] !== null;
                }

                return this.sources.some(function (source) {
                    return source.hasPlayer(oid);
                });
            },
            getPlayer: function (oid) {
                if (typeof this.cache[oid] !== 'undefined') {
                    return this.cache[oid];
                }

                var data = [ {} ],
                    result,
                    faction;

                this.sources.forEach(function (source) {
                    result = source.getPlayer(oid);

                    if (result !== null) {
                        data.push(result);
                    }
                });

                if (data.length < 2) {
                    return this.cache[oid] = null;
                }

                faction = data[1].faction;
                if (data.some(function (elem) {
                    return elem.faction && (elem.faction !== faction);
                })) {
                    data[0].err = ['Player ' + data[0].name + ' [' + data[0].nickname + '] has been registered as both enlightened and resistance'];
                }

                this.cache[oid] = merge_player.apply(null, data);

                return this.cache[oid];
            },

            getSources: function () {
                return this.sources;
            },
            getSource: function (key) {
                var sources = this.sources,
                    length = sources.length,
                    i;

                for (i = 0; i < length; i++) {
                    if (sources[i].getKey() == key) {
                        return sources[i];
                    }
                }

                return null;
            },

            isCombined: function () {
                return true;
            },

            invalidateCache: function () {
                this.getSources().each(function (source) {
                    if (source.isCombined()) {
                        source.invalidateCache();
                    }
                });

                this.cache = {};

                return this;
            },

            shouldUpdateRemote: function (remoteTimestamp) {
                return remoteTimestamp < this.timestamp;
            },
            shouldUpdate: function () {
                return true;
            },
            update: function (callback) {
                var origCallback = callback,
                    self = this;
                callback = function (updated) {
                    if (updated) {
                        self.timestamp = +new Date();
                    }

                    origCallback(updated);
                }

                if (this.spreadsheet) {
                    var source,
                        step,
                        length;

                    module.log.log('Updating manifest %s', this.key);
                    this.spreadsheet.load(function (err, data) {
                        length = data.length;

                        step = function (i, updated) {
                            if (i >= length) {
                                callback(updated);
                                return;
                            }

                            source = self.getSource(data[i].key);
                            if (source === null) {
                                loadSource(data[i], function (err, source) {
                                    if (source) {
                                        module.log.log('Adding new source sheet %s', data[i].key)
                                        self.sources.push(source);
                                        if (err) {
                                            err.forEach(module.log.warn);
                                        }

                                        step(i + 1, true);
                                    } else {
                                        module.log.error('Error occured while adding source');
                                        err.forEach(module.log.error);

                                        step(i + 1, updated);
                                    }
                                });
                            } else {
                                if (source.shouldUpdate()) {
                                    if (source.getVersion() !== data[i].lastupdated) {
                                        module.log.log('Updating source sheet %s from version %s to %s', data[i].key, source.getVersion(), data[i].lastupdated);
                                        source.data = data[i];
                                        source.update(function (u) {
                                            step(i + 1, updated || u);
                                        });
                                    } else {
                                        source.setUpdated();
                                        step(i + 1, updated);
                                    }
                                } else {
                                    step(i + 1, updated);
                                }
                            }
                        };
                        step(0, false);
                    });
                } else {
                    var sources = this.getSources(),
                        length = sources.length;

                    module.log.log('Updating collection of manifests');
                    step = function (i, updated) {
                        if (i >= length) {
                            callback(updated);
                            return;
                        }

                        if (sources[i].shouldUpdate()) {
                            sources[i].update(function (u) {
                                step(i + 1, updated || u);
                            });
                        } else {
                            step(i + 1, updated);
                        }
                    };
                    step(0, false);
                }

                return this;
            },

            hasErrors: function () {
                return this.getSources().some(function (source) {
                    return source.hasErrors();
                });
            },
            getErrors: function () {
                var errors = {};

                this.getSources().forEach(function (source) {
                    if (source.hasErrors()) {
                        errors[source.getKey()] = source.getErrors();
                    }
                });

                return $.extend(true, {}, errors, this.loadingErrors);
            },

            hasLoadingErrors: function () {
                return !!this.loadingErrors;
            },
            setLoadingErrors: function (err) {
                if (typeof err === 'undefined' || err === null) {
                    this.loadingErrors = null;
                    return;
                }
                if ((Array.isArray(err) ? err.length : Object.size(err)) === 0) {
                    this.loadingErrors = null;
                    return;
                }

                this.loadingErrors = err;
                return this;
            },

            getUrl: function () {
                return this.spreadsheet ? this.spreadsheet.getUrl() : null;
            },

            getSourcesForExtra: function (tag, oid) {
                var result = [];

                this.getSources().each(function (source) {
                    if (source.isCombined()) {
                        result.push(source.getSourcesForExtra(tag, oid));
                    } else if (source.hasExtra(tag, oid)) {
                        result.push([{
                            url: source.getUrl(),
                            key: source.getTag()
                        }]);
                    }
                });

                return result.reduce(function (res, elem) {
                    return res.concat(elem);
                }, []);
            },
        }),

        loadSource = function (data, callback) {
            var key = data.key,
                source = new module.spreadsheets.Source(key);
            delete data.key;

            source.load(function (err, players) {
                if (players === null) {
                    callback(err, null);
                    return;
                }

                callback(err, new PlayerSource(key, source, data, players));
            });
        },

        loadManifest = function (key, callback) {
            var manifest = new module.spreadsheets.Manifest(key),
                sources = [];

            manifest.load(function (merr, sourcesData) {
                module.log.log('Loaded manifest ', key, ', got ', sourcesData, 'err: ', merr);
                if (sourcesData === null) {
                    callback({ __errors: merr }, null);
                    return;
                }

                var err = {};
                if (merr !== null) {
                    err.__errors = merr;
                }

                var nbSources = sourcesData.length,
                    step = function (i) {
                        if (i >= nbSources) {
                            callback(
                                Object.size(err) > 0 ? err : null,
                                new CombinedPlayerSource(sources, key, manifest)
                            );
                            return;
                        }

                        var skey = sourcesData[i].key;

                        loadSource(sourcesData[i], function (err2, source) {
                            if (err2) {
                                err[skey] = err2;
                            }

                            if (source === null) {
                                callback(err, null);
                                return;
                            }

                            sources.push(source);

                            step(i + 1);
                        });
                    };

                step(0);
            });
        },

        loadManifests = function (keys, callback) {
            var nbKeys = keys.length,
                sources = [],
                err = {},
                step = function (i) {
                    if (i >= nbKeys) {
                        callback(
                            Object.size(err) > 0 ? err : null,
                            sources.length > 0 ? new CombinedPlayerSource(sources) : null
                        );
                        return;
                    }

                    loadManifest(keys[i], function (err2, manifest) {
                        if (err2) {
                            err[keys[i]] = err2;
                        }

                        if (manifest !== null) {
                            sources.push(manifest);
                        }

                        step(i + 1);
                    });
                };

            step(0);
        };

    // exported functions
    exports.loadManifests = loadManifests;
})(window.iidentity, window.jQuery);
<|endoftext|>


<commit_before>const React = require('react'),
	ReactDOM = require('react-dom')

const app = function() {

	const Header = React.createClass({
		render: () => {
			return
YOLO

		}
	})

	ReactDOM.render(,document.querySelector('.container'))
}

app()<commit_msg>changed requires to imports<commit_after>import React from 'react'
import ReactDOM from 'react-dom'

const app = function() {

	const Header = React.createClass({
		render: () => {
			return
YOLO

		}
	})

	ReactDOM.render(,document.querySelector('.container'))
}

app()<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for Node
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanIO = require( 'TANDEM/types/BooleanIO' );
  var NodeProperty = require( 'SCENERY/util/NodeProperty' );
  var NullableIO = require( 'TANDEM/types/NullableIO' );
  var NumberProperty = require( 'AXON/NumberProperty' );
  var ObjectIO = require( 'TANDEM/types/ObjectIO' );
  var phetioInherit = require( 'TANDEM/phetioInherit' );
  var PropertyIO = require( 'AXON/PropertyIO' );
  var Range = require( 'DOT/Range' );
  var scenery = require( 'SCENERY/scenery' );

  /**
   * IO type for phet/scenery's Node
   * @param {Node} node
   * @param {string} phetioID
   * @constructor
   */
  function NodeIO( node, phetioID ) {
    ObjectIO.call( this, node, phetioID );

    // TODO: This is in-progress work to convert object properties to Axon Properties, see https://github.com/phetsims/phet-io/issues/1326
    var visibleProperty = new NodeProperty( node, 'visibility', 'visible', _.extend( {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,
      phetioType: PropertyIO( BooleanIO ),

      tandem: node.tandem.createTandem( 'visibleProperty' ),
      phetioDocumentation: 'Controls whether the Node will be visible (and interactive), see the NodeIO documentation for more details.'
    }, node.phetioComponentOptions, node.phetioComponentOptions.visibleProperty ) );

    var pickableProperty = new NodeProperty( node, 'pickability', 'pickable', _.extend( {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,

      tandem: node.tandem.createTandem( 'pickableProperty' ),
      phetioType: PropertyIO( NullableIO( BooleanIO ) ),
      phetioDocumentation: 'Sets whether the node will be pickable (and hence interactive), see the NodeIO documentation for more details'
    }, node.phetioComponentOptions, node.phetioComponentOptions.pickableProperty ) );

    // Adapter for the opacity.  Cannot use NodeProperty at the moment because it doesn't handle numeric types
    // properly--we may address this by moving to a mixin pattern.
    var opacityProperty = new NumberProperty( node.opacity, _.extend( {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,

      tandem: node.tandem.createTandem( 'opacityProperty' ),
      range: new Range( 0, 1 ),
      phetioDocumentation: 'Opacity of the parent NodeIO, between 0 (invisible) and 1 (fully visible)'
    }, node.phetioComponentOptions, node.phetioComponentOptions.opacityProperty ) );
    opacityProperty.link( function( opacity ) { node.opacity = opacity; } );
    node.on( 'opacity', function() { opacityProperty.value = node.opacity; } );

    // @private
    this.disposeNodeIO = function() {
      visibleProperty.dispose();
      pickableProperty.dispose();
      opacityProperty.dispose();
    };
  }

  phetioInherit( ObjectIO, 'NodeIO', NodeIO, {

    /**
     * @public - called by PhetioObject when the wrapper is done
     */
    dispose: function() {
      this.disposeNodeIO();
    }
  }, {

    validator: { valueType: scenery.Node },

    documentation: 'The base type for graphical and potentially interactive objects.  NodeIO has nested PropertyIO values ' +
                   'for visibility, pickability and opacity.' +
                   '
' +
                   '
' +
                   'Pickable can take one of three values:
' +
                   '
' +
                   '
null: pass-through behavior. Nodes with input listeners are pickable, but nodes without input listeners won\'t block events for nodes behind it.
' +
                   '
false: The node cannot be interacted with, and it blocks events for nodes behind it.
' +
                   '
true: The node can be interacted with (if it has an input listener).
' +
                   '
' +
                   'For more about Scenery node pickability, please see http://phetsims.github.io/scenery/doc/implementation-notes#pickability'
  } );

  scenery.register( 'NodeIO', NodeIO );

  return NodeIO;
} );

<commit_msg>Use baseline values to set phetioReadOnly baseline value for NodeIO's nested Properties, see https://github.com/phetsims/tandem/issues/89<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for Node
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanIO = require( 'TANDEM/types/BooleanIO' );
  var NodeProperty = require( 'SCENERY/util/NodeProperty' );
  var NullableIO = require( 'TANDEM/types/NullableIO' );
  var NumberProperty = require( 'AXON/NumberProperty' );
  var ObjectIO = require( 'TANDEM/types/ObjectIO' );
  var phetioInherit = require( 'TANDEM/phetioInherit' );
  var PropertyIO = require( 'AXON/PropertyIO' );
  var Range = require( 'DOT/Range' );
  var scenery = require( 'SCENERY/scenery' );

  /**
   * IO type for phet/scenery's Node
   * @param {Node} node
   * @param {string} phetioID
   * @constructor
   */
  function NodeIO( node, phetioID ) {
    ObjectIO.call( this, node, phetioID );

    // TODO: This is in-progress work to convert object properties to Axon Properties, see https://github.com/phetsims/phet-io/issues/1326
    var visibleProperty = new NodeProperty( node, 'visibility', 'visible', _.extend( {

      // pick the baseline value from the parent Node's baseline
      phetioReadOnly: node.phetioReadOnlyBaseline,
      phetioType: PropertyIO( BooleanIO ),

      tandem: node.tandem.createTandem( 'visibleProperty' ),
      phetioDocumentation: 'Controls whether the Node will be visible (and interactive), see the NodeIO documentation for more details.'
    }, node.phetioComponentOptions, node.phetioComponentOptions.visibleProperty ) );

    var pickableProperty = new NodeProperty( node, 'pickability', 'pickable', _.extend( {

      // pick the baseline value from the parent Node's baseline
      phetioReadOnly: node.phetioReadOnlyBaseline,

      tandem: node.tandem.createTandem( 'pickableProperty' ),
      phetioType: PropertyIO( NullableIO( BooleanIO ) ),
      phetioDocumentation: 'Sets whether the node will be pickable (and hence interactive), see the NodeIO documentation for more details'
    }, node.phetioComponentOptions, node.phetioComponentOptions.pickableProperty ) );

    // Adapter for the opacity.  Cannot use NodeProperty at the moment because it doesn't handle numeric types
    // properly--we may address this by moving to a mixin pattern.
    var opacityProperty = new NumberProperty( node.opacity, _.extend( {

      // pick the baseline value from the parent Node's baseline
      phetioReadOnly: node.phetioReadOnlyBaseline,

      tandem: node.tandem.createTandem( 'opacityProperty' ),
      range: new Range( 0, 1 ),
      phetioDocumentation: 'Opacity of the parent NodeIO, between 0 (invisible) and 1 (fully visible)'
    }, node.phetioComponentOptions, node.phetioComponentOptions.opacityProperty ) );
    opacityProperty.link( function( opacity ) { node.opacity = opacity; } );
    node.on( 'opacity', function() { opacityProperty.value = node.opacity; } );

    // @private
    this.disposeNodeIO = function() {
      visibleProperty.dispose();
      pickableProperty.dispose();
      opacityProperty.dispose();
    };
  }

  phetioInherit( ObjectIO, 'NodeIO', NodeIO, {

    /**
     * @public - called by PhetioObject when the wrapper is done
     */
    dispose: function() {
      this.disposeNodeIO();
    }
  }, {

    validator: { valueType: scenery.Node },

    documentation: 'The base type for graphical and potentially interactive objects.  NodeIO has nested PropertyIO values ' +
                   'for visibility, pickability and opacity.' +
                   '
' +
                   '
' +
                   'Pickable can take one of three values:
' +
                   '
' +
                   '
null: pass-through behavior. Nodes with input listeners are pickable, but nodes without input listeners won\'t block events for nodes behind it.
' +
                   '
false: The node cannot be interacted with, and it blocks events for nodes behind it.
' +
                   '
true: The node can be interacted with (if it has an input listener).
' +
                   '
' +
                   'For more about Scenery node pickability, please see http://phetsims.github.io/scenery/doc/implementation-notes#pickability'
  } );

  scenery.register( 'NodeIO', NodeIO );

  return NodeIO;
} );

<|endoftext|>