<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

// Verifies the order of getOwnPropertyDescriptor trap called for ownKeys
function test1() {
    var obj = {};
    var proxy = new Proxy(obj, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy : ' + property.toString());
            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy');
            return ["prop0", "prop1", Symbol("prop2"), Symbol("prop5")];
        }
    });

    var proxy2 = new Proxy(proxy, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy2 : ' + property.toString());
            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy2');
            return ["prop2", "prop3", Symbol("prop4"), Symbol("prop5")];
        }
    });

    print('***Testing Object.getOwnPropertyNames()');
    print(Object.getOwnPropertyNames(proxy2));
    print('***Testing Object.keys()');
    print(Object.keys(proxy2));
    print('***Testing Object.getOwnPropertySymbols()');
    print(Object.getOwnPropertySymbols(proxy2).length);

    print('***Testing Object.freeze()');
    try{
        Object.freeze(proxy2);
        print('Object.freeze should fail because underlying OwnPropertyKeys should fail since target becomes non-extensible');
    } catch (e) {
        if (!(e instanceof TypeError)) {
            $ERROR('incorrect instanceof Error' + e);
        }
    }
}

// Verifies that we don't call GetPropertyDescriptor of target for Object.keys unnecessarily if we throw TypeERROR before
function test2() {
    var obj = {};
    Object.defineProperty(obj, "a", { value: 5, configurable: false });
    var proxy = new Proxy(obj, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy : ' + property.toString());
            return Object.getOwnPropertyDescriptor(target, property);
        },

        ownKeys: function (target) {
            print('ownKeys for proxy');
            return ["a", "prop0", "prop1", Symbol("prop2"), Symbol("prop5")];
        }
    });

    var proxy2 = new Proxy(proxy, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy2 : ' + property.toString());
            return Object.getOwnPropertyDescriptor(target, property);
        },

        ownKeys: function (target) {
            print('ownKeys for proxy2');
            return ["prop2", "prop3", Symbol("prop4"), Symbol("prop5")];
        }
    });

    print('***Testing Object.keys()');
    try{
        print(Object.keys(proxy2));
        print('Should throw TypeError because ownKeys doesnt return non-configurable key.');
    } catch (e) {
        if (!(e instanceof TypeError)) {
            print('incorrect instanceof Error');
        }
    }
}

function test3() {
    var obj = {};
    var count = 0;
    var proxy = new Proxy(obj, {

        get: function (target, property, receiver) {
            print('get on proxy : ' + property.toString());
            return count++ * 5;
        },
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy : ' + property.toString());
            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy');
            return ["prop0", "prop1", Symbol("prop2"), Symbol("prop5")];
        }
    });

    var proxy2 = new Proxy(proxy, {
        get: function (target, property, receiver) {
            print('get on proxy2 : ' + property.toString());
            return Reflect.get(target, property, receiver);
        },
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy2 : ' + property.toString());

            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy2');
            return ["prop2", "prop3",  Symbol("prop4"), Symbol("prop5")];
        }
    });

    print('***Testing Object.assign()');
    var answer = Object.assign(obj, null, proxy, proxy2);
    var symbols = Object.getOwnPropertySymbols(answer);
    var names = Object.getOwnPropertyNames(answer);
    print("PropertyNames returned : ");
    for (i = 0; i < names.length; i++)
    {
        print(names[i].toString())
    }
    print("PropertySymbols returned : ");
    for (i = 0; i < symbols.length; i++)
    {
        print(symbols[i].toString())
    }

}

function test4() {
    print("***Traps whose value is null are ignored");

    function getProxy(trap, result, obj) {
        const proxy = new Proxy(obj, {
            [trap]: () => {
                print(`"${trap}" called`);
                return result;
            }
        });
        return new Proxy(proxy, {
            [trap]: null
        });
    }

    Object.getPrototypeOf(getProxy("getPrototypeOf", {}, {}));
    Object.setPrototypeOf(getProxy("setPrototypeOf", true, {}), {});
    Object.isExtensible(getProxy("isExtensible", true, {}));
    Object.preventExtensions(getProxy("preventExtensions", false, {}));
    Object.getOwnPropertyDescriptor(getProxy("getOwnPropertyDescriptor", undefined, {}));
    Object.defineProperty(getProxy("defineProperty", true, {}), "prop", { value: 0 });
    "prop" in getProxy("has", true, {});
    getProxy("get", 0, {}).prop;
    getProxy("set", true, {}).prop = 0;
    delete getProxy("deleteProperty", true, {}).prop;
    Object.keys(getProxy("ownKeys", [], {}));
    getProxy("apply", 0, function () {})();
    new (getProxy("construct", {}, function () {}));
}

function test5() {
    print("***function wrapped in 2+ proxies");

    function a() {}

    const p1 = new Proxy(a, {})
    console.log(typeof p1) // "function"

    const p2 = new Proxy(p1, {})
    console.log(typeof p2) // "object" but should be "function"

    const p3 = new Proxy(p2, {})
    console.log(typeof p3) // "object" but should be "function"
}

function test6() {
    print("*** proxied function and Object.prototype.toString.call");

    console.log(Object.prototype.toString.call(new Proxy(function a() {}, {})));
    // "[object Function]"

    console.log(Object.prototype.toString.call(new Proxy(new Proxy(function a() {}, {}), {})));
    // "[object Function]"

    console.log(Object.prototype.toString.call(new Proxy([], {})));
    // "[object Array]"

    console.log(Object.prototype.toString.call(new Proxy(new Number(1), {})));
    // "[object Object]"

    console.log(Object.prototype.toString.call(new Proxy(new String(""), {})));
    // "[object Object]"

    console.log(Object.prototype.toString.call(new Proxy(new Boolean(true), {})));
    // "[object Object]"

    console.log(Object.prototype.toString.call(new Proxy(new Date, {})));
    // "[object Object]"
}

function test7() {
    print("*** proxied function and Function.prototype.toString.call");

    console.log(Function.prototype.toString.call(new Proxy(function a() { }, {})));
    // "[object Function]"

    console.log(Function.prototype.toString.call(new Proxy(new Proxy(function a() { }, {}), {})));
    // "[object Function]"
}

test1();
test2();
test3();
test4();
test5();
test6();
test7();
<commit_msg>PR feedback<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

// Verifies the order of getOwnPropertyDescriptor trap called for ownKeys
function test1() {
    var obj = {};
    var proxy = new Proxy(obj, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy : ' + property.toString());
            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy');
            return ["prop0", "prop1", Symbol("prop2"), Symbol("prop5")];
        }
    });

    var proxy2 = new Proxy(proxy, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy2 : ' + property.toString());
            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy2');
            return ["prop2", "prop3", Symbol("prop4"), Symbol("prop5")];
        }
    });

    print('***Testing Object.getOwnPropertyNames()');
    print(Object.getOwnPropertyNames(proxy2));
    print('***Testing Object.keys()');
    print(Object.keys(proxy2));
    print('***Testing Object.getOwnPropertySymbols()');
    print(Object.getOwnPropertySymbols(proxy2).length);

    print('***Testing Object.freeze()');
    try{
        Object.freeze(proxy2);
        print('Object.freeze should fail because underlying OwnPropertyKeys should fail since target becomes non-extensible');
    } catch (e) {
        if (!(e instanceof TypeError)) {
            $ERROR('incorrect instanceof Error' + e);
        }
    }
}

// Verifies that we don't call GetPropertyDescriptor of target for Object.keys unnecessarily if we throw TypeERROR before
function test2() {
    var obj = {};
    Object.defineProperty(obj, "a", { value: 5, configurable: false });
    var proxy = new Proxy(obj, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy : ' + property.toString());
            return Object.getOwnPropertyDescriptor(target, property);
        },

        ownKeys: function (target) {
            print('ownKeys for proxy');
            return ["a", "prop0", "prop1", Symbol("prop2"), Symbol("prop5")];
        }
    });

    var proxy2 = new Proxy(proxy, {
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy2 : ' + property.toString());
            return Object.getOwnPropertyDescriptor(target, property);
        },

        ownKeys: function (target) {
            print('ownKeys for proxy2');
            return ["prop2", "prop3", Symbol("prop4"), Symbol("prop5")];
        }
    });

    print('***Testing Object.keys()');
    try{
        print(Object.keys(proxy2));
        print('Should throw TypeError because ownKeys doesnt return non-configurable key.');
    } catch (e) {
        if (!(e instanceof TypeError)) {
            print('incorrect instanceof Error');
        }
    }
}

function test3() {
    var obj = {};
    var count = 0;
    var proxy = new Proxy(obj, {

        get: function (target, property, receiver) {
            print('get on proxy : ' + property.toString());
            return count++ * 5;
        },
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy : ' + property.toString());
            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy');
            return ["prop0", "prop1", Symbol("prop2"), Symbol("prop5")];
        }
    });

    var proxy2 = new Proxy(proxy, {
        get: function (target, property, receiver) {
            print('get on proxy2 : ' + property.toString());
            return Reflect.get(target, property, receiver);
        },
        getOwnPropertyDescriptor: function (target, property) {
            print('getOwnPropertyDescriptor on proxy2 : ' + property.toString());

            return { configurable: true, enumerable: true, value: 10 };
        },

        ownKeys: function (target) {
            print('ownKeys for proxy2');
            return ["prop2", "prop3",  Symbol("prop4"), Symbol("prop5")];
        }
    });

    print('***Testing Object.assign()');
    var answer = Object.assign(obj, null, proxy, proxy2);
    var symbols = Object.getOwnPropertySymbols(answer);
    var names = Object.getOwnPropertyNames(answer);
    print("PropertyNames returned : ");
    for (i = 0; i < names.length; i++)
    {
        print(names[i].toString())
    }
    print("PropertySymbols returned : ");
    for (i = 0; i < symbols.length; i++)
    {
        print(symbols[i].toString())
    }

}

function test4() {
    print("***Traps whose value is null are ignored");

    function getProxy(trap, result, obj) {
        const proxy = new Proxy(obj, {
            [trap]: () => {
                print(`"${trap}" called`);
                return result;
            }
        });
        return new Proxy(proxy, {
            [trap]: null
        });
    }

    Object.getPrototypeOf(getProxy("getPrototypeOf", {}, {}));
    Object.setPrototypeOf(getProxy("setPrototypeOf", true, {}), {});
    Object.isExtensible(getProxy("isExtensible", true, {}));
    Object.preventExtensions(getProxy("preventExtensions", false, {}));
    Object.getOwnPropertyDescriptor(getProxy("getOwnPropertyDescriptor", undefined, {}));
    Object.defineProperty(getProxy("defineProperty", true, {}), "prop", { value: 0 });
    "prop" in getProxy("has", true, {});
    getProxy("get", 0, {}).prop;
    getProxy("set", true, {}).prop = 0;
    delete getProxy("deleteProperty", true, {}).prop;
    Object.keys(getProxy("ownKeys", [], {}));
    getProxy("apply", 0, function () {})();
    new (getProxy("construct", {}, function () {}));
}

function test5() {
    print("***function wrapped in 2+ proxies");

    function a() {}

    const p1 = new Proxy(a, {})
    console.log(typeof p1) // "function"

    const p2 = new Proxy(p1, {})
    console.log(typeof p2) // "function"

    const p3 = new Proxy(p2, {})
    console.log(typeof p3) // "function"
}

function test6() {
    print("*** proxied function and Object.prototype.toString.call");

    console.log(Object.prototype.toString.call(new Proxy(function a() {}, {})));
    // "[object Function]"

    console.log(Object.prototype.toString.call(new Proxy(new Proxy(function a() {}, {}), {})));
    // "[object Function]"

    console.log(Object.prototype.toString.call(new Proxy([], {})));
    // "[object Array]"

    console.log(Object.prototype.toString.call(new Proxy(new Number(1), {})));
    // "[object Object]"

    console.log(Object.prototype.toString.call(new Proxy(new String(""), {})));
    // "[object Object]"

    console.log(Object.prototype.toString.call(new Proxy(new Boolean(true), {})));
    // "[object Object]"

    console.log(Object.prototype.toString.call(new Proxy(new Date, {})));
    // "[object Object]"
}

function test7() {
    print("*** proxied function and Function.prototype.toString.call");

    console.log(Function.prototype.toString.call(new Proxy(function a() { }, {})));
    // "function a() { }"

    console.log(Function.prototype.toString.call(new Proxy(new Proxy(function a() { }, {}), {})));
    // "function a() { }"
}

test1();
test2();
test3();
test4();
test5();
test6();
test7();
<|endoftext|>


<commit_before>function translate(sourceLang, destLang, sourceId, destId, loadingId) {
	$(destId).hide();
	$(loadingId).show();
	$.post('/translate', {
	    text: $(sourceId).text(),
	    sourceLang: sourceLang,
	    destLang: destLang
	}).done(function(translated) {
	    $(destId).text(translated['text'])
	    $(loadingId).hide();
	    $(destId).show();
	}).fail(function() {
	    $(destId).text("{{ _('Error: Could not contact server.') }}");
	    $(loadingId).hide();
	    $(destId).show();
	});
}

function processNetResults(result) {
        var text = "";

        for(var i=0, count=result.length; i<count; i++) {
            text += result[i].text+'';
        }
        document.getElementById('votd').innerHTML = text;
}

function loadNetText(reference) {
        var script = document.createElement('script');
        script.setAttribute('src', 'http://labs.bible.org/api/?passage='+escape(reference)+'&type=json&callback=processNetResults');
        document.getElementsByTagName('head')[0].appendChild(script);
}

$(document).ready(function() {
        $('#public').change(function() {
            $('.js-groups').slideToggle('slow');
        });
        // Hide groups because default is public.
        $('.js-groups').hide();

        $('.js-show-post-options').click(function() {
            $('.fake-link', this).hide();
            $('.js-post-options', this).show('slow');
        });
        /* Hide options until requested to be shown.
        *  Set as inline in base.css then hide so,
        *  jquery will revert back to inline when 'show().'
        */
        $('.js-post-options', this).hide();

	/*$.ajax({  //Fix this to use jquery.
	    type: 'GET',
	    url: 'http://labs.bible.org/api/?passage=votd&type=json',
	    dataType: 'jsonp',
 	    success: function(data) {
	        $('#votd').html(data);
	    },
	    error: function(e) {
		console.log(e.message);
	    }
	});*/
        loadNetText('votd');

});

<commit_msg>Format votd<commit_after>function translate(sourceLang, destLang, sourceId, destId, loadingId) {
	$(destId).hide();
	$(loadingId).show();
	$.post('/translate', {
	    text: $(sourceId).text(),
	    sourceLang: sourceLang,
	    destLang: destLang
	}).done(function(translated) {
	    $(destId).text(translated['text'])
	    $(loadingId).hide();
	    $(destId).show();
	}).fail(function() {
	    $(destId).text("{{ _('Error: Could not contact server.') }}");
	    $(loadingId).hide();
	    $(destId).show();
	});
}

function processNetResults(result) {
        var text = '' + result[0].bookname + ' ';

        for(var i=0, count=result.length; i<count; i++) {
            text += '' + result[i].verse + ' ' + result[i].text+' ';
        }
        document.getElementById('votd').innerHTML = text;
}

function loadNetText(reference) {
        var script = document.createElement('script');
        script.setAttribute('src', 'http://labs.bible.org/api/?passage='+escape(reference)+'&type=json&callback=processNetResults');
        document.getElementsByTagName('head')[0].appendChild(script);
}

$(document).ready(function() {
        $('#public').change(function() {
            $('.js-groups').slideToggle('slow');
        });
        // Hide groups because default is public.
        $('.js-groups').hide();

        $('.js-show-post-options').click(function() {
            $('.fake-link', this).hide();
            $('.js-post-options', this).show('slow');
        });
        /* Hide options until requested to be shown.
        *  Set as inline in base.css then hide so,
        *  jquery will revert back to inline when 'show().'
        */
        $('.js-post-options', this).hide();

	/*$.ajax({  //Fix this to use jquery.
	    type: 'GET',
	    url: 'http://labs.bible.org/api/?passage=votd&type=json',
	    dataType: 'jsonp',
 	    success: function(data) {
	        $('#votd').html(data);
	    },
	    error: function(e) {
		console.log(e.message);
	    }
	});*/
        loadNetText('votd');

});

<|endoftext|>


<commit_before>//'use strict'
// TODO: refactor this

createListItem = function(list, name) {
    let li = document.createElement('li');
    let article = document.createElement('article');
    article.innerHTML = '<h2>' + name + '</h2>'
    li.appendChild(article);

    list.appendChild(li);
}

updateList = function(list) {
    fetch('/api/v1/rooms/test/members/', {
	    method: 'get'
    }).then((response) => {
        return response.json();
    }).then((members) => {
        members.forEach((member) => {
            createListItem(list, member.name)
        });
    }).catch(function(error) {
	    alert(error);
    });
}

document.addEventListener("DOMContentLoaded", (event) => {

    let listMembers = document.querySelector('#members-list');
    let listWinners = document.querySelector('#winners-list');
    let addMemberForm = document.querySelector('#add-member-form');
    let selectWinnersButton = document.querySelector('#select-winners-button');

    selectWinnersButton.addEventListener('click', (event) => {
        fetch('/api/v1/rooms/test/members/?random=3', {
	        method: 'get',
        }).then((response) => {
            //alert(response.status)
            return response.json();
        }).then((winners) => {
            listWinners.innerHTML='';
            winners.forEach((member) => {
                createListItem(listWinners, member.name);
        });
        }).catch((error) => {
	        alert(error);
        });
    })

    addMemberForm.addEventListener('submit', (event) => {
        event.preventDefault();
        fetch('/api/v1/rooms/test/members/', {
	        method: 'post',
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
		        name: event.target.elements['name'].value.trim()
	        })
        }).then((response) => {
            if (response.status != 409) {
                return response.json()
            }
            return null
        }).then((newMember) => {
            if (newMember) {
                createListItem(listMembers, newMember.name)
            }
        }).catch((error) => {
	        alert(error);
        });
    })

    updateList(listMembers);
});<commit_msg>Add ability to remove members<commit_after>//'use strict'
// TODO: refactor this

createListItem = function(list, name) {
    let liseItemTemplate = document.querySelector('#members-list-item-template');
    let listItem = document.importNode(liseItemTemplate.content, true);
    listItem.querySelector('.member-name').innerHTML = name;

    list.appendChild(listItem);
}

updateList = function(list) {
    fetch('/api/v1/rooms/test/members/', {
	    method: 'get'
    }).then((response) => {
        return response.json();
    }).then((members) => {
        members.forEach((member) => {
            createListItem(list, member.name)
        });
    }).catch(function(error) {
	    alert(error);
    });
}

document.addEventListener("DOMContentLoaded", (event) => {
    let listMembers = document.querySelector('#members-list');
    let listWinners = document.querySelector('#winners-list');

    let addMemberForm = document.querySelector('#add-member-form');

    let selectWinnersButton = document.querySelector('#select-winners-button');

    selectWinnersButton.addEventListener('click', (event) => {
        fetch('/api/v1/rooms/test/members/?random=3', {
	        method: 'get',
        }).then((response) => {
            //alert(response.status)
            return response.json();
        }).then((winners) => {
            listWinners.innerHTML='';
            winners.forEach((member) => {
                createListItem(listWinners, member.name);
        });
        }).catch((error) => {
	        alert(error);
        });
    });

    addMemberForm.addEventListener('submit', (event) => {
        event.preventDefault();
        fetch('/api/v1/rooms/test/members/', {
	        method: 'post',
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
		        name: event.target.elements['name'].value.trim()
	        })
        }).then((response) => {
            if (response.status != 409) {
                return response.json()
            }
            return null
        }).then((newMember) => {
            if (newMember) {
                createListItem(listMembers, newMember.name)
            }
        }).catch((error) => {
	        alert(error);
        });
    });

    listMembers.addEventListener('click', (event) => {
        if (event.target.tagName == 'BUTTON') {
            let listEntry = event.target.closest('li');
            name = listEntry.querySelector('.member-name').innerHTML;

            fetch('/api/v1/rooms/test/members/' + name, {
	            method: 'delete'
            }).then((response) => {
                if (response.status === 204) {
                    listEntry.setAttribute('hidden', true);
                }
            }).catch(function(error) {
	            alert(error);
            });
        }
    });

    updateList(listMembers);
});<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @namespace google
 */
/**
 * @namespace google.cloud
 */
/**
 * @namespace google.cloud.securitycenter
 */
/**
 * @namespace google.cloud.securitycenter.v1beta1
 */
/**
 * @namespace google.iam.v1
 */
/**
 * @namespace google.protobuf
 */
/**
 * @namespace google.longrunning
 */
/**
 * @namespace google.rpc
 */

'use strict';

// Import the clients for each version supported by this package.
const gapic = Object.freeze({
  v1beta1: require('./v1beta1'),
});

/**
 * The `securitycenter` package has the following named exports:
 *
 * - `SecurityCenterClient` - Reference to
 *   {@link v1beta1.SecurityCenterClient}
 * - `v1beta1` - This is used for selecting or pinning a
 *   particular backend service version. It exports:
 *     - `SecurityCenterClient` - Reference to
 *       {@link v1beta1.SecurityCenterClient}
 *
 * @module {object} @google-cloud/securitycenter
 * @alias nodejs-securitycenter
 *
 * @example
Install the client library with npm:

 * npm install --save securitycenter
 *
 * @example
Import the client library:

 * const securitycenter = require('securitycenter');
 *
 * @example
Create a client that uses Application Default Credentials (ADC):

 * const client = new securitycenter.SecurityCenterClient();
 *
 * @example
Create a client with explicit credentials:

 * const client = new securitycenter.SecurityCenterClient({
 *   projectId: 'your-project-id',
 *   keyFilename: '/path/to/keyfile.json',
 * });
 */

/**
 * @type {object}
 * @property {constructor} SecurityCenterClient
 *   Reference to {@link v1beta1.SecurityCenterClient}
 */
module.exports = gapic.v1beta1;

/**
 * @type {object}
 * @property {constructor} SecurityCenterClient
 *   Reference to {@link v1beta1.SecurityCenterClient}
 */
module.exports.v1beta1 = gapic.v1beta1;

// Alias `module.exports` as `module.exports.default`, for future-proofing.
module.exports.default = Object.assign({}, module.exports);
<commit_msg>fix(docs): require stmt (#29)<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @namespace google
 */
/**
 * @namespace google.cloud
 */
/**
 * @namespace google.cloud.securitycenter
 */
/**
 * @namespace google.cloud.securitycenter.v1beta1
 */
/**
 * @namespace google.iam.v1
 */
/**
 * @namespace google.protobuf
 */
/**
 * @namespace google.longrunning
 */
/**
 * @namespace google.rpc
 */

'use strict';

// Import the clients for each version supported by this package.
const gapic = Object.freeze({
  v1beta1: require('./v1beta1'),
});

/**
 * The `securitycenter` package has the following named exports:
 *
 * - `SecurityCenterClient` - Reference to
 *   {@link v1beta1.SecurityCenterClient}
 * - `v1beta1` - This is used for selecting or pinning a
 *   particular backend service version. It exports:
 *     - `SecurityCenterClient` - Reference to
 *       {@link v1beta1.SecurityCenterClient}
 *
 * @module {object} @google-cloud/security-center
 * @alias nodejs-securitycenter
 *
 * @example
Install the client library with npm:

 * npm install --save @google-cloud/security-center
 *
 * @example
Import the client library:

 * const securitycenter = require('@google-cloud/security-center');
 *
 * @example
Create a client that uses Application Default Credentials (ADC):

 * const client = new securitycenter.SecurityCenterClient();
 *
 * @example
Create a client with explicit credentials:

 * const client = new securitycenter.SecurityCenterClient({
 *   projectId: 'your-project-id',
 *   keyFilename: '/path/to/keyfile.json',
 * });
 */

/**
 * @type {object}
 * @property {constructor} SecurityCenterClient
 *   Reference to {@link v1beta1.SecurityCenterClient}
 */
module.exports = gapic.v1beta1;

/**
 * @type {object}
 * @property {constructor} SecurityCenterClient
 *   Reference to {@link v1beta1.SecurityCenterClient}
 */
module.exports.v1beta1 = gapic.v1beta1;

// Alias `module.exports` as `module.exports.default`, for future-proofing.
module.exports.default = Object.assign({}, module.exports);
<|endoftext|>


<commit_before>var buster = require('buster'),
	mask = require('../lib/mask.node.js'),
	Expression = mask.Utils.Expression,
	$eval = mask.Utils.Expression.eval,
	template, node, attr;

function expression(expr, result, model, cntx, controller) {
	if (expr instanceof Array) {
		for (var i = 0, x, length = expr.length; i < length; i++) {
			x = expr[i];
			expression(x, result, model, cntx, controller);
		}
		return;
	}

	var ast = Expression.parse(expr),
		value = Expression.eval(ast, model, cntx, controller);

	assert.equals(value, result, 'Unexpected Result (' + expr + ')');
}

buster.testCase("Expressions", {
	'concat': function() {
		expression([ //
		'5+"hello"', //
		' 5 + "hello"', //
		' 5 + "hello" + ""', //
		'"" + 5 + "hello"', //
		"'' + 5 + 'hello'", "'' + 5 + 'h' + 'e' + \"l\" + 'l' + 'o'", "'' + ('5' + 'h' + 'e') + (\"l\" + 'l' + 'o')", //
		"'' + ('5' + ('h' + 'e') + (\"l\" ) +  'l' + 'o')", //
		"5 + fn()", //
		"5 + fn2()", //
		"5 + hello", //
		"1 + 2*2 + hello"], '5hello', {
			hello: "hello",
			fn: function() {
				return "hello";
			}
		}, null, {
			parent: {
				fn2: function() {
					return "hello"
				}
			}
		});
	},
	'math': function() {
		expression([ //
		'10', //
		'5+5', //
		'6+1+3', //
		'15-5', //
		'5*2', //
		'20/2', //
		'2*(2+3)', //
		'2+2*4', //
		'3 * (2+3) - 5', //
		'(5*1)*1/5+9', //
		'(5 * 1) * 1 / 5 +   9 ', //
		'(((5 / 1) / 1) / 5) +   9 ', //
		'((((5 / 1) / 1) / 5) +   9 )', //
		'(5 * 1) * 1 / 5 + 1 + (4 * 2)', //
		'-(-10)'], 10);

		expression(['a + b+b', //
		'_c*c3+4+a', //
		'fn(5)', //
		'fn(3) + fn(2)', //
		'fn(3) + fn(1) +fn(1)', //
		'fn(3,4) + fn(4,3) + fn(2,-2)', //
		], 20, {
			a: 10,
			b: 5,
			_c: 2,
			c3: 3,
			fn: function(n, x) {
				return n * (x || 4);
			}
		});

	},
	'condition': function() {
		expression([ //
		'5==5', //
		'6!=5', //
		'3>2', //
		'2>=2', //
		'3>=2', //
		'2<3', //
		'2<=3', //
		'3<=3', //
		'0.01 == 0.01', //

		'3<=3 && "a"=="a"', //
		'3<=3 && "a"!="b"', //
		'3==3 && 2 != 5 || 1==0', //
		'3==3 && 2 == 5 || 0.5==.5', //

		'name=="A" && number == 10', //
		'a == b + b', //
		'a + 5 == b * 3', //
		'!(false)', //
		'!0', //
		'a == b || !(a==5) ', //
		'!!true', //
		'!null', //
		], true, {
			name: 'A',
			number: 10,
			a: 10,
			b: 5
		})
	},
	'ternary': function() {
		expression(['enabled?"enabled":"disabled"'], 'enabled', {
			enabled: true
		});
	}
});
<commit_msg>[update] test<commit_after>var buster = require('buster'),
	mask = require('../lib/mask.node.js'),
	Expression = mask.Utils.Expression,
	$eval = mask.Utils.Expression.eval,
	template, node, attr;

function expression(expr, result, model, cntx, controller) {
	if (expr instanceof Array) {
		for (var i = 0, x, length = expr.length; i < length; i++) {
			x = expr[i];
			expression(x, result, model, cntx, controller);
		}
		return;
	}

	var ast = Expression.parse(expr),
		value = Expression.eval(ast, model, cntx, controller);

	assert.equals(value, result, 'Unexpected Result (' + expr + ')');
}

buster.testCase("Expressions", {
	'concat': function() {
		expression([ //
		'5+"hello"', //
		' 5 + "hello"', //
		' 5 + "hello" + ""', //
		'"" + 5 + "hello"', //
		"'' + 5 + 'hello'", "'' + 5 + 'h' + 'e' + \"l\" + 'l' + 'o'", "'' + ('5' + 'h' + 'e') + (\"l\" + 'l' + 'o')", //
		"'' + ('5' + ('h' + 'e') + (\"l\" ) +  'l' + 'o')", //
		"5 + fn()", //
		"5 + fn2()", //
		"5 + hello", //
		"1 + 2*2 + hello"], '5hello', {
			hello: "hello",
			fn: function() {
				return "hello";
			}
		}, null, {
			parent: {
				fn2: function() {
					return "hello"
				}
			}
		});
	},
	'math': function() {
		expression([ //
		'10', //
		'5+5', //
		'6+1+3', //
		'15-5', //
		'5*2', //
		'20/2', //
		'2*(2+3)', //
		'2+2*4', //
		'3 * (2+3) - 5', //
		'(5*1)*1/5+9', //
		'(5 * 1) * 1 / 5 +   9 ', //
		'(((5 / 1) / 1) / 5) +   9 ', //
		'((((5 / 1) / 1) / 5) +   9 )', //
		'(5 * 1) * 1 / 5 + 1 + (4 * 2)', //
		'-(-10)'], 10);

		expression(['a + b+b', //
		'_c*c3+4+a', //
		'fn(5)', //
		'fn(3) + fn(2)', //
		'fn(3) + fn(1) +fn(1)', //
		'fn(3,4) + fn(4,3) + fn(2,-2)', //
		], 20, {
			a: 10,
			b: 5,
			_c: 2,
			c3: 3,
			fn: function(n, x) {
				return n * (x || 4);
			}
		});

	},
	'condition': function() {
		expression([ //
		'5==5', //
		'6!=5', //
		'3>2', //
		'2>=2', //
		'3>=2', //
		'2<3', //
		'2<=3', //
		'3<=3', //
		'0.01 == 0.01', //

		'3<=3 && "a"=="a"', //
		'3<=3 && "a"!="b"', //
		'3==3 && 2 != 5 || 1==0', //
		'3==3 && 2 == 5 || 0.5==.5', //

		'name=="A" && number == 10', //
		'a == b + b', //
		'a + 5 == b * 3', //
		'!(false)', //
		'!0', //
		'a == b || !(a==5) ', //
		'!!true', //
		'!null', //
		], true, {
			name: 'A',
			number: 10,
			a: 10,
			b: 5
		})
	},
	'ternary': function() {
		expression(['enabled?"enabled":"disabled"'], 'enabled', {
			enabled: true
		});
	},

	'OR': function(){
		expression(['a || b', '."some-key" || b'], '1', {
			a: 1,
			b: 2,
			'some-key': 1
		});
	}
});
<|endoftext|>


<commit_before>import styles from './Layout.css';
import React from 'react';
import Head from 'cxx/head';
import Link from 'cxx/link';

const Layout = ({ title, titleTemplate, children }) =>

Hello World Example

      <Link href="/">Home</Link>
      <Link href="/hello">Hello</Link>
      <Link href="/world">World</Link>
      Graphiql

    {children}

;

Layout.defaultProps = {
  titleTemplate: '%s - Hello World Example'
};

export default Layout;
<commit_msg>update <commit_after>import styles from './Layout.css';
import React from 'react';
import Head from 'cxx/head';
import Link from 'cxx/link';

const metas = [
  { charset: 'utf-8' },
  { httpEquiv: 'X-UA-Compatible', content: 'IE=edge' },
  { name: 'renderer', content: 'webkit' },
  {
    name: 'viewport',
    content:
      'width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no'
  }
];

const Layout = ({ title, titleTemplate, children }) =>

Hello World Example

      <Link href="/">Home</Link>
      <Link href="/hello">Hello</Link>
      <Link href="/world">World</Link>
      Graphiql

    {children}

;

Layout.defaultProps = {
  titleTemplate: '%s - Hello World Example'
};

export default Layout;
<|endoftext|>


<commit_before>"use strict";
const config = require(__base+'config'),
      PokemonSighting = require(__appbase + 'models/pokemonSighting'),
      common = require(__base + 'app/services/common'),
      moment = require('moment'),
      request = require('request'),
      twitterLinkLength = 23;

module.exports = {
    /*
     * inserting the pokemon sighting details extracted from twitter
     */
    add: function (data, pokemonName) {

        let location = null,
            pokemonId = parseInt(common.getPokemonIdByName(pokemonName)),
            pokemonSighting = new PokemonSighting({source: config.pokemonDataSources.twitter, pokemonId: pokemonId, appearedOn: moment.unix(data.timestamp_ms/1000)});

       /* */

        //get the location of the tweet if exist
        var pokemonFoundLongitude;
        var pokemonFoundLatitude;
        if (data.coordinates){
            pokemonFoundLongitude = data.coordinates.coordinates[0];
            pokemonFoundLatitude = data.coordinates.coordinates[1];
            location = {type: "Point",coordinates: [pokemonFoundLongitude, pokemonFoundLatitude]};
            savePokemonSighthing(pokemonSighting);
        } else if(data.text.indexOf('https://t.co') != -1) {
                let url = data.text.substr(data.text.indexOf('https://t.co'), twitterLinkLength);
                logger.info(url);
                request.get(url)
                .on('response', function(response) {
                    if(response.statusCode == 200) {
                        // check if the link is related to google maps
                        if(typeof response.request.uri !== 'undefined' && response.request.uri.host === "www.google.com" && typeof response.request.uri.pathname !== 'undefined') {
                            let googleMapsPath = response.request.uri.pathname;
                            logger.info(googleMapsPath);

                            // check the link path and get the latitude and longitude
                            if(googleMapsPath.indexOf('search') != -1) { // path is of the form /maps/place/40.4377315739453,-79.9990332286566
                                pokemonFoundLatitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf('search/') + 7, googleMapsPath.indexOf(',') - googleMapsPath.indexOf('search/') - 5 ));
                                pokemonFoundLongitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf(',') + 1, googleMapsPath.length));
                            } else if(googleMapsPath.indexOf('place') != -1) { // path is of the form /maps/search/40.4377315739453,-79.9990332286566
                                pokemonFoundLatitude = parseFloat(googleMapsPath.substr(googleMapsPath.lastIndexOf('place/') + 6, googleMapsPath.indexOf(',') - googleMapsPath.lastIndexOf('place/') - 5));
                                pokemonFoundLongitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf(',') + 1, googleMapsPath.length));
                            } else if(googleMapsPath.indexOf('Location') != -1) { // path is of the form /maps/current+Location/40.4377315739453,-79.9990332286566
                                pokemonFoundLatitude = parseFloat(googleMapsPath.substr(googleMapsPath.lastIndexOf('Location/') + 9, googleMapsPath.indexOf(',') - googleMapsPath.lastIndexOf('Location/') - 7));
                                pokemonFoundLongitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf(',') + 1, googleMapsPath.length));
                            }

                            location = {type: "Point",coordinates: [pokemonFoundLongitude, pokemonFoundLatitude]};
                            savePokemonSighthing(pokemonSighting);
                        } else {
                            // save null location when link is not google maps related
                            savePokemonSighthing(pokemonSighting);
                        }
                    } else {
                        // save null location when response is not 200
                        savePokemonSighthing(pokemonSighting);
                    }
                });
        } else {
            // save null location when no location related data is found
            savePokemonSighthing(pokemonSighting);
        }

        function savePokemonSighthing(pokemonSighting) {
            pokemonSighting.location = location;
            // saving the data to the database
            pokemonSighting.save(function (err) {
                // on error
                if (err) {
                    logger.error("Error while saving pokmon sighting from source twitter ");
                }
                // on success
                else {
                    logger.info("Pokemon sighting data saved successfully from source twitter ");
                }
            });
        }
    }
};<commit_msg>udpated comments<commit_after>"use strict";
const config = require(__base+'config'),
      PokemonSighting = require(__appbase + 'models/pokemonSighting'),
      common = require(__base + 'app/services/common'),
      moment = require('moment'),
      request = require('request'),
      twitterLinkLength = 23;

module.exports = {
    /*
     * inserting the pokemon sighting details extracted from twitter
     */
    add: function (data, pokemonName) {

        let location = null,
            pokemonId = parseInt(common.getPokemonIdByName(pokemonName)),
            pokemonSighting = new PokemonSighting({source: config.pokemonDataSources.twitter, pokemonId: pokemonId, appearedOn: moment.unix(data.timestamp_ms/1000)});

       /* */

        //get the location of the tweet if exist
        var pokemonFoundLongitude;
        var pokemonFoundLatitude;
        if (data.coordinates){
            pokemonFoundLongitude = data.coordinates.coordinates[0];
            pokemonFoundLatitude = data.coordinates.coordinates[1];
            location = {type: "Point",coordinates: [pokemonFoundLongitude, pokemonFoundLatitude]};
            savePokemonSighthing(pokemonSighting);
        } else if(data.text.indexOf('https://t.co') != -1) { // check if external link exist in the tweet
                let url = data.text.substr(data.text.indexOf('https://t.co'), twitterLinkLength); // get the required external url
                logger.info(url);
                request.get(url)
                .on('response', function(response) {
                    if(response.statusCode == 200) {
                        // check if the link is related to google maps
                        if(typeof response.request.uri !== 'undefined' && response.request.uri.host === "www.google.com" && typeof response.request.uri.pathname !== 'undefined') {
                            let googleMapsPath = response.request.uri.pathname;
                            logger.info(googleMapsPath);

                            // check the link path and get the latitude and longitude
                            if(googleMapsPath.indexOf('search') != -1) { // path is of the form /maps/place/40.4377315739453,-79.9990332286566
                                pokemonFoundLatitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf('search/') + 7, googleMapsPath.indexOf(',') - googleMapsPath.indexOf('search/') - 5 ));
                                pokemonFoundLongitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf(',') + 1, googleMapsPath.length));
                            } else if(googleMapsPath.indexOf('place') != -1) { // path is of the form /maps/search/40.4377315739453,-79.9990332286566
                                pokemonFoundLatitude = parseFloat(googleMapsPath.substr(googleMapsPath.lastIndexOf('place/') + 6, googleMapsPath.indexOf(',') - googleMapsPath.lastIndexOf('place/') - 5));
                                pokemonFoundLongitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf(',') + 1, googleMapsPath.length));
                            } else if(googleMapsPath.indexOf('Location') != -1) { // path is of the form /maps/current+Location/40.4377315739453,-79.9990332286566
                                pokemonFoundLatitude = parseFloat(googleMapsPath.substr(googleMapsPath.lastIndexOf('Location/') + 9, googleMapsPath.indexOf(',') - googleMapsPath.lastIndexOf('Location/') - 7));
                                pokemonFoundLongitude = parseFloat(googleMapsPath.substr(googleMapsPath.indexOf(',') + 1, googleMapsPath.length));
                            }

                            location = {type: "Point",coordinates: [pokemonFoundLongitude, pokemonFoundLatitude]};
                            savePokemonSighthing(pokemonSighting);
                        } else {
                            // save null location when link is not google maps related
                            savePokemonSighthing(pokemonSighting);
                        }
                    } else {
                        // save null location when response is not 200
                        savePokemonSighthing(pokemonSighting);
                    }
                });
        } else {
            // save null location when no location related data is found
            savePokemonSighthing(pokemonSighting);
        }

        function savePokemonSighthing(pokemonSighting) {
            pokemonSighting.location = location;
            // saving the data to the database
            pokemonSighting.save(function (err) {
                // on error
                if (err) {
                    logger.error("Error while saving pokmon sighting from source twitter ");
                }
                // on success
                else {
                    logger.info("Pokemon sighting data saved successfully from source twitter ");
                }
            });
        }
    }
};<|endoftext|>


<commit_before>var factories = {};

Factory = function(name, collection, attributes) {
  this.name = name;
  this.collection = collection;
  this.attributes = attributes;
  this.afterHooks = [];
};

Factory.define = function(name, collection, attributes) {
  factories[name] = new Factory(name, collection, attributes);
};

Factory.get = function(name) {
  return factories[name];
};

Factory.build = function(name, attributes, options) {
  var factory = Factory.get(name);
  var base = {};
  attributes = attributes || {};
  options = options || {};

  if (_.has(factory.collection, 'init'))
    base = factory.collection.init();

  // "raw" attributes without functions evaluated, or dotted properties resolved
  attributes = _.extend(base, factory.attributes, attributes);

  var result = {};

  var walk = function(record, object) {
    _.each(object, function(value, key) {
      // check for a factory being passed in
      if (value instanceof Factory) {
        if (options.insert)
          record[key] = Factory.create(value.name)._id;
        else
          // fake an id here
          record[key] = Random.id();
        return;

      } else if (_.isFunction(value)) {
        value = value.call(result);

      // if an object is passed in, traverse deeper into it
      } else if (_.isObject(value) && !_.isArray(value)) {
        record[key] = record[key] || {};
        return walk(record[key], value);
      }

      var modifier = { $set: {}};
      modifier.$set[key] = value;

      LocalCollection._modify(record, modifier);
    });
  };

  walk(result, attributes);

  if (_.has(factory.collection, 'isValid') && ! factory.collection.isValid(result))
    throw new Meteor.Error('Factory: Invalid Document (' + factory.collection._name + ') ' + EJSON.stringify(result), EJSON.stringify(factory.collection.errors(result)));

  result._id = Random.id();
  return result;
};

Factory._create = function(factoryName, doc) {
  var collection = Factory.get(factoryName).collection;
  var insertId = collection.insert(doc);
  var record = collection.findOne(insertId);
  return record;
};

Factory.create = function(name, attributes) {
  attributes = attributes || {};
  var doc = Factory.build(name, attributes, { insert: true });
  var record = Factory._create(name, doc);

  _.each(Factory.get(name).afterHooks, function(cb) {
    cb(record);
  });

  return record;
};

Factory.extend = function(name, attributes) {
  attributes = attributes || {};
  return _.extend(EJSON.clone(Factory.get(name).attributes), attributes);
};

Factory.create.prototype.after = function(fn) {
  this.afterHooks.push(fn);
  return this;
};
<commit_msg>fix after hook<commit_after>var factories = {};

Factory = function(name, collection, attributes) {
  this.name = name;
  this.collection = collection;
  this.attributes = attributes;
  this.afterHooks = [];
};

Factory.define = function(name, collection, attributes) {
  factories[name] = new Factory(name, collection, attributes);
  return factories[name];
};

Factory.get = function(name) {
  return factories[name];
};

Factory.build = function(name, attributes, options) {
  var factory = Factory.get(name);
  var base = {};
  attributes = attributes || {};
  options = options || {};

  if (_.has(factory.collection, 'init'))
    base = factory.collection.init();

  // "raw" attributes without functions evaluated, or dotted properties resolved
  attributes = _.extend(base, factory.attributes, attributes);

  var result = {};

  var walk = function(record, object) {
    _.each(object, function(value, key) {
      // check for a factory being passed in
      if (value instanceof Factory) {
        if (options.insert)
          record[key] = Factory.create(value.name)._id;
        else
          // fake an id here
          record[key] = Random.id();
        return;

      } else if (_.isFunction(value)) {
        value = value.call(result);

      // if an object is passed in, traverse deeper into it
      } else if (_.isObject(value) && !_.isArray(value)) {
        record[key] = record[key] || {};
        return walk(record[key], value);
      }

      var modifier = { $set: {}};
      modifier.$set[key] = value;

      LocalCollection._modify(record, modifier);
    });
  };

  walk(result, attributes);

  if (_.has(factory.collection, 'isValid') && ! factory.collection.isValid(result))
    throw new Meteor.Error('Factory: Invalid Document (' + factory.collection._name + ') ' + EJSON.stringify(result), EJSON.stringify(factory.collection.errors(result)));

  result._id = Random.id();
  return result;
};

Factory._create = function(factoryName, doc) {
  var collection = Factory.get(factoryName).collection;
  var insertId = collection.insert(doc);
  var record = collection.findOne(insertId);
  return record;
};

Factory.create = function(name, attributes) {
  attributes = attributes || {};
  var doc = Factory.build(name, attributes, { insert: true });
  var record = Factory._create(name, doc);

  _.each(Factory.get(name).afterHooks, function(cb) {
    cb(record);
  });

  return record;
};

Factory.extend = function(name, attributes) {
  attributes = attributes || {};
  return _.extend(EJSON.clone(Factory.get(name).attributes), attributes);
};

Factory.prototype.after = function(fn) {
  this.afterHooks.push(fn);
  return this;
};
<|endoftext|>


<commit_before>import React from "react";
import { View, Picker, StyleSheet } from "react-native";
import { withRouter } from "react-router-dom";
import first from "lodash/first";
import last from "lodash/last";
import dropRight from "lodash/dropRight";

const sortTypes = { hot: "hot", top: "top", new: "new" };

export function getSortType(location) {
  const { pathname } = location;
  if (pathname === "/") {
    return sortTypes.hot;
  }

  const pathParts = pathname.split("/");
  const pathNamedParts = pathParts.filter(Boolean);
  const lastPart = last(pathNamedParts);

  if (sortTypes[lastPart.toLowerCase()]) {
    return sortTypes[lastPart.toLowerCase()];
  }

  // Return the default sortType of hot if we don't know
  return sortTypes.hot;
}

export function getSortRange(location) {
  // TODO
}

export function resolveSortTypePath(location, newSort) {
  const { pathname, search } = location;

  // Depending on if we're on a subreddit or a multireddit
  // We could have differing number of parts in our path.
  const pathParts = pathname.split("/");
  const pathNamedParts = pathParts.filter(Boolean);

  // Handle root case, where currently the user is at the root path
  const atRoot = pathNamedParts.length <= 1;
  if (atRoot) {
    if (pathname === "/" && newSort === "hot") {
      return { pathname, search };
    }

    const newPathname = `/${newSort}`;
    return { pathname: newPathname, search };
  }

  // Handle subreddits and multireddits
  // If we're at the root and we're trying to navigate to a hot sort type
  // We want to preserve the existing path instead of tacking on /hot
  const atListingRoot =
    first(pathNamedParts) === "r" && pathNamedParts.length === 2;
  if (atListingRoot && newSort === "hot") {
    return { pathname, search };
  }

  const hasSortType = sortTypes[last(pathNamedParts)];
  let newParts;
  if (hasSortType) {
    newParts = dropRight(pathParts).concat(newSort);
  } else {
    newParts = pathParts.concat(newSort);
  }

  return { pathname: newParts.join("/"), search };
}

export function resolveSortRangePath(location, newRange) {
  const { pathname, search } = location;
  return { pathname, search };
}

export function PostListSort(props) {
  const { location } = props;

  return (
    <View style={styles.postListSort}>
      <Picker
        selectedValue={getSortType(location)}
        onValueChange={sortType => {
          const nextPath = resolveSortTypePath(location, sortType);
          props.history.push(nextPath);
        }}
      >
        <Picker.Item label="Hot" value={sortTypes.hot} />
        <Picker.Item label="New" value={sortTypes.new} />
        <Picker.Item label="Top" value={sortTypes.top} />
      </Picker>
    </View>
  );
}

const styles = StyleSheet.create({
  postListSort: {
    padding: 16
  }
});

export default withRouter(PostListSort);
<commit_msg>Display.a list of sort ranges<commit_after>import React from "react";
import { View, Picker, StyleSheet } from "react-native";
import { withRouter } from "react-router-dom";
import first from "lodash/first";
import last from "lodash/last";
import dropRight from "lodash/dropRight";

const sortTypes = { hot: "hot", top: "top", new: "new" };
const sortRanges = { day: "day", week: "week", month: "month" };

export function getSortType(location) {
  const { pathname } = location;
  if (pathname === "/") {
    return sortTypes.hot;
  }

  const pathParts = pathname.split("/");
  const pathNamedParts = pathParts.filter(Boolean);
  const lastPart = last(pathNamedParts);

  if (sortTypes[lastPart.toLowerCase()]) {
    return sortTypes[lastPart.toLowerCase()];
  }

  // Return the default sortType of hot if we don't know
  return sortTypes.hot;
}

export function getSortRange(location) {
  // TODO
}

export function resolveSortTypePath(location, newSort) {
  const { pathname, search } = location;

  // Depending on if we're on a subreddit or a multireddit
  // We could have differing number of parts in our path.
  const pathParts = pathname.split("/");
  const pathNamedParts = pathParts.filter(Boolean);

  // Handle root case, where currently the user is at the root path
  const atRoot = pathNamedParts.length <= 1;
  if (atRoot) {
    if (pathname === "/" && newSort === "hot") {
      return { pathname, search };
    }

    const newPathname = `/${newSort}`;
    return { pathname: newPathname, search };
  }

  // Handle subreddits and multireddits
  // If we're at the root and we're trying to navigate to a hot sort type
  // We want to preserve the existing path instead of tacking on /hot
  const atListingRoot =
    first(pathNamedParts) === "r" && pathNamedParts.length === 2;
  if (atListingRoot && newSort === "hot") {
    return { pathname, search };
  }

  const hasSortType = sortTypes[last(pathNamedParts)];
  let newParts;
  if (hasSortType) {
    newParts = dropRight(pathParts).concat(newSort);
  } else {
    newParts = pathParts.concat(newSort);
  }

  return { pathname: newParts.join("/"), search };
}

export function resolveSortRangePath(location, newRange) {
  const { pathname, search } = location;
  return { pathname, search };
}

export function PostListSort(props) {
  const { location } = props;
  const currentSortType = getSortType(location);

  return (
    <View style={styles.postListSort}>
      <Picker
        selectedValue={currentSortType}
        onValueChange={sortType => {
          const nextPath = resolveSortTypePath(location, sortType);
          props.history.push(nextPath);
        }}
      >
        <Picker.Item label="Hot" value={sortTypes.hot} />
        <Picker.Item label="New" value={sortTypes.new} />
        <Picker.Item label="Top" value={sortTypes.top} />
      </Picker>

      {currentSortType === sortTypes.top ? (
        <Picker
          selectedValue={sortRanges.day}
          onValueChange={sortRange => {
            console.log(sortRange);
          }}
        >
          <Picker.Item label="Day" value={sortRanges.day} />
          <Picker.Item label="Week" value={sortRanges.week} />
          <Picker.Item label="Month" value={sortRanges.month} />
        </Picker>
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  postListSort: {
    padding: 16
  }
});

export default withRouter(PostListSort);
<|endoftext|>


<commit_before>
var path = require('path'),
    express = require('express'),
    exctrl = require('exctrl');

module.exports = function () {
  var app = express();

  app.use(express.bodyParser());
  app.use(express.methodOverride());

  exctrl
    .bind(app)
    .load({
      pattern: __dirname + '/api/**/*.controller.js',
      prefix: 'api',
      nameRegExp: /([^\/\\]+).controller.js$/
    });

  app.configure('development', function () {
    app.use(require('connect-livereload')());
    app.use(express.static(path.join(__dirname, 'app')));
    app.use(express.static(path.join(__dirname, '..', '.tmp')));
    app.use(express.static(path.join(__dirname, '..', 'bower_components')));
  });

  app.configure('production', function () {
    app.use(express.static(path.join(__dirname, '..', 'dist')));
  });

  return app;

};
<commit_msg>The express app should use compression by default<commit_after>
var path = require('path'),
    express = require('express'),
    exctrl = require('exctrl');

module.exports = function () {
  var app = express();

  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.compress());

  exctrl
    .bind(app)
    .load({
      pattern: __dirname + '/api/**/*.controller.js',
      prefix: 'api',
      nameRegExp: /([^\/\\]+).controller.js$/
    });

  app.configure('development', function () {
    app.use(require('connect-livereload')());
    app.use(express.static(path.join(__dirname, 'app')));
    app.use(express.static(path.join(__dirname, '..', '.tmp')));
    app.use(express.static(path.join(__dirname, '..', 'bower_components')));
  });

  app.configure('production', function () {
    app.use(express.static(path.join(__dirname, '..', 'dist')));
  });

  return app;

};
<|endoftext|>


<commit_before>import { html } from 'lit-html';
import { define } from 'skatejs';
import withRenderer from '..';

const Component = withRenderer(HTMLElement);

@define
class MyElement extends Component {
  render({ name }) {
    return html`Hello, ${name}!`;
  }
}

it('renders', () => {
  const el = new MyElement();
  expect(el.innerHTML).toEqual('');
  el.renderer(el, el.render.bind(el, { name: 'World' }));
  expect(el.innerHTML).toEqual('Hello, <!---->!');
  el.renderer(el, el.render.bind(el, { name: 'Bob' }));
  expect(el.innerHTML).toEqual('Hello, <!---->!');
});
<commit_msg>Make tests between hyperhtml and lit-html consistent since they're very similar.<commit_after>import { html } from 'lit-html';
import { define } from 'skatejs';
import withRenderer from '..';

const Component = withRenderer(HTMLElement);

function regexContent(text) {
  return new RegExp(`Hello, ${text}!`);
}

@define
class MyElement extends Component {
  render({ name }) {
    return html`Hello, ${name}!`;
  }
}

it('renders', () => {
  const el = new MyElement();
  expect(el.innerHTML).toEqual('');
  el.renderer(el, el.render.bind(el, { name: 'World' }));
  expect(el.innerHTML).toMatch(regexContent('World'));
  el.renderer(el, el.render.bind(el, { name: 'Bob' }));
  expect(el.innerHTML).toMatch(regexContent('Bob'));
});
<|endoftext|>


<commit_before>/**
 * Created by dt on 2016/9/1.
 */
var crypto = require("crypto");

var toString = Object.prototype.toString;

module.exports = {
    /* --数据类型检查---------------------------*/
    isString: function (str) {
        if (toString.call(str) === "[object String]") {
            return true;
        }
        return false;
    },
    isFunction: function (fn) {
        if (toString.call(fn) === "[object Function]") {
            return true;
        }
        return false;
    },
    isObject: function (fn) {
        if (toString.call(fn) === "[object Object]") {
            return true;
        }
        return false;
    },

    /* --数据操作--------------------------*/
    //深拷贝（完美）
    cloneObjectPerfect: function (obj) {
        if (typeof obj === "object") {
            if (util.isArray(obj)) {
                var newArr = [];
                for (var i = 0; i < obj.length; i++) newArr.push(obj[i]);
                return newArr;
            } else {
                var newObj = {};
                for (var key in obj) {
                    newObj[key] = this.cloneObject(obj[key]);
                }
                return newObj;
            }
        } else {
            return obj;
        }
    },
    //深拷贝（缺陷）
    cloneObjectFuck : function(old){
        var latest = JSON.parse(JSON.stringify(old));
        return latest;
    },
    //MD5
    toMD5 :function(content){
        return crypto.createHash('md5').update(content).digest('hex');
    }
};<commit_msg>工具方法添加<commit_after>/**
 * Created by dt on 2016/9/1.
 */
var crypto = require("crypto");

var toString = Object.prototype.toString;

module.exports = {
    /* --数据类型检查---------------------------*/
    isString: function (str) {
        if (toString.call(str) === "[object String]") {
            return true;
        }
        return false;
    },
    isFunction: function (fn) {
        if (toString.call(fn) === "[object Function]") {
            return true;
        }
        return false;
    },
    isObject: function (fn) {
        if (toString.call(fn) === "[object Object]") {
            return true;
        }
        return false;
    },
    isIp: function (ip) {
        // 211.222.11.*
        return /((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))|\*)/.test(ip);
    },

    /* --数据操作--------------------------*/
    //深拷贝（完美）
    cloneObjectPerfect: function (obj) {
        if (typeof obj === "object") {
            if (util.isArray(obj)) {
                var newArr = [];
                for (var i = 0; i < obj.length; i++) newArr.push(obj[i]);
                return newArr;
            } else {
                var newObj = {};
                for (var key in obj) {
                    newObj[key] = this.cloneObject(obj[key]);
                }
                return newObj;
            }
        } else {
            return obj;
        }
    },
    //深拷贝（缺陷）
    cloneObjectFuck: function (old) {
        var latest = JSON.parse(JSON.stringify(old));
        return latest;
    },
    //MD5
    toMD5: function (content) {
        return crypto.createHash('md5').update(content).digest('hex');
    },
    //Sha1
    toSha1: function (text) {
        return crypto.createHash("sha1").update(text, "utf8").digest('hex');
    },
    //小数加法
    decAdd: function (a, b, precision) {
        var x = Math.pow(10, precision || 3);
        return (Math.round(a * x) + Math.round(b * x)) / x;
    },
    //小数减法
    decSub: function (a, b, precision) {
        var x = Math.pow(10, precision || 3);
        return (Math.round(a * x) - Math.round(b * x)) / x;
    },
    //小数乘法
    decMul: function (a, b, precision) {
        var x = Math.pow(10, precision || 3);
        return (Math.round(a * x) * Math.round(b * x)) / (x * x);
    },
    //小数除法
    decDiv: function (a, b, precision) {
        var x = Math.pow(10, precision || 3);
        return Math.round((Math.round(a * x) / Math.round(b * x)) * x) / x;
    },
    //随机数生成
    random: function (type, len) {    //type 类型有 string num mixture smMixture bgMixture easyMixture
        len = len || 32;
        var $chars;
        switch (type) {
            case 'string':
                $chars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
                break;
            case 'num':
                $chars = '0123456789';
                break;
            case 'mixture':
                $chars = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
                break;
            case 'smMixture':
                $chars = '0123456789qwertyuiopasdfghjklzxcvbnm';
                break;
            case 'bgMixture':
                $chars = '0123456789QWERTYUIOPASDFGHJKLZXCVBNM';
                break;
            /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            case 'easyMixture':
                $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                break;
            /****默认mixture****/
            default :
                $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                break;
        }

        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }
};
<|endoftext|>


<commit_before>/*!
* Modal for the Styleguide Layer
* For both annotations and code/info
*
* Copyright (c) 2016 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*
* @requires panels-util.js
* @requires url-handler.js
*
*/

var modalStyleguide = {

  // set up some defaults
  active:       [ ],
  targetOrigin: (window.location.protocol === 'file:') ? '*' : window.location.protocol+'//'+window.location.host,

  /**
  * initialize the modal window
  */
  onReady: function() {

    // go through the panel toggles and add click event
    var els = document.querySelectorAll('.sg-pattern-extra-toggle');
    for (var i = 0; i < els.length; ++i) {
      els[i].onclick = (function(e) {
          e.preventDefault();
          var patternPartial = this.getAttribute('data-patternpartial');
          modalStyleguide.toggle(patternPartial);
      });
    }

  },

  /**
  * toggle the modal window open and closed based on clicking the pip
  * @param  {String}       the patternPartial that identifies what needs to be toggled
  */
  toggle: function(patternPartial) {
    if ((modalStyleguide.active[patternPartial] === undefined) || !modalStyleguide.active[patternPartial]) {
      var el = document.getElementById('sg-pattern-data-'+patternPartial);
      modalStyleguide.collectAndSend(el, true, false);
    } else {
      modalStyleguide.close(patternPartial);
    }

  },

  /**
  * open the modal window for a view-all entry
  * @param  {String}       the patternPartial that identifies what needs to be opened
  * @param  {String}       the content that should be inserted
  */
  open: function(patternPartial, content) {

    // make sure templateRendered is modified to be an HTML element
    var div       = document.createElement('div');
    div.innerHTML = content;
    content       = document.createElement('div').appendChild(div).querySelector('div');

    // add click events
    content = panelsUtil.addClickEvents(content, patternPartial);

    // make sure the modal viewer and other options are off just in case
    modalStyleguide.close(patternPartial);

    // note it's turned on in the viewer
    modalStyleguide.active[patternPartial] = true;

    // make sure there's no content
    div = document.getElementById('sg-pattern-extra-'+patternPartial);
    if (div.childNodes.length > 0) {
      div.removeChild(div.childNodes[0]);
    }

    // add the content
    document.getElementById('sg-pattern-extra-'+patternPartial).appendChild(content);

    // show the modal
    document.getElementById('sg-pattern-extra-toggle-'+patternPartial).classList.add('active');
    document.getElementById('sg-pattern-extra-'+patternPartial).classList.add('active');

  },

  /**
  * close the modal window for a view-all entry
  * @param  {String}       the patternPartial that identifies what needs to be closed
  */
  close: function(patternPartial) {

    // not that the modal viewer is no longer active
    modalStyleguide.active[patternPartial] = false;

    // hide the modal, look at info-panel.js
    document.getElementById('sg-pattern-extra-toggle-'+patternPartial).classList.remove('active');
    document.getElementById('sg-pattern-extra-'+patternPartial).classList.remove('active');

  },

  /**
  * get the data that needs to be send to the viewer for rendering
  * @param  {Element}      the identifier for the element that needs to be collected
  * @param  {Boolean}      if the refresh is of a view-all view and the content should be sent back
  * @param  {Boolean}      if the text in the dropdown should be switched
  */
  collectAndSend: function(el, iframePassback, switchText) {
    var patternData = JSON.parse(el.innerHTML);
    patternMarkupEl = document.querySelector('#'+patternData.patternPartial+' > .sg-pattern-example');
    patternData.patternMarkup = (patternMarkupEl !== null) ? patternMarkupEl.innerHTML : document.querySelector('body').innerHTML;
    modalStyleguide.patternQueryInfo(patternData, iframePassback, switchText);
  },

  /**
  * return the pattern info to the top level
  * @param  {Object}       the content that will be sent to the viewer for rendering
  * @param  {Boolean}      if the refresh is of a view-all view and the content should be sent back
  * @param  {Boolean}      if the text in the dropdown should be switched
  */
  patternQueryInfo: function(patternData, iframePassback, switchText) {

    // send a message to the pattern
    try {
      var obj = JSON.stringify({ 'event': 'patternLab.patternQueryInfo', 'patternData': patternData, 'iframePassback': iframePassback, 'switchText': switchText});
      parent.postMessage(obj, modalStyleguide.targetOrigin);
    } catch(e) {}

  },

  /**
  * toggle the comment pop-up based on a user clicking on the pattern
  * based on the great MDN docs at https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
  * @param  {Object}      event info
  */
  receiveIframeMessage: function(event) {

    var i;

    // does the origin sending the message match the current host? if not dev/null the request
    if ((window.location.protocol !== 'file:') && (event.origin !== window.location.protocol+'//'+window.location.host)) {
      return;
    }

    var data = {};
    try {
      data = (typeof event.data !== 'string') ? event.data : JSON.parse(event.data);
    } catch(e) {}

    // see if it got a path to replace
    if ((data.event !== undefined) && (data.event == 'patternLab.patternQuery')) {

      var els, iframePassback, patternData, patternMarkupEl;

      // find all elements related to pattern info
      els = document.querySelectorAll('.sg-pattern-data');
      iframePassback = (els.length > 1);

      // send each up to the parent to be read and compiled into panels
      for (i = 0; i < els.length; i++) {
        modalStyleguide.collectAndSend(els[i], iframePassback, data.switchText);
      }

    } else if ((data.event !== undefined) && (data.event == 'patternLab.patternModalInsert')) {

      // insert the previously rendered content being passed from the iframe
      modalStyleguide.open(data.patternPartial, data.modalContent);

    } else if ((data.event !== undefined) && (data.event == 'patternLab.annotationsHighlightShow')) {

      var elsToHighlight, j, item, span;

      // go over the supplied annotations
      for (i = 0; i < data.annotations.length; i++) {

        item = data.annotations[i];
        elsToHighlight = document.querySelectorAll(item.el);

        if (elsToHighlight.length > 0) {

          for (j = 0; j < elsToHighlight.length; j++) {

            elsToHighlight[j].classList.add('has-annotation');

            span = document.createElement('span');
            span.innerHTML = item.displayNumber;
            span.classList.add('annotation-tip');

            if (window.getComputedStyle(elsToHighlight[j],null).getPropertyValue('max-height') == '0px') {
              span.style.display = 'none';
            }

            annotationTip = document.querySelector(item.el+' > span.annotation-tip');
            if (annotationTip === null) {
              elsToHighlight[j].insertBefore(span,elsToHighlight[j].firstChild);
            } else {
              annotationTip.style.display = 'inline';
            }

            elsToHighlight[j].onclick = (function(item) {
              return function(e) {
                e.preventDefault();
                e.stopPropagation();
                var obj = JSON.stringify({'event': 'patternLab.annotationNumberClicked', 'displayNumber': item.displayNumber });
                parent.postMessage(obj, modalStyleguide.targetOrigin);
              };
            })(item);

          }

        }

      }

    } else if ((data.event !== undefined) && (data.event == 'patternLab.annotationsHighlightHide')) {

      elsToHide = document.querySelectorAll('.has-annotation');
      for (i = 0; i < elsToHide.length; i++) {
        elsToHide[i].classList.remove('has-annotation');
      }
      elsToHide = document.querySelectorAll('.annotation-tip');
      for (i = 0; i < elsToHide.length; i++) {
        elsToHide[i].style.display = 'none';
      }

    } else if ((data.event !== undefined) && (data.event == 'patternLab.patternModalClose')) {

      var keys = [];
      for (var k in modalStyleguide.active) {
        keys.push(k);
      }
      for (i = 0; i < keys.length; i++) {
        var patternPartial = keys[i];
        if (modalStyleguide.active[patternPartial]) {
          modalStyleguide.close(patternPartial);
        }
      }

    }

  }

};

// when the document is ready make sure the modal is ready
modalStyleguide.onReady();
window.addEventListener('message', modalStyleguide.receiveIframeMessage, false);
<commit_msg>killing a bug on the view-all view<commit_after>/*!
* Modal for the Styleguide Layer
* For both annotations and code/info
*
* Copyright (c) 2016 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*
* @requires panels-util.js
* @requires url-handler.js
*
*/

var modalStyleguide = {

  // set up some defaults
  active:       [ ],
  targetOrigin: (window.location.protocol === 'file:') ? '*' : window.location.protocol+'//'+window.location.host,

  /**
  * initialize the modal window
  */
  onReady: function() {

    // go through the panel toggles and add click event
    var els = document.querySelectorAll('.sg-pattern-extra-toggle');
    for (var i = 0; i < els.length; ++i) {
      els[i].onclick = (function(e) {
          e.preventDefault();
          var patternPartial = this.getAttribute('data-patternpartial');
          modalStyleguide.toggle(patternPartial);
      });
    }

  },

  /**
  * toggle the modal window open and closed based on clicking the pip
  * @param  {String}       the patternPartial that identifies what needs to be toggled
  */
  toggle: function(patternPartial) {
    if ((modalStyleguide.active[patternPartial] === undefined) || !modalStyleguide.active[patternPartial]) {
      var el = document.getElementById('sg-pattern-data-'+patternPartial);
      modalStyleguide.collectAndSend(el, true, false);
    } else {
      modalStyleguide.close(patternPartial);
    }

  },

  /**
  * open the modal window for a view-all entry
  * @param  {String}       the patternPartial that identifies what needs to be opened
  * @param  {String}       the content that should be inserted
  */
  open: function(patternPartial, content) {

    // make sure templateRendered is modified to be an HTML element
    var div       = document.createElement('div');
    div.innerHTML = content;
    content       = document.createElement('div').appendChild(div).querySelector('div');

    // add click events
    content = panelsUtil.addClickEvents(content, patternPartial);

    // make sure the modal viewer and other options are off just in case
    modalStyleguide.close(patternPartial);

    // note it's turned on in the viewer
    modalStyleguide.active[patternPartial] = true;

    // make sure there's no content
    div = document.getElementById('sg-pattern-extra-'+patternPartial);
    if (div.childNodes.length > 0) {
      div.removeChild(div.childNodes[0]);
    }

    // add the content
    document.getElementById('sg-pattern-extra-'+patternPartial).appendChild(content);

    // show the modal
    document.getElementById('sg-pattern-extra-toggle-'+patternPartial).classList.add('active');
    document.getElementById('sg-pattern-extra-'+patternPartial).classList.add('active');

  },

  /**
  * close the modal window for a view-all entry
  * @param  {String}       the patternPartial that identifies what needs to be closed
  */
  close: function(patternPartial) {

    // not that the modal viewer is no longer active
    modalStyleguide.active[patternPartial] = false;

    // hide the modal, look at info-panel.js
    document.getElementById('sg-pattern-extra-toggle-'+patternPartial).classList.remove('active');
    document.getElementById('sg-pattern-extra-'+patternPartial).classList.remove('active');

  },

  /**
  * get the data that needs to be send to the viewer for rendering
  * @param  {Element}      the identifier for the element that needs to be collected
  * @param  {Boolean}      if the refresh is of a view-all view and the content should be sent back
  * @param  {Boolean}      if the text in the dropdown should be switched
  */
  collectAndSend: function(el, iframePassback, switchText) {
    var patternData = JSON.parse(el.innerHTML);
    if (patternData.patternName !== undefined) {
      patternMarkupEl = document.querySelector('#'+patternData.patternPartial+' > .sg-pattern-example');
      patternData.patternMarkup = (patternMarkupEl !== null) ? patternMarkupEl.innerHTML : document.querySelector('body').innerHTML;
      modalStyleguide.patternQueryInfo(patternData, iframePassback, switchText);
    }
  },

  /**
  * return the pattern info to the top level
  * @param  {Object}       the content that will be sent to the viewer for rendering
  * @param  {Boolean}      if the refresh is of a view-all view and the content should be sent back
  * @param  {Boolean}      if the text in the dropdown should be switched
  */
  patternQueryInfo: function(patternData, iframePassback, switchText) {

    // send a message to the pattern
    try {
      var obj = JSON.stringify({ 'event': 'patternLab.patternQueryInfo', 'patternData': patternData, 'iframePassback': iframePassback, 'switchText': switchText});
      parent.postMessage(obj, modalStyleguide.targetOrigin);
    } catch(e) {}

  },

  /**
  * toggle the comment pop-up based on a user clicking on the pattern
  * based on the great MDN docs at https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
  * @param  {Object}      event info
  */
  receiveIframeMessage: function(event) {

    var i;

    // does the origin sending the message match the current host? if not dev/null the request
    if ((window.location.protocol !== 'file:') && (event.origin !== window.location.protocol+'//'+window.location.host)) {
      return;
    }

    var data = {};
    try {
      data = (typeof event.data !== 'string') ? event.data : JSON.parse(event.data);
    } catch(e) {}

    // see if it got a path to replace
    if ((data.event !== undefined) && (data.event == 'patternLab.patternQuery')) {

      var els, iframePassback, patternData, patternMarkupEl;

      // find all elements related to pattern info
      els = document.querySelectorAll('.sg-pattern-data');
      iframePassback = (els.length > 1);

      // send each up to the parent to be read and compiled into panels
      for (i = 0; i < els.length; i++) {
        modalStyleguide.collectAndSend(els[i], iframePassback, data.switchText);
      }

    } else if ((data.event !== undefined) && (data.event == 'patternLab.patternModalInsert')) {

      // insert the previously rendered content being passed from the iframe
      modalStyleguide.open(data.patternPartial, data.modalContent);

    } else if ((data.event !== undefined) && (data.event == 'patternLab.annotationsHighlightShow')) {

      var elsToHighlight, j, item, span;

      // go over the supplied annotations
      for (i = 0; i < data.annotations.length; i++) {

        item = data.annotations[i];
        elsToHighlight = document.querySelectorAll(item.el);

        if (elsToHighlight.length > 0) {

          for (j = 0; j < elsToHighlight.length; j++) {

            elsToHighlight[j].classList.add('has-annotation');

            span = document.createElement('span');
            span.innerHTML = item.displayNumber;
            span.classList.add('annotation-tip');

            if (window.getComputedStyle(elsToHighlight[j],null).getPropertyValue('max-height') == '0px') {
              span.style.display = 'none';
            }

            annotationTip = document.querySelector(item.el+' > span.annotation-tip');
            if (annotationTip === null) {
              elsToHighlight[j].insertBefore(span,elsToHighlight[j].firstChild);
            } else {
              annotationTip.style.display = 'inline';
            }

            elsToHighlight[j].onclick = (function(item) {
              return function(e) {
                e.preventDefault();
                e.stopPropagation();
                var obj = JSON.stringify({'event': 'patternLab.annotationNumberClicked', 'displayNumber': item.displayNumber });
                parent.postMessage(obj, modalStyleguide.targetOrigin);
              };
            })(item);

          }

        }

      }

    } else if ((data.event !== undefined) && (data.event == 'patternLab.annotationsHighlightHide')) {

      elsToHide = document.querySelectorAll('.has-annotation');
      for (i = 0; i < elsToHide.length; i++) {
        elsToHide[i].classList.remove('has-annotation');
      }
      elsToHide = document.querySelectorAll('.annotation-tip');
      for (i = 0; i < elsToHide.length; i++) {
        elsToHide[i].style.display = 'none';
      }

    } else if ((data.event !== undefined) && (data.event == 'patternLab.patternModalClose')) {

      var keys = [];
      for (var k in modalStyleguide.active) {
        keys.push(k);
      }
      for (i = 0; i < keys.length; i++) {
        var patternPartial = keys[i];
        if (modalStyleguide.active[patternPartial]) {
          modalStyleguide.close(patternPartial);
        }
      }

    }

  }

};

// when the document is ready make sure the modal is ready
modalStyleguide.onReady();
window.addEventListener('message', modalStyleguide.receiveIframeMessage, false);
<|endoftext|>