text:
var INTERNAL_PROPS = hammerhead.PROCESSING_INSTRUCTIONS.dom.internal_props;

var domUtils      = hammerhead.utils.dom;
var browserUtils  = hammerhead.utils.browser;
var nativeMethods = hammerhead.nativeMethods;
var Promise       = hammerhead.Promise;

module('isCrossDomainWindows', function () {
    test('self', function () {
        ok(!domUtils.isCrossDomainWindows(window, window));
    });

    test('iframe with empty src', function () {
        return createTestIframe({ src: '' })
            .then(function (iframe) {
                ok(!domUtils.isCrossDomainWindows(window, iframe.contentWindow));
            });
    });

    test('iframe with about blank src', function () {
        return createTestIframe({ src: 'about:blank' })
            .then(function (iframe) {
                ok(!domUtils.isCrossDomainWindows(window, iframe.contentWindow));
            });
    });

    test('iframe with cross domain src', function () {
        return createTestIframe({ src: getCrossDomainPageUrl('../../data/cross-domain/get-message.html') })
            .then(function (iframe) {
                ok(domUtils.isCrossDomainWindows(window, iframe.contentWindow));
            });
    });
});

test('isDomElement', function () {
    ok(!domUtils.isDomElement(document));
    ok(domUtils.isDomElement(document.documentElement));
    ok(domUtils.isDomElement(document.body));
    ok(domUtils.isDomElement(document.createElement('span')));
    ok(domUtils.isDomElement(document.createElement('strong')));
    ok(domUtils.isDomElement(document.createElement('a')));
    ok(!domUtils.isDomElement(null));
    ok(!domUtils.isDomElement(document.createTextNode('text')));
    ok(!domUtils.isDomElement(document.createDocumentFragment()));

    //T184805
    var p = Element.prototype;

    do
        ok(!domUtils.isDomElement(p));
    // eslint-disable-next-line no-extra-parens
    while ((p = Object.getPrototypeOf(p)));

    if (window.Proxy)
        ok(!domUtils.isDomElement(new Proxy({}, {})));
});

test('isDomElement for iframe elements', function () {
    return createTestIframe({ src: '' })
        .then(function (iframe) {
            var iframeDocument = iframe.contentDocument;

            ok(!domUtils.isDomElement(iframeDocument));
            ok(domUtils.isDomElement(iframeDocument.documentElement));
            ok(domUtils.isDomElement(iframeDocument.body));
            ok(domUtils.isDomElement(iframeDocument.createElement('span')));
            ok(domUtils.isDomElement(iframeDocument.createElement('strong')));
            ok(domUtils.isDomElement(iframeDocument.createElement('a')));
            ok(!domUtils.isDomElement(iframeDocument.createTextNode('text')));
            ok(!domUtils.isDomElement(iframeDocument.createDocumentFragment()));

            var p = iframe.contentWindow.Element.prototype;

            do
                ok(!domUtils.isDomElement(p));
            // eslint-disable-next-line no-extra-parens
            while ((p = Object.getPrototypeOf(p)));

            if (window.Proxy)
                ok(!domUtils.isDomElement(new Proxy({}, {})));
        });
});

test('isDocumentFragmentNode (GH-1344)', function () {
    ok(domUtils.isDocumentFragmentNode(document.createDocumentFragment()));
    ok(!domUtils.isDocumentFragmentNode(document.createElement('span')));
    ok(!domUtils.isDocumentFragmentNode(document.createElement('strong')));
    ok(!domUtils.isDocumentFragmentNode(document.createElement('a')));
    ok(!domUtils.isDocumentFragmentNode(null));
    ok(!domUtils.isDocumentFragmentNode(document.createTextNode('text')));

    if (window.Proxy)
        ok(!domUtils.isDocumentFragmentNode(new Proxy({}, {})));
});

test('isTextNode (GH-1344)', function () {
    ok(domUtils.isTextNode(document.createTextNode('text')));
    ok(!domUtils.isTextNode(document.createDocumentFragment()));
    ok(!domUtils.isTextNode(document.createElement('span')));
    ok(!domUtils.isTextNode(document.createElement('strong')));
    ok(!domUtils.isTextNode(document.createElement('a')));
    ok(!domUtils.isTextNode(null));

    if (window.Proxy)
        ok(!domUtils.isTextNode(new Proxy({}, {})));
});

test('isProcessingInstructionNode (GH-1344)', function () {
    var doc         = new DOMParser().parseFromString('<xml></xml>', 'application/xml');
    var instruction = doc.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"');

    ok(domUtils.isProcessingInstructionNode(instruction));
    ok(!domUtils.isProcessingInstructionNode(document.createDocumentFragment()));
    ok(!domUtils.isProcessingInstructionNode(document.createElement('span')));
    ok(!domUtils.isProcessingInstructionNode(document.createElement('strong')));
    ok(!domUtils.isProcessingInstructionNode(document.createElement('a')));
    ok(!domUtils.isProcessingInstructionNode(null));
    ok(!domUtils.isProcessingInstructionNode(document.createTextNode('text')));

    if (window.Proxy)
        ok(!domUtils.isProcessingInstructionNode(new Proxy({}, {})));
});

test('isCommentNode (GH-1344)', function () {
    ok(domUtils.isCommentNode(document.createComment('comment')));
    ok(!domUtils.isCommentNode(document.createDocumentFragment()));
    ok(!domUtils.isCommentNode(document.createElement('span')));
    ok(!domUtils.isCommentNode(document.createElement('strong')));
    ok(!domUtils.isCommentNode(document.createElement('a')));
    ok(!domUtils.isCommentNode(null));
    ok(!domUtils.isCommentNode(document.createTextNode('text')));

    if (window.Proxy)
        ok(!domUtils.isCommentNode(new Proxy({}, {})));
});

test('isDocument (GH-1344)', function () {
    ok(domUtils.isDocument(document));
    ok(domUtils.isDocument(document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null)));
    ok(domUtils.isDocument(document.implementation.createHTMLDocument('title')));
    ok(!domUtils.isDocument(document.createElement('span')));
    ok(!domUtils.isDocument(document.createElement('strong')));
    ok(!domUtils.isDocument(document.createElement('a')));
    ok(!domUtils.isDocument(null));
    ok(!domUtils.isDocument(document.createTextNode('text')));
    ok(!domUtils.isDocument(document.createDocumentFragment()));

    if (window.Proxy)
        ok(!domUtils.isDocument(new Proxy({}, {})));
});

test('isWebSocket', function () {
    var webSocket = new WebSocket('ws://127.0.0.1:2000/');

    ok(domUtils.isWebSocket(webSocket));
    ok(!domUtils.isWebSocket(document));
    ok(!domUtils.isWebSocket({}));
    ok(!domUtils.isWebSocket({ url: 'ws://127.0.0.1:2000/' }));
    ok(!domUtils.isWebSocket(null));

    webSocket.close();
});

test('isMessageEvent', function () {
    return createTestIframe()
        .then(function (iframe) {
            var iframeWindow = iframe.contentWindow;

            iframeWindow['%hammerhead%'].sandbox.event.message.postMessage(window, ['message', '*']);

            return new Promise(function (resolve) {
                window.addEventListener('message', resolve);
            });
        })
        .then(function (eventObj) {
            ok(domUtils.isMessageEvent(eventObj));
            ok(!domUtils.isMessageEvent(document));
            ok(!domUtils.isMessageEvent({}));
            ok(!domUtils.isMessageEvent({ target: window }));
            ok(!domUtils.isMessageEvent(null));
        });
});

if (window.PerformanceNavigationTiming) {
    test('isPerformanceNavigationTiming', function () {
        ok(domUtils.isPerformanceNavigationTiming(window.performance.getEntriesByType('navigation')[0]));
        ok(!domUtils.isPerformanceNavigationTiming(window.performance.getEntriesByType('resource')[0]));
        ok(!domUtils.isPerformanceNavigationTiming(window.performance.getEntriesByType('paint')[0]));
    });
}

test('isArrayBuffer', function () {
    ok(domUtils.isArrayBuffer(new ArrayBuffer(0)), 'ArrayBuffer');
    ok(!domUtils.isArrayBuffer(void 0), 'undefined');
});

test('isArrayBufferView', function () {
    ok(domUtils.isArrayBufferView(new Uint8Array(0)), 'Uint8Array');
    ok(!domUtils.isArrayBufferView(void 0), 'undefined');
});

test('isDataView', function () {
    ok(domUtils.isDataView(new DataView(new ArrayBuffer(0))), 'DataView');
    ok(!domUtils.isDataView(void 0), 'undefined');
});

test('getTopSameDomainWindow', function () {
    return createTestIframe()
        .then(function (iframe) {
            strictEqual(domUtils.getTopSameDomainWindow(window.top), window.top);
            strictEqual(domUtils.getTopSameDomainWindow(iframe.contentWindow), window.top);
        });
});

test('isWindow', function () {
    ok(domUtils.isWindow(window));
    ok(!domUtils.isWindow({ top: '' }));

    var storedToString = window.toString;

    window.toString = function () {
        throw 'eid library overrides window.toString() method';
    };

    ok(domUtils.isWindow(window));
    ok(!domUtils.isWindow([
        {
            toString: function () {
                ok(false);
            }
        }
    ]));

    window.toString = storedToString;

    ok(!domUtils.isWindow(Object.create(Window.prototype)));
});

test('isWindow for a cross-domain window', function () {
    return createTestIframe({ src: getCrossDomainPageUrl('../../data/cross-domain/simple-page.html') })
        .then(function (iframe) {
            var iframeWindow = iframe.contentWindow;

            ok(domUtils.isWindow(iframeWindow));

            // NOTE: The firefox does not provide access to the cross-domain location.
            if (!browserUtils.isFirefox)
                ok(!domUtils.isWindow(iframeWindow.location));
        });
});

test('isWindow for a window received from the MessageEvent.target property (GH-1445)', function () {
    return createTestIframe()
        .then(function (iframe) {
            var iframeWindow = iframe.contentWindow;

            iframeWindow['%hammerhead%'].sandbox.event.message.postMessage(window, ['message', '*']);

            return new Promise(function (resolve) {
                window.addEventListener('message', resolve);
            });
        })
        .then(function (eventObj) {
            ok(domUtils.isWindow(eventObj.target));
        });
});

test('closest', function () {
    var div = document.createElement('div');

    div.className = 'parent';
    div           = document.body.appendChild(div);

    var innerDiv = document.createElement('div');

    innerDiv.className = 'child';
    div.appendChild(innerDiv);

    ok(!domUtils.closest(null, '.test'));
    strictEqual(domUtils.closest(innerDiv, '.parent'), div);
    strictEqual(domUtils.closest(div, 'html'), document.documentElement);

    var iframe = document.createElement('iframe');

    iframe.id = 'test5';
    iframe    = document.body.appendChild(iframe);

    var iframeDiv = iframe.contentDocument.createElement('div');

    iframeDiv.className = 'parent';
    iframeDiv           = iframe.contentDocument.body.appendChild(iframeDiv);

    var innerIframeDiv = iframe.contentDocument.createElement('div');

    innerIframeDiv.className = 'child';
    iframeDiv.appendChild(innerIframeDiv);

    strictEqual(domUtils.closest(innerIframeDiv, '.parent'), iframeDiv);
    strictEqual(domUtils.closest(iframeDiv, 'body'), iframe.contentDocument.body);

    iframe.parentNode.removeChild(iframe);
    div.parentNode.removeChild(div);
});

test('match', function () {
    var div = document.createElement('div');

    document.body.appendChild(div);

    ok(domUtils.matches(div, 'div'));

    div.parentNode.removeChild(div);
});

test('isSVGElement', function () {
    ok(!domUtils.isSVGElement(null));
    ok(!domUtils.isSVGElement(document));
    ok(!domUtils.isSVGElement(document.documentElement));
    ok(domUtils.isSVGElement(document.createElementNS('http://www.w3.org/2000/svg', 'svg')));
    ok(domUtils.isSVGElement(document.createElementNS('http://www.w3.org/2000/svg', 'use')));
    ok(!domUtils.isSVGElement(document.createElement('div')));
});

test('isSVGElement for iframe elements', function () {
    return createTestIframe()
        .then(function (iframe) {
            var iframeDocument = iframe.contentDocument;

            ok(!domUtils.isSVGElement(null));
            ok(!domUtils.isSVGElement(iframeDocument));
            ok(!domUtils.isSVGElement(iframeDocument.documentElement));
            ok(domUtils.isSVGElement(iframeDocument.createElementNS('http://www.w3.org/2000/svg', 'svg')));
            ok(domUtils.isSVGElement(iframeDocument.createElementNS('http://www.w3.org/2000/svg', 'use')));
            ok(!domUtils.isSVGElement(iframeDocument.createElement('div')));
        });
});

if (window.fetch) {
    test('isFetchHeaders', function () {
        ok(!domUtils.isFetchHeaders(null));
        ok(!domUtils.isFetchHeaders(document));
        ok(!domUtils.isFetchHeaders(document.documentElement));
        ok(!domUtils.isFetchHeaders(window.Headers));
        ok(domUtils.isFetchHeaders(new window.Headers()));
    });

    test('isFetchHeaders in iframe', function () {
        return createTestIframe()
            .then(function (iframe) {
                var iframeDocument = iframe.contentDocument;
                var iframeWindow   = iframe.contentWindow;

                ok(!domUtils.isFetchHeaders(null));
                ok(!domUtils.isFetchHeaders(iframeDocument));
                ok(!domUtils.isFetchHeaders(iframeDocument.documentElement));
                ok(!domUtils.isFetchHeaders(iframeWindow.Headers));
                ok(domUtils.isFetchHeaders(new iframeWindow.Headers()));
            });
    });

    test('isFetchRequest', function () {
        ok(!domUtils.isFetchRequest(null));
        ok(!domUtils.isFetchRequest(document));
        ok(!domUtils.isFetchRequest(document.documentElement));
        ok(!domUtils.isFetchRequest(window.Request));
        ok(domUtils.isFetchRequest(new window.Request('http://domain.com')));
    });

    test('isFetchRequest in iframe', function () {
        return createTestIframe()
            .then(function (iframe) {
                var iframeDocument = iframe.contentDocument;
                var iframeWindow   = iframe.contentWindow;

                ok(!domUtils.isFetchRequest(null));
                ok(!domUtils.isFetchRequest(iframeDocument));
                ok(!domUtils.isFetchRequest(iframeDocument.documentElement));
                ok(!domUtils.isFetchRequest(iframeWindow.Request));
                ok(domUtils.isFetchRequest(new iframeWindow.Request('http://domain.com')));
            });
    });

    test('window.Request should work with the operator "instanceof" (GH-690)', function () {
        var request = new Request();

        ok(request instanceof window.Request);
    });
}

test('isHammerheadAttr', function () {
    ok(!domUtils.isHammerheadAttr('href'));
    ok(!domUtils.isHammerheadAttr('class'));
    ok(domUtils.isHammerheadAttr('data-hammerhead-focused'));
    ok(domUtils.isHammerheadAttr('data-hammerhead-hovered'));
    ok(domUtils.isHammerheadAttr('src-hammerhead-stored-value'));
});

test('isContentEditableElement', function () {
    notOk(domUtils.isContentEditableElement(null));

    document.designMode = 'on';
    ok(domUtils.isContentEditableElement(document));
    ok(domUtils.isContentEditableElement(document.body));
    document.designMode = 'off';

    // isRenderedNode
    var doc         = new DOMParser().parseFromString('<xml></xml>', 'application/xml');
    var instruction = doc.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"');

    notOk(domUtils.isContentEditableElement(instruction));

    notOk(domUtils.isContentEditableElement(document.createElement('script')));
    notOk(domUtils.isContentEditableElement(document.createElement('style')));
    notOk(domUtils.isContentEditableElement(document.createComment('comment text')));

    // isAlwaysNotEditableElement
    notOk(domUtils.isContentEditableElement(document.createElement('select')));
    notOk(domUtils.isContentEditableElement(document.createElement('option')));

    // NOTE: Disable due to IEWebDriver problem (Saucelabs)
    //notOk(domUtils.isContentEditableElement(document.createElement('applet')));
    notOk(domUtils.isContentEditableElement(document.createElement('area')));
    notOk(domUtils.isContentEditableElement(document.createElement('audio')));
    notOk(domUtils.isContentEditableElement(document.createElement('canvas')));
    notOk(domUtils.isContentEditableElement(document.createElement('datalist')));
    notOk(domUtils.isContentEditableElement(document.createElement('keygen')));
    notOk(domUtils.isContentEditableElement(document.createElement('map')));
    notOk(domUtils.isContentEditableElement(document.createElement('meter')));
    notOk(domUtils.isContentEditableElement(document.createElement('object')));
    notOk(domUtils.isContentEditableElement(document.createElement('progress')));
    notOk(domUtils.isContentEditableElement(document.createElement('source')));
    notOk(domUtils.isContentEditableElement(document.createElement('track')));
    notOk(domUtils.isContentEditableElement(document.createElement('video')));
    notOk(domUtils.isContentEditableElement(document.createElement('img')));
    notOk(domUtils.isContentEditableElement(document.createElement('input')));
    notOk(domUtils.isContentEditableElement(document.createElement('textarea')));
    notOk(domUtils.isContentEditableElement(document.createElement('button')));

    var parentElement = document.createElement('div');
    var element       = document.createElement('p');
    var textNode      = document.createTextNode('text');

    parentElement.appendChild(element);
    element.appendChild(textNode);
    notOk(domUtils.isContentEditableElement(parentElement));
    notOk(domUtils.isContentEditableElement(element));
    notOk(domUtils.isContentEditableElement(textNode));

    //TODO: GH - 1369
    if (!browserUtils.isAndroid) {
        parentElement.setAttribute('contenteditable', '');
        ok(domUtils.isContentEditableElement(parentElement));
        ok(domUtils.isContentEditableElement(element));
        ok(domUtils.isContentEditableElement(textNode));
    }

    // GH-1366
    var elementMock = {
        isContentEditable: true,
        tagName:           'rich-text-area',
        getAttribute:      function () {
            return 'null';
        }
    };

    ok(domUtils.isContentEditableElement(elementMock));
});

test('isElementInDocument', function () {
    var shadowParent = document.createElement('div');

    ok(domUtils.isElementInDocument(document.body));
    notOk(domUtils.isElementInDocument(shadowParent));

    if (!nativeMethods.attachShadow)
        return;

    var shadow = shadowParent.attachShadow({ mode: 'open' });
    var div    = document.createElement('div');

    notOk(domUtils.isElementInDocument(div));

    shadow.appendChild(div);

    notOk(domUtils.isElementInDocument(div));

    document.body.appendChild(shadowParent);

    ok(domUtils.isElementInDocument(shadowParent));
    ok(domUtils.isElementInDocument(div));

    var nestedShadowDiv = document.createElement('div');
    var nestedShadow    = div.attachShadow({ mode: 'closed' });

    nestedShadow.appendChild(nestedShadowDiv);

    ok(domUtils.isElementInDocument(nestedShadowDiv));

    document.body.removeChild(shadowParent);
});

module('isIframeWithoutSrc');

test('should not process an iframe with a same url twice (GH-1419)', function () {
    var nestedIframe = null;

    return createTestIframe({ src: getSameDomainPageUrl('../../data/same-domain/form-target-to-iframe.html') })
        .then(function (iframe) {
            var iframeDocument = iframe.contentDocument;
            var formSubmit     = iframeDocument.querySelector('form > input[type=submit]');

            nestedIframe = iframeDocument.querySelector('iframe');

            ok(domUtils.isIframeWithoutSrc(nestedIframe));

            return new Promise(function (resolve) {
                nestedIframe.addEventListener('load', resolve);
                formSubmit.click();
            });
        })
        .then(function () {
            var nestedIframeHammerhead             = nestedIframe.contentWindow['%hammerhead%'];
            var nestedIframeNativeAddEventListener = nestedIframeHammerhead.nativeMethods.windowAddEventListener || nestedIframeHammerhead.nativeMethods.addEventListener;
            var stringifiedAddEventListener        = nestedIframeNativeAddEventListener.toString();

            ok(/\s*function\s+[^\s(]*\s*\([^)]*\)\s*{\s*\[native code]\s*}\s*/.test(stringifiedAddEventListener));
            ok(!domUtils.isIframeWithoutSrc(nestedIframe));
        });
});

test('after the location is set to an iframe without src isIframeWithoutSrc should return "false"', function () {
    return createTestIframe()
        .then(function (iframe) {
            var src = getSameDomainPageUrl('../../data/same-domain/service-message-from-removed-iframe.html');

            ok(domUtils.isIframeWithoutSrc(iframe));

            return new Promise(function (resolve) {
                iframe.addEventListener('load', function () {
                    resolve(iframe);
                });
                iframe.contentWindow.location = src;
            });
        })
        .then(function (iframe) {
            ok(!domUtils.isIframeWithoutSrc(iframe));
        });
});

// NOTE: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8187450/
if (!browserUtils.isIE) {
    test('should return "false" after calling document.open, document.write, document.close for the same-domain iframe (GH-703) (GH-704)', function () {
        return createTestIframe({ src: getSameDomainPageUrl('../../data/code-instrumentation/iframe.html') })
            .then(function (iframe) {
                ok(!domUtils.isIframeWithoutSrc(iframe));

                iframe.contentDocument.open();

                ok(domUtils.isIframeWithoutSrc(iframe));

                iframe.contentDocument.write('<h1>test</h1>');
                ok(domUtils.isIframeWithoutSrc(iframe));

                iframe.contentDocument.close();
                ok(domUtils.isIframeWithoutSrc(iframe));
            });
    });
}

test('should return "false" after calling document.open, document.write, document.close for the iframe with javascript src (GH-815)', function () {
    return createTestIframe({ src: 'javascript:false;' })
        .then(function (iframe) {
            ok(domUtils.isIframeWithoutSrc(iframe));

            iframe.contentDocument.open();

            ok(domUtils.isIframeWithoutSrc(iframe));

            iframe.contentDocument.write('<h1>test</h1>');
            ok(domUtils.isIframeWithoutSrc(iframe));

            iframe.contentDocument.close();
            ok(domUtils.isIframeWithoutSrc(iframe));
        });
});

test('changed location 2', function () {
    return createTestIframe({ src: 'about:blank' })
        .then(function (iframe) {
            return new Promise(function (resolve) {
                iframe.addEventListener('load', function () {
                    resolve(iframe);
                });
                iframe.contentWindow.location = 'http://' + location.host + '/';
            });
        })
        .then(function (iframe) {
            iframe[INTERNAL_PROPS.processedContext] = window;
            ok(!domUtils.isIframeWithoutSrc(iframe));
            ok(!domUtils.isCrossDomainIframe(iframe));
        });
});

test('crossdomain src', function () {
    return createTestIframe({ src: getCrossDomainPageUrl('../../data/cross-domain/simple-page.html') })
        .then(function (iframe) {
            iframe[INTERNAL_PROPS.processedContext] = window;
            ok(!domUtils.isIframeWithoutSrc(iframe));
            ok(domUtils.isCrossDomainIframe(iframe));
        });
});

test('samedomain src', function () {
    var iframe = document.createElement('iframe');

    iframe.id  = 'test' + Date.now();
    iframe.src = 'http://' + location.host + '/';

    ok(!domUtils.isIframeWithoutSrc(iframe));

    var promise = window.QUnitGlobals.waitForIframe(iframe)
        .then(function () {
            iframe[INTERNAL_PROPS.processedContext] = window;
            ok(!domUtils.isIframeWithoutSrc(iframe));
            ok(!domUtils.isCrossDomainIframe(iframe));
            iframe.parentNode.removeChild(iframe);
        });

    document.body.appendChild(iframe);

    ok(!domUtils.isIframeWithoutSrc(iframe));

    return promise;
});

test('without src attribute', function () {
    return createTestIframe()
        .then(function (iframe) {
            iframe[INTERNAL_PROPS.processedContext] = window;
            ok(domUtils.isIframeWithoutSrc(iframe));
            ok(!domUtils.isCrossDomainIframe(iframe));
        });
});

test('about:blank', function () {
    return createTestIframe({ src: 'about:blank' })
        .then(function (iframe) {
            iframe[INTERNAL_PROPS.processedContext] = window;
            ok(domUtils.isIframeWithoutSrc(iframe));
            ok(!domUtils.isCrossDomainIframe(iframe));
        });
});

module('isCrossDomainIframe');

test('location is changed to cross-domain', function () {
    return createTestIframe({ src: 'http://' + location.host + '/' })
        .then(function (iframe) {
            ok(!domUtils.isCrossDomainIframe(iframe));
            ok(!domUtils.isCrossDomainIframe(iframe, true));

            return new Promise(function (resolve) {
                iframe.addEventListener('load', function () {
                    resolve(iframe);
                });
                iframe.contentDocument.location.href = getCrossDomainPageUrl('../../data/cross-domain/simple-page.html');
            });
        })
        .then(function (iframe) {
            ok(domUtils.isCrossDomainIframe(iframe));
            ok(!domUtils.isCrossDomainIframe(iframe, true));
        });
});

test('empty src attribute', function () {
    return createTestIframe({ src: '' })
        .then(function (iframe) {
            iframe[INTERNAL_PROPS.processedContext] = window;
            ok(domUtils.isIframeWithoutSrc(iframe));
            ok(!domUtils.isCrossDomainIframe(iframe));
        });
});

module('class manipulation');

test('addClass', function () {
    var div = document.createElement('div');

    document.body.appendChild(div);

    domUtils.addClass(null, 'test');
    strictEqual(div.className, '');

    domUtils.addClass(div, 'test');
    strictEqual(div.className, 'test');

    div.className = 'test1';
    domUtils.addClass(div, 'test2 test3');
    strictEqual(div.className, 'test1 test2 test3');

    div.className = 'test1 test2';
    domUtils.addClass(div, 'test2 test3');
    strictEqual(div.className, 'test1 test2 test3');

    div.parentNode.removeChild(div);
});

test('removeClass', function () {
    var div = document.createElement('div');

    document.body.appendChild(div);

    domUtils.removeClass(null, 'test');
    domUtils.removeClass(div, 'test');
    strictEqual(div.className, '');

    div.className = 'test';
    domUtils.removeClass(div, 'test');
    strictEqual(div.className, '');

    div.className = 'test1 test2 test3';
    domUtils.removeClass(div, 'test1');
    strictEqual(div.className, 'test2 test3');

    div.className = 'test1 test2 test3';
    domUtils.removeClass(div, 'test2');
    strictEqual(div.className, 'test1 test3');

    div.className = 'test1 test2 test3';
    domUtils.removeClass(div, 'test3');
    strictEqual(div.className, 'test1 test2');

    div.className = 'test1 test2 test3';
    domUtils.removeClass(div, 'test1 test3');
    strictEqual(div.className, 'test2');

    div.parentNode.removeChild(div);
});

test('hasClass', function () {
    var div = document.createElement('div');

    document.body.appendChild(div);

    ok(!domUtils.hasClass(null, 'test'));

    div.className = 'test';
    ok(domUtils.hasClass(div, 'test'));

    div.className = 'test1 test2 test3';
    ok(domUtils.hasClass(div, 'test1'));
    ok(domUtils.hasClass(div, 'test2'));
    ok(domUtils.hasClass(div, 'test3'));

    div.parentNode.removeChild(div);
});

test('isElementFocusable', function () {
    var src = getSameDomainPageUrl('../../data/is-focusable/iframe.html', 'is-focusable/iframe.html');

    return createTestIframe({ src: src })
        .then(function (iframe) {
            iframe.style.width  = '500px';
            iframe.style.height = '500px';

            var iframeDocument          = iframe.contentDocument;
            var allElements             = iframeDocument.querySelectorAll('*');
            var expectedFocusedElements = Array.prototype.slice.call(iframeDocument.querySelectorAll('.expected'));
            var focusedElements         = [];

            if (browserUtils.isIE) {
                expectedFocusedElements = expectedFocusedElements.filter(function (el) {
                    if (browserUtils.version <= 10 && domUtils.isAnchorElement(el) && el.getAttribute('href') === '' &&
                        domUtils.getTabIndex(el) === null)
                        return false;

                    return !domUtils.isOptionElement(el);
                });
            }
            else {
                expectedFocusedElements = expectedFocusedElements.filter(function (el) {
                    return !domUtils.isTableDataCellElement(el);
                });
            }

            for (var i = 0; i < allElements.length; i++) {
                if (domUtils.isElementFocusable(allElements[i]))
                    focusedElements.push(allElements[i]);
            }

            deepEqual(expectedFocusedElements, focusedElements);
        });
});

test('isTextEditableInput', function () {
    var editableTypes = {
        'color':          false,
        'date':           false,
        'datetime-local': false,
        'email':          true,
        'month':          false,
        'number':         true,
        'password':       true,
        'range':          false,
        'search':         true,
        'tel':            true,
        'text':           true,
        'time':           false,
        'url':            true,
        'week':           false
    };

    var input = nativeMethods.createElement.call(document, 'input');

    // NOTE: check element with empty "type" attribute
    ok(domUtils.isTextEditableInput(input));

    for (var type in editableTypes) {
        if (editableTypes.hasOwnProperty(type)) {
            input.setAttribute('type', type);
            strictEqual(domUtils.isTextEditableInput(input), editableTypes[type]);
        }
    }
});

test('isInputWithoutSelectionProperties', function () {
    var input1 = nativeMethods.createElement.call(document, 'input');
    var input2 = nativeMethods.createElement.call(document, 'input');
    var input3 = nativeMethods.createElement.call(document, 'input');

    input1.type = 'email';
    input2.type = 'number';
    input3.type = 'text';

    if (browserUtils.isIE || browserUtils.isSafari) {
        notOk(domUtils.isInputWithoutSelectionProperties(input1));
        notOk(domUtils.isInputWithoutSelectionProperties(input2));
    }
    else {
        ok(domUtils.isInputWithoutSelectionProperties(input1));
        ok(domUtils.isInputWithoutSelectionProperties(input2));
    }

    notOk(domUtils.isInputWithoutSelectionProperties(input3));
});

test('isElementReadOnly', function () {
    var input = document.createElement('input');

    ok(!domUtils.isElementReadOnly(input));

    input.readOnly = true;

    ok(domUtils.isElementReadOnly(input));

    input.readOnly = false;

    ok(!domUtils.isElementReadOnly(input));

    input.setAttribute('readOnly', 'readOnly');

    ok(domUtils.isElementReadOnly(input));
});

module('regression');

test('isDocument infinite recursion (GH-923)', function () {
    var obj = eval(processScript('({ toString: function () { this.location = 1; } })'));

    ok(!domUtils.isDocument(obj));
});

test('isDocument for a cross-domain object (GH-467)', function () {
    return createTestIframe({ src: getCrossDomainPageUrl('../../data/cross-domain/target-url.html') })
        .then(function (iframe) {
            ok(!domUtils.isDocument(iframe.contentWindow));
        });
});

test('isDomElement for <object> tag (B252941)', function () {
    var objectElement = document.createElement('object');

    document.body.appendChild(objectElement);

    ok(domUtils.isDomElement(objectElement));

    objectElement.parentNode.removeChild(objectElement);
});

asyncTest('cross domain iframe that contains iframe without src should not throw the security error (GH-114)', function () {
    var iframe = document.createElement('iframe');

    iframe.src = getCrossDomainPageUrl('../../data/cross-domain/page-with-iframe-with-js-protocol.html');

    window.addEventListener('message', function (e) {
        strictEqual(e.data, 'ok');

        document.body.removeChild(iframe);

        start();
    });

    document.body.appendChild(iframe);
});

if (!browserUtils.isFirefox) {
    test('getIframeByElement', function () {
        var parentIframe = null;
        var childIframe  = null;

        return createTestIframe()
            .then(function (iframe) {
                parentIframe = iframe;

                return createTestIframe(null, parentIframe.contentDocument.body);
            })
            .then(function (iframe) {
                childIframe = iframe;

                var parentIframeUtils = parentIframe.contentWindow['%hammerhead%'].utils.dom;
                var childIframeUtils  = childIframe.contentWindow['%hammerhead%'].utils.dom;

                strictEqual(domUtils.getIframeByElement(parentIframe.contentDocument.body), parentIframe);
                strictEqual(domUtils.getIframeByElement(childIframe.contentDocument.body), childIframe);
                strictEqual(childIframeUtils.getIframeByElement(parentIframe.contentDocument.body), parentIframe);
                strictEqual(childIframeUtils.getIframeByElement(childIframe.contentDocument.body), childIframe);
                strictEqual(parentIframeUtils.getIframeByElement(parentIframe.contentDocument.body), parentIframe);
                strictEqual(parentIframeUtils.getIframeByElement(childIframe.contentDocument.body), childIframe);
            });
    });
}

test("An object with the 'tagName' and 'nodeName' properties shouldn't be recognized as a dom element", function () {
    notOk(domUtils.isIframeElement({ tagName: 'iframe', nodeName: 'iframe' }), 'iframe');
    notOk(domUtils.isFrameElement({ tagName: 'frame', nodeName: 'frame' }), 'frame');
    notOk(domUtils.isImgElement({ tagName: 'img', nodeName: 'img' }), 'img');
    notOk(domUtils.isInputElement({ tagName: 'input', nodeName: 'input' }), 'input');
    notOk(domUtils.isHtmlElement({ tagName: 'html', nodeName: 'html' }), 'html');
    notOk(domUtils.isBodyElement({ tagName: 'body', nodeName: 'body' }), 'body');
    notOk(domUtils.isHeadElement({ tagName: 'head', nodeName: 'head' }), 'head');
    notOk(domUtils.isHeadOrBodyElement({ tagName: 'body', nodeName: 'body' }), 'body');
    notOk(domUtils.isHeadOrBodyElement({ tagName: 'head', nodeName: 'head' }), 'head');
    notOk(domUtils.isBaseElement({ tagName: 'base', nodeName: 'base' }), 'base');
    notOk(domUtils.isScriptElement({ tagName: 'script', nodeName: 'script' }), 'script');
    notOk(domUtils.isStyleElement({ tagName: 'style', nodeName: 'style' }), 'style');
    notOk(domUtils.isLabelElement({ tagName: 'label', nodeName: 'label' }), 'label');
    notOk(domUtils.isTextAreaElement({ tagName: 'textarea', nodeName: 'textarea' }), 'textarea');
    notOk(domUtils.isOptionElement({ tagName: 'option', nodeName: 'option' }), 'option');
    notOk(domUtils.isSelectElement({ tagName: 'select', nodeName: 'select' }), 'select');
    notOk(domUtils.isFormElement({ tagName: 'form', nodeName: 'form' }), 'form');
    notOk(domUtils.isMapElement({ tagName: 'map', nodeName: 'map' }), 'map');
    notOk(domUtils.isMapElement({ tagName: 'area', nodeName: 'area' }), 'area');
    notOk(domUtils.isAnchorElement({ tagName: 'a', nodeName: 'a' }), 'a');
    notOk(domUtils.isTableElement({ tagName: 'table', nodeName: 'table' }), 'table');
    notOk(domUtils.isTableDataCellElement({ tagName: 'td', nodeName: 'td' }), 'td');
});

test('inspect html elements', function () {
    const htmlElements = [
        { tagName: 'iframe', assertFn: domUtils.isIframeElement },
        { tagName: 'frame', assertFn: domUtils.isFrameElement },
        { tagName: 'img', assertFn: domUtils.isImgElement },
        { tagName: 'input', assertFn: domUtils.isInputElement },
        { tagName: 'html', assertFn: domUtils.isHtmlElement },
        { tagName: 'body', assertFn: domUtils.isBodyElement },
        { tagName: 'head', assertFn: domUtils.isHeadElement },
        { tagName: 'body', assertFn: domUtils.isHeadOrBodyElement },
        { tagName: 'head', assertFn: domUtils.isHeadOrBodyElement },
        { tagName: 'base', assertFn: domUtils.isBaseElement },
        { tagName: 'script', assertFn: domUtils.isScriptElement },
        { tagName: 'style', assertFn: domUtils.isStyleElement },
        { tagName: 'label', assertFn: domUtils.isLabelElement },
        { tagName: 'textarea', assertFn: domUtils.isTextAreaElement },
        { tagName: 'option', assertFn: domUtils.isOptionElement },
        { tagName: 'select', assertFn: domUtils.isSelectElement },
        { tagName: 'form', assertFn: domUtils.isFormElement },
        { tagName: 'map', assertFn: domUtils.isMapElement },
        { tagName: 'area', assertFn: domUtils.isMapElement },
        { tagName: 'a', assertFn: domUtils.isAnchorElement },
        { tagName: 'table', assertFn: domUtils.isTableElement },
        { tagName: 'td', assertFn: domUtils.isTableDataCellElement },
        { tagName: 'input', assertFn: domUtils.isRadioButtonElement, attributes: { type: 'radio' } },
        { tagName: 'input', assertFn: domUtils.isCheckboxElement, attributes: { type: 'checkbox' } }
    ];

    if (!browserUtils.isIE11 && !browserUtils.isSafari)
        htmlElements.push({ tagName: 'input', assertFn: domUtils.isColorInputElement, attributes: { type: 'color' } });

    htmlElements.forEach(function (info) {
        var existingTags = ['html', 'body', 'script', 'head'];
        var element      = null;

        if (existingTags.indexOf(info.tagName) > -1)
            element = nativeMethods.querySelector.call(document, info.tagName);
        else
            element = nativeMethods.createElement.call(document, info.tagName);

        if (info.attributes) {
            Object.keys(info.attributes).forEach(function (attr) {
                nativeMethods.setAttribute.call(element, attr, info.attributes[attr]);
            });
        }

        ok(info.assertFn(element), info.tagName);
    });
});

test('isInputWithNativeDialog', function () {
    var checkedInputTypes = ['color', 'date', 'datetime-local', 'month', 'week'];
    var countCheckedTypes = 0;

    for (var i = 0; i < checkedInputTypes.length; i++) {
        var checkedInputType = checkedInputTypes[i];
        var checkedInput = document.createElement('input');

        checkedInput.type = checkedInputType;

        // NOTE: check the browser support for the specified input type
        if (checkedInput.type !== checkedInputType)
            continue;

        countCheckedTypes++;
        ok(domUtils.isInputWithNativeDialog(checkedInput), checkedInputType);
    }

    if (countCheckedTypes === 0)
        expect(0);
});

if (browserUtils.isChrome) {
    test('should return active element inside shadow DOM', function () {
        var host  = document.createElement('div');
        var root  = host.attachShadow({ mode: 'open' });
        var input = document.createElement('input');

        document.body.appendChild(host);
        root.appendChild(input);

        nativeMethods.focus.call(input);

        strictEqual(domUtils.getActiveElement(), input);

        document.body.removeChild(host);
    });

    test('should return active element inside nested shadow DOM', function () {
        var hostParent = document.createElement('div');
        var hostChild  = document.createElement('div');
        var rootParent = hostParent.attachShadow({ mode: 'open' });
        var rootChild  = hostChild.attachShadow({ mode: 'open' });
        var input      = document.createElement('input');

        document.body.appendChild(hostParent);
        rootParent.appendChild(hostChild);
        rootChild.appendChild(input);

        nativeMethods.focus.call(input);

        strictEqual(domUtils.getActiveElement(), input);

        document.body.removeChild(hostParent);
    });
}

if (window.HTMLElement.prototype.attachShadow) {
    test('isShadowRoot', function () {
        notOk(domUtils.isShadowRoot(null));
        notOk(domUtils.isShadowRoot(document));
        notOk(domUtils.isShadowRoot(window));
        notOk(domUtils.isShadowRoot(document.createElement('div')));
        ok(domUtils.isShadowRoot(document.createElement('div').attachShadow({ mode: 'open' })));
    });

    test('"getParents" should work properly for elements inside shadowDOM', function () {
        var host  = document.createElement('div');
        var root  = host.attachShadow({ mode: 'open' });
        var div   = document.createElement('div');
        var input = document.createElement('input');

        document.body.appendChild(host);
        div.appendChild(input);
        root.appendChild(div);

        var parents = domUtils.getParents(input);

        deepEqual(parents, [div, host, document.body, document.documentElement]);
        document.body.removeChild(host);
    });

    test('"getParents" should work property for elements with slots/templates', function () {
        var template = document.createElement('template');

        template.innerHTML = '<div class=\'slot-parent\'><slot name=\'slot-name\'></slot></div>';

        // NOTE: bypass IE syntax validation
        customElements.define('custom-test-element', eval(
            '(class El extends HTMLElement { ' +
            'constructor () { ' +
            '   super(); ' +
            '   var templateContent = template.content; ' +
            '   this.attachShadow({ mode: \'open\' }).appendChild(templateContent.cloneNode(true)); ' +
            '} ' +
        '})'
        ));

        var custom = document.createElement('custom-test-element');
        var button = document.createElement('button');

        custom.innerHTML = '<div class="div-slot" slot="slot-name"></div>';
        button.innerHTML = 'Click me';

        var slotParent  = custom.shadowRoot.querySelector('div.slot-parent');
        var slotContent = custom.querySelector('div.div-slot');

        slotContent.appendChild(button);
        document.body.appendChild(custom);

        deepEqual(domUtils.getParents(button), [slotContent, slotParent, custom, document.body, document.documentElement]);

        document.body.removeChild(custom);
    });
}

if (window.HTMLElement.prototype.matches && window.HTMLElement.prototype.closest) {
    test('`closest` and `matches` methods should use stored native methods (GH-1603)', function () {
        var div             = document.createElement('div');
        var storedMatchesFn = window.HTMLElement.prototype.matches;

        window.HTMLElement.prototype.matches = function () {
            ok(false, 'Should not use the `HTMLElement.prototype.matches` method');
        };
        window.HTMLElement.prototype.closest = function () {
            ok(false, 'Should not use the `HTMLElement.prototype.closest method`');
        };
        document.body.appendChild(div);

        ok(domUtils.matches(div, 'div'));
        strictEqual(domUtils.closest(div, 'div'), div);

        window.HTMLElement.prototype.matches = storedMatchesFn;
    });
}

test('hammerhead should use the native classList getter in addClass, removeClass and hasClass functions (GH-1890)', function () {
    var div                           = document.createElement('div');
    var elementClassListPropOwnerName = window.Element.prototype.hasOwnProperty('classList') ? 'Element' : 'HTMLElement';
    var storedСlassListDescriptor     = Object.getOwnPropertyDescriptor(window[elementClassListPropOwnerName].prototype, 'classList');

    Object.defineProperty(window[elementClassListPropOwnerName].prototype, 'classList', {
        get: function () { /* eslint-disable-line getter-return */
            ok(false);
        },

        configurable: true
    });

    document.body.appendChild(div);

    domUtils.addClass(div, 'test');
    ok(domUtils.hasClass(div, 'test'));
    domUtils.removeClass(div, 'test');

    div.parentNode.removeChild(div);

    Object.defineProperty(window[elementClassListPropOwnerName], 'classList', storedСlassListDescriptor);
});


text:
function HoleFilling_sp_cnn_fixed()

cnn_dim = [128, 128];
numUnits = [1 4];
interval = 16;

test_dir = '../../test_files/';
tests = {'lowerA', 'capitalA', 'vertLine', 'circle', 'rect', 'filledSquare', 'zero', 'seven', 'eight', 'nine'};
%tests = {'filledSquare'};
raw = cell(length(tests) + 1, 5);
raw(1, 1:5) = {'Test', 'Num CNN', 'Num Iters.' 'Total Conv Time', 'Virtual Conv Time'};
ind = 2;
for i = 1:length(tests)
    for numCNN = numUnits
        test_name = tests{i};
        disp(test_name);
        img_file = [test_dir, test_name, '_512x512.dlm'];
        runData = HoleFilling_sp_cnn_fixed_interval(test_name, img_file, cnn_dim, interval, numCNN );
        raw{ind, 1} = test_name;
        raw{ind, 2} = numCNN;
        raw{ind, 3} = runData.numIters;
        raw{ind, 4} = runData.tot_conv_time;
        raw{ind, 5} = runData.virt_conv_time;
        ind = ind + 1;
    end
end
my_csvwrite('fixed_interval_results/results.csv', raw);
end

function [runData] = HoleFilling_sp_cnn_fixed_interval(test_name, img_file, cnn_dim, interval, numCNN)
img = dlmread(img_file);
dim = size(img);

[r, A, B, z, u, initState ] = HoleFilling_gene(img);

partitions = gen_partitions2D(dim, cnn_dim, 'row-major');

[runData, state, output ] = sp_cnn('fixed-interval', cnn_dim, r, A, B, z, initState, u, ...
    partitions, interval, numCNN );
file_header = sprintf('fixed_interval_results/%s_%d', test_name, numCNN);
dlmwrite([file_header '_state.dlm'], state, ' ');
dlmwrite([file_header '_output.dlm'], output, ' ');

end

redpajama_set_name: RedPajamaGithub


text:
body{width:100%;height:100%;font-family:Lora,"Helvetica Neue",Helvetica,Arial,sans-serif;color:#fff;background-color:#000;overflow-x:hidden}
html{width:100%;height:100%}
h1,h2,h3,h4,h5,h6{margin:0 0 35px;text-transform:uppercase;font-family:Roboto,"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:700;letter-spacing:1px}
p{margin:0 0 25px;font-size:18px;line-height:1.5}
@media (min-width:768px){
p{margin:0 0 35px;font-size:20px;line-height:1.6}
}
a{color:#42dca3;-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;transition:all .2s ease-in-out}
a:focus,a:hover{text-decoration:none;color:#1d9b6c}
.light{font-weight:400}
.navbar-custom{margin-bottom:0;border-bottom:1px solid rgba(255,255,255,.3);text-transform:uppercase;font-family:Roboto,"Helvetica Neue",Helvetica,Arial,sans-serif;background-color:#000}
.navbar-custom .navbar-toggle{color:#fff;background-color:rgba(255,255,255,.2);font-size:12px}
.navbar-custom .navbar-toggle:active,.navbar-custom .navbar-toggle:focus{outline:0}
.navbar-custom .navbar-brand{font-weight:700}
.navbar-custom .navbar-brand:focus{outline:0}
.navbar-custom a{color:#fff}
.navbar-custom .nav li a{-webkit-transition:background .3s ease-in-out;-moz-transition:background .3s ease-in-out;transition:background .3s ease-in-out}
.navbar-custom .nav li a:hover{color:rgba(255,255,255,.8);outline:0;background-color:transparent}
.navbar-custom .nav li a:active,.navbar-custom .nav li a:focus{outline:0;background-color:transparent}
.navbar-custom .nav li.active{outline:0}
.navbar-custom .nav li.active a{background-color:rgba(255,255,255,.3)}
.navbar-custom .nav li.active a:hover{color:#fff}
@media (min-width:768px){
.navbar-custom{padding:20px 0;border-bottom:none;letter-spacing:1px;background:0 0;-webkit-transition:background .5s ease-in-out,padding .5s ease-in-out;-moz-transition:background .5s ease-in-out,padding .5s ease-in-out;transition:background .5s ease-in-out,padding .5s ease-in-out}
.navbar-custom.top-nav-collapse{padding:0;background:#000;border-bottom:1px solid rgba(255,255,255,.3)}
}
.intro{display:table;width:100%;height:auto;padding:100px 0;text-align:center;color:#fff;background:url(../img/emu_bg.jpg) no-repeat bottom center scroll;background-color:#000;background-attachment:fixed;-webkit-background-size:cover;-moz-background-size:cover;background-size:cover;-o-background-size:cover}
.intro .intro-body{display:table-cell;vertical-align:middle}
.intro .intro-body .brand-heading{font-size:40px}
.intro .intro-body .intro-text{font-size:18px}
@media (min-width:768px){
.intro{height:100%;padding:0}
.intro .intro-body .brand-heading{font-size:100px}
.intro .intro-body .intro-text{font-size:26px}
}
.btn-circle{width:70px;height:70px;margin-top:15px;padding:7px 16px;border:2px solid #fff;border-radius:100%!important;font-size:40px;color:#fff;background:0 0;-webkit-transition:background .3s ease-in-out;-moz-transition:background .3s ease-in-out;transition:background .3s ease-in-out}
.btn-circle:focus,.btn-circle:hover{outline:0;color:#fff;background:rgba(255,255,255,.1)}
.btn-circle i.animated{-webkit-transition-property:-webkit-transform;-webkit-transition-duration:1s;-moz-transition-property:-moz-transform;-moz-transition-duration:1s}
.btn-circle:hover i.animated{-webkit-animation-name:pulse;-moz-animation-name:pulse;-webkit-animation-duration:1.5s;-moz-animation-duration:1.5s;-webkit-animation-iteration-count:infinite;-moz-animation-iteration-count:infinite;-webkit-animation-timing-function:linear;-moz-animation-timing-function:linear}
@-webkit-keyframes pulse{
0%{-webkit-transform:scale(1);transform:scale(1)}
50%{-webkit-transform:scale(1.2);transform:scale(1.2)}
100%{-webkit-transform:scale(1);transform:scale(1)}
}
@-moz-keyframes pulse{
0%{-moz-transform:scale(1);transform:scale(1)}
50%{-moz-transform:scale(1.2);transform:scale(1.2)}
100%{-moz-transform:scale(1);transform:scale(1)}
}
.content-section{padding-top:100px}
.download-section{width:100%;padding:50px 0;color:#fff;background:url(../img/downloads-bg.jpg) no-repeat center center scroll;background-color:#000;-webkit-background-size:cover;-moz-background-size:cover;background-size:cover;-o-background-size:cover}
#map{width:100%;height:200px;margin-top:100px}
@media (min-width:767px){
.content-section{padding-top:250px}
.download-section{padding:100px 0}
#map{height:400px;margin-top:250px}
}
.btn{text-transform:uppercase;font-family:Roboto,"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;-webkit-transition:all .3s ease-in-out;-moz-transition:all .3s ease-in-out;transition:all .3s ease-in-out;border-radius:0}
.btn-default,.btn-default:focus{background-color:transparent;border-color:#fff;color:#fff;outline:0;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px}
.btn-default:hover{background-color:#fff;color:#000}
.btn-default:active{background-color:rgba(255,255,255,.1);border-color:#000;outline:0}
ul.banner-social-buttons{margin-top:0}
@media (max-width:1199px){
ul.banner-social-buttons{margin-top:15px}
}
@media (max-width:767px){
ul.banner-social-buttons li{display:block;margin-bottom:20px;padding:0}
ul.banner-social-buttons li:last-child{margin-bottom:0}
}
footer{padding:50px 0}
footer p{margin:0}
::-moz-selection{text-shadow:none;background:#fcfcfc;background:rgba(255,255,255,.2)}
::selection{text-shadow:none;background:#fcfcfc;background:rgba(255,255,255,.2)}
img::selection{background:0 0}
img::-moz-selection{background:0 0}
body{webkit-tap-highlight-color:rgba(255,255,255,.2)}
.streams{position:relative;display:inline-block;overflow:hidden}
.music h4{margin:35px 0 10px}
.music p a{font-size:50px;color:rgba(255,255,255,.4);padding:0 15px}
.music a:hover{color:#fff}


text:
module ListPulls where

import qualified Github.PullRequests as Github
import Data.List

main = do
  possiblePullRequests <- Github.pullRequestsFor "thoughtbot" "paperclip"
  case possiblePullRequests of
       (Left error) -> putStrLn $ "Error: " ++ (show error)
       (Right pullRequests) ->
         putStrLn $ intercalate "\n\n" $ map formatPullRequest pullRequests

formatPullRequest pullRequest =
  (Github.pullRequestTitle pullRequest) ++ "\n" ++
    (take 80 $ Github.pullRequestBody pullRequest) ++ "\n" ++
    (Github.githubOwnerLogin $ Github.pullRequestUser pullRequest) ++
    " submitted to thoughtbot/paperclip " ++
    (formatDate $ Github.pullRequestCreatedAt pullRequest) ++
    " updated " ++
    (formatDate $ Github.pullRequestUpdatedAt pullRequest) ++ "\n" ++
    (Github.pullRequestHtmlUrl pullRequest)

formatDate = show . Github.fromDate


text:
/**
 * Roll a number of dice with a number of sides.
 *
 * If only one argument is provided, it is assumed to be
 * the number of 6 sided dice.
 *
 * If no arguments are provided, a single d6 is rolled.
 *
 * Returns an array containing all of the die rolls.
 */
module.exports = function(numberOfDice, numberOfSides) {
    var rolls = [],
        latestResult,
        totalResult = 0;
    // Normalize the request, first.
    if (numberOfSides === undefined) {
        numberOfSides = 6;
    }

    if (numberOfDice === undefined) {
        numberOfDice = 1;
    }

    for (var i = 0; i < numberOfDice; i++) {
        latestResult = Math.floor(Math.random() * numberOfSides) + 1;
        rolls.push(latestResult);
        totalResult += latestResult;
    }

    return {
        rolls: rolls,
        total: totalResult
    }
};


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
module System.IO.Machine where

#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.IOData (IOData, hGetChunk, hGetLine, hPut, hPutStrLn)
import Data.Machine
import Data.Word (Word8)
import System.IO (Handle, hIsEOF)

import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC8

type DataModeIO m a = MonadIO m => ((Handle -> m a), (Handle -> a -> m ()))
type SinkIO m k = MonadIO m => forall a. ProcessT m k a
type SourceIO m a = MonadIO m => forall k. MachineT m k a

type IODataMode a = ((Handle -> IO a), (Handle -> a -> IO ()))
type IOSink k = forall a. ProcessT IO k a
type IOSource a = forall k. MachineT IO k a

byChar :: IODataMode Char
byChar = (\h -> BSC8.head <$> BSC8.hGet h 1, \h w -> BSC8.hPut h $ BSC8.pack [w])

byChunk ::  IOData a => IODataMode a
byChunk = (\h -> hGetChunk h, \h xs -> hPut h xs)

byChunkOf :: Int -> IODataMode BS.ByteString
byChunkOf n = (\h -> BS.hGet h n, \h xs -> BS.hPut h xs)

byWord8 :: IODataMode Word8
byWord8 = (\h -> BS.head <$> BS.hGet h 1, \h w -> BS.hPut h $ BS.pack [w])

byLine :: IOData a => DataModeIO m a
byLine = (hGetLine, hPutStrLn)

sourceIO :: IO a -> SourceIO m a
sourceIO f = repeatedly $ liftIO f >>= yield

sourceHandle :: DataModeIO m a -> Handle -> SourceIO m a
sourceHandle (r, _) = sourceHandleWith r

sourceIOWith :: m r -> (r -> m Bool) -> (r -> m a) -> SourceIO m a
sourceIOWith acquire release read' = MachineT $ do
  r         <- acquire
  released  <- release r
  if released then
    return Stop
  else do
    x <- read' r
    return . Yield x $ sourceIOWith acquire release read'

sourceHandleWith :: (Handle -> m a) -> Handle -> SourceIO m a
sourceHandleWith f h = sourceIOWith (return h) (liftIO . hIsEOF) f

sinkIO :: (a -> IO ()) -> SinkIO m a
sinkIO f = repeatedly $ await >>= liftIO . f

sinkHandle :: IODataMode a -> Handle -> SinkIO m a
sinkHandle (_, w) h = repeatedly $ await >>= liftIO . w h

sinkHandleWith :: (Handle -> a -> IO ()) -> Handle -> SinkIO m a
sinkHandleWith f h = repeatedly $ await >>= liftIO . f h

filteredIO :: (a -> IO Bool) -> ProcessT IO a a
filteredIO p = repeatedly $ do
  i <- await
  x <- liftIO $ p i
  if x then yield i else return ()

printer :: Show a => SinkIO m a
printer = sinkIO $ liftIO . print


text:
package nfs

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path"
	"strings"
	"syscall"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/pborman/uuid"

	"github.com/portworx/kvdb"

	"github.com/libopenstorage/openstorage/api"
	"github.com/libopenstorage/openstorage/pkg/mount"
	"github.com/libopenstorage/openstorage/pkg/seed"
	"github.com/libopenstorage/openstorage/volume"
)

const (
	Name         = "nfs"
	Type         = volume.File
	NfsDBKey     = "OpenStorageNFSKey"
	nfsMountPath = "/var/lib/openstorage/nfs/"
	nfsBlockFile = ".blockdevice"
)

// Implements the open storage volume interface.
type driver struct {
	*volume.DefaultEnumerator
	nfsServer string
	nfsPath   string
	mounter   mount.Manager
}

func copyFile(source string, dest string) (err error) {
	sourcefile, err := os.Open(source)
	if err != nil {
		return err
	}

	defer sourcefile.Close()

	destfile, err := os.Create(dest)
	if err != nil {
		return err
	}

	defer destfile.Close()

	_, err = io.Copy(destfile, sourcefile)
	if err == nil {
		sourceinfo, err := os.Stat(source)
		if err != nil {
			err = os.Chmod(dest, sourceinfo.Mode())
		}

	}

	return
}

func copyDir(source string, dest string) (err error) {
	// get properties of source dir
	sourceinfo, err := os.Stat(source)
	if err != nil {
		return err
	}

	// create dest dir

	err = os.MkdirAll(dest, sourceinfo.Mode())
	if err != nil {
		return err
	}

	directory, _ := os.Open(source)

	objects, err := directory.Readdir(-1)

	for _, obj := range objects {

		sourcefilepointer := source + "/" + obj.Name()

		destinationfilepointer := dest + "/" + obj.Name()

		if obj.IsDir() {
			// create sub-directories - recursively
			err = copyDir(sourcefilepointer, destinationfilepointer)
			if err != nil {
				fmt.Println(err)
			}
		} else {
			// perform copy
			err = copyFile(sourcefilepointer, destinationfilepointer)
			if err != nil {
				fmt.Println(err)
			}
		}

	}
	return
}

func Init(params volume.DriverParams) (volume.VolumeDriver, error) {
	path, ok := params["path"]
	if !ok {
		return nil, errors.New("No NFS path provided")
	}

	server, ok := params["server"]
	if !ok {
		log.Printf("No NFS server provided, will attempt to bind mount %s", path)
	} else {
		log.Printf("NFS driver initializing with %s:%s ", server, path)
	}

	// Create a mount manager for this NFS server. Blank sever is OK.
	mounter, err := mount.New(mount.NFSMount, server)
	if err != nil {
		log.Warnf("Failed to create mount manager for server: %v (%v)", server, err)
		return nil, err
	}

	inst := &driver{
		DefaultEnumerator: volume.NewDefaultEnumerator(Name, kvdb.Instance()),
		nfsServer:         server,
		nfsPath:           path,
		mounter:           mounter,
	}

	err = os.MkdirAll(nfsMountPath, 0744)
	if err != nil {
		return nil, err
	}
	src := inst.nfsPath
	if server != "" {
		src = ":" + inst.nfsPath
	}

	// If src is already mounted at dest, leave it be.
	mountExists, err := mounter.Exists(src, nfsMountPath)
	if !mountExists {
		// Mount the nfs server locally on a unique path.
		syscall.Unmount(nfsMountPath, 0)
		if server != "" {
			err = syscall.Mount(src, nfsMountPath, "nfs", 0, "nolock,addr="+inst.nfsServer)
		} else {
			err = syscall.Mount(src, nfsMountPath, "", syscall.MS_BIND, "")
		}
		if err != nil {
			log.Printf("Unable to mount %s:%s at %s (%+v)", inst.nfsServer, inst.nfsPath, nfsMountPath, err)
			return nil, err
		}
	}

	volumeInfo, err := inst.DefaultEnumerator.Enumerate(
		api.VolumeLocator{},
		nil)
	if err == nil {
		for _, info := range volumeInfo {
			if info.Status == "" {
				info.Status = api.Up
				inst.UpdateVol(&info)
			}
		}
	} else {
		log.Println("Could not enumerate Volumes, ", err)
	}

	log.Println("NFS initialized and driver mounted at: ", nfsMountPath)
	return inst, nil
}

func (d *driver) String() string {
	return Name
}

func (d *driver) Type() volume.DriverType {
	return Type
}

// Status diagnostic information
func (d *driver) Status() [][2]string {
	return [][2]string{}
}

func (d *driver) Create(locator api.VolumeLocator, opt *api.CreateOptions, spec *api.VolumeSpec) (api.VolumeID, error) {
	volumeID := uuid.New()
	volumeID = strings.TrimSuffix(volumeID, "\n")

	// Create a directory on the NFS server with this UUID.
	volPath := path.Join(nfsMountPath, volumeID)
	err := os.MkdirAll(volPath, 0744)
	if err != nil {
		log.Println(err)
		return api.BadVolumeID, err
	}
	if opt != nil && len(opt.CreateFromSource) != 0 {
		seed, err := seed.New(opt.CreateFromSource, spec.ConfigLabels)
		if err != nil {
			log.Warnf("Failed to initailize seed from %q : %v",
				opt.CreateFromSource, err)
			return api.BadVolumeID, err
		}
		err = seed.Load(volPath)
		if err != nil {
			log.Warnf("Failed to  seed from %q to %q: %v",
				opt.CreateFromSource, nfsMountPath, err)
			return api.BadVolumeID, err
		}
	}

	f, err := os.Create(path.Join(nfsMountPath, volumeID, nfsBlockFile))
	if err != nil {
		log.Println(err)
		return api.BadVolumeID, err
	}
	defer f.Close()

	err = f.Truncate(int64(spec.Size))
	if err != nil {
		log.Println(err)
		return api.BadVolumeID, err
	}

	v := &api.Volume{
		ID:         api.VolumeID(volumeID),
		Locator:    locator,
		Ctime:      time.Now(),
		Spec:       spec,
		LastScan:   time.Now(),
		Format:     "nfs",
		State:      api.VolumeAvailable,
		Status:     api.Up,
		DevicePath: path.Join(nfsMountPath, string(volumeID), nfsBlockFile),
	}

	err = d.CreateVol(v)
	if err != nil {
		return api.BadVolumeID, err
	}
	return v.ID, err
}

func (d *driver) Delete(volumeID api.VolumeID) error {
	v, err := d.GetVol(volumeID)
	if err != nil {
		log.Println(err)
		return err
	}

	// Delete the simulated block volume
	os.Remove(v.DevicePath)

	// Delete the directory on the nfs server.
	os.RemoveAll(path.Join(nfsMountPath, string(volumeID)))

	err = d.DeleteVol(volumeID)
	if err != nil {
		log.Println(err)
		return err
	}

	return nil
}

func (d *driver) Mount(volumeID api.VolumeID, mountpath string) error {
	v, err := d.GetVol(volumeID)
	if err != nil {
		log.Println(err)
		return err
	}

	srcPath := path.Join(":", d.nfsPath, string(volumeID))
	mountExists, err := d.mounter.Exists(srcPath, mountpath)
	if !mountExists {
		syscall.Unmount(mountpath, 0)
		err = syscall.Mount(path.Join(nfsMountPath, string(volumeID)), mountpath, string(v.Spec.Format), syscall.MS_BIND, "")
		if err != nil {
			log.Printf("Cannot mount %s at %s because %+v",
				path.Join(nfsMountPath, string(volumeID)), mountpath, err)
			return err
		}
	}

	v.AttachPath = mountpath
	err = d.UpdateVol(v)

	return err
}

func (d *driver) Unmount(volumeID api.VolumeID, mountpath string) error {
	v, err := d.GetVol(volumeID)
	if err != nil {
		return err
	}
	if v.AttachPath == "" {
		return fmt.Errorf("Device %v not mounted", volumeID)
	}
	err = syscall.Unmount(v.AttachPath, 0)
	if err != nil {
		return err
	}
	v.AttachPath = ""
	err = d.UpdateVol(v)
	return err
}

func (d *driver) Snapshot(volumeID api.VolumeID, readonly bool, locator api.VolumeLocator) (api.VolumeID, error) {
	volIDs := make([]api.VolumeID, 1)
	volIDs[0] = volumeID
	vols, err := d.Inspect(volIDs)
	if err != nil {
		return api.BadVolumeID, nil
	}

	newVolumeID, err := d.Create(locator, nil, vols[0].Spec)
	if err != nil {
		return api.BadVolumeID, nil
	}

	// NFS does not support snapshots, so just copy the files.
	err = copyDir(nfsMountPath+string(volumeID), nfsMountPath+string(newVolumeID))
	if err != nil {
		d.Delete(newVolumeID)
		return api.BadVolumeID, nil
	}

	return newVolumeID, nil
}

func (d *driver) Attach(volumeID api.VolumeID) (string, error) {
	return path.Join(nfsMountPath, string(volumeID), nfsBlockFile), nil
}

func (d *driver) Format(volumeID api.VolumeID) error {
	return nil
}

func (d *driver) Detach(volumeID api.VolumeID) error {
	return nil
}

func (d *driver) Stats(volumeID api.VolumeID) (api.Stats, error) {
	return api.Stats{}, volume.ErrNotSupported
}

func (d *driver) Alerts(volumeID api.VolumeID) (api.Alerts, error) {
	return api.Alerts{}, volume.ErrNotSupported
}

func (d *driver) Shutdown() {
	log.Printf("%s Shutting down", Name)
	syscall.Unmount(nfsMountPath, 0)
}

func init() {
	// Register ourselves as an openstorage volume driver.
	volume.Register(Name, Init)
}


text:
using hyperdex::backup_state_machine;

backup_state_machine :: backup_state_machine(const char* name,
                                             uint64_t id,
                                             hyperdex_admin_returncode* status,
                                             const char** backups)
    : multi_yieldable(id, status)
    , m_name(name)
    , m_state(INITIALIZED)
    , m_nested_id()
    , m_nested_rc()
    , m_configuration_version(0)
    , m_servers()
    , m_backup(NULL)
    , m_backups()
    , m_backups_str()
    , m_backups_c_str(backups)
{
}

backup_state_machine :: ~backup_state_machine() throw ()
{
}

bool
backup_state_machine :: can_yield()
{
    return m_state == DONE || m_state == ERROR;
}

bool
backup_state_machine :: yield(hyperdex_admin_returncode* status)
{
    assert(this->can_yield());
    *status = HYPERDEX_ADMIN_SUCCESS;
    m_state = YIELDED;
    m_backups_str = m_backups.str();
    *m_backups_c_str = m_backups_str.c_str();
    return true;
}

bool
backup_state_machine :: initialize(admin* adm, hyperdex_admin_returncode* status)
{
    *status = HYPERDEX_ADMIN_SUCCESS;
    m_nested_id = adm->read_only(1, &m_nested_rc);

    if (!check_nested(adm))
    {
        *status = m_nested_rc;
        return false;
    }

    adm->m_multi_ops[m_nested_id] = this;
    m_state = SET_READ_ONLY;
    return true;
}

bool
backup_state_machine :: callback(admin* adm, int64_t id, hyperdex_admin_returncode* status)
{
    *status = HYPERDEX_ADMIN_SUCCESS;

    switch (m_state)
    {
        case INITIALIZED:
            callback_unexpected(adm, id);
            return true;
        case SET_READ_ONLY:
            callback_set_read_only(adm, id);
            return true;
        case WAIT_TO_QUIESCE:
            callback_wait_to_quiesce(adm, id);
            return true;
        case DAEMON_BACKUP:
            callback_daemon_backup(adm, id);
            return true;
        case COORD_BACKUP:
            callback_coord_backup(adm, id);
            return true;
        case WAIT_TO_QUIESCE_AGAIN:
            callback_wait_to_quiesce_again(adm, id);
            return true;
        case SET_READ_WRITE:
            callback_set_read_write(adm, id);
            return true;
        case DONE:
            callback_unexpected(adm, id);
            return true;
        case BACKOUT:
            callback_backout(adm, id);
            return true;
        case ERROR:
            callback_unexpected(adm, id);
            return true;
        case YIELDED:
            callback_unexpected(adm, id);
            return true;
        default:
            YIELDING_ERROR(INTERNAL) << "wandered into undefined state";
            return true;
    }
}

void
backup_state_machine :: backout(admin* adm)
{
    m_nested_id = adm->read_only(0, &m_nested_rc);

    if (m_nested_id < 0)
    {
        m_state = ERROR;
    }
    else
    {
        adm->m_multi_ops[m_nested_id] = this;
    }
}

bool
backup_state_machine :: common_callback(admin* adm, int64_t id)
{
    bool ret = true;

    if (m_state == ERROR || m_state == YIELDED)
    {
        ret = false;
    }
    else if (m_nested_id != id)
    {
        YIELDING_ERROR(INTERNAL) << "callback had id=" << id
                                 << " when it should have id=" << m_nested_id;
        m_state = m_state > SET_READ_ONLY ? BACKOUT : ERROR;
        ret = false;
    }
    else if (m_nested_rc != HYPERDEX_ADMIN_SUCCESS)
    {
        this->set_status(m_nested_rc);
        this->set_error(adm->m_last_error);
        m_state = m_state > SET_READ_ONLY ? BACKOUT : ERROR;
        ret = false;
    }

    if (!ret && m_state == BACKOUT)
    {
        backout(adm);
    }

    return ret;
}

bool
backup_state_machine :: check_nested(admin* adm)
{
    if (m_nested_id >= 0)
    {
        return true;
    }

    this->set_status(m_nested_rc);
    this->set_error(adm->m_last_error);
    m_state = m_state >= SET_READ_ONLY ? BACKOUT : ERROR;

    if (m_state == BACKOUT)
    {
        backout(adm);
    }

    return false;
}

void
backup_state_machine :: callback_unexpected(admin*, int64_t)
{
    YIELDING_ERROR(INTERNAL) << "wandered into undefined state";
    m_state = ERROR;
}

void
backup_state_machine :: callback_set_read_only(admin* adm, int64_t id)
{
    if (!common_callback(adm, id))
    {
        return;
    }

    m_nested_id = adm->wait_until_stable(&m_nested_rc);

    if (!check_nested(adm))
    {
        return;
    }

    adm->m_multi_ops[m_nested_id] = this;
    m_state = WAIT_TO_QUIESCE;
}

void
backup_state_machine :: callback_wait_to_quiesce(admin* adm, int64_t id)
{
    if (!common_callback(adm, id))
    {
        return;
    }

    // at this point we know that:
    // 1. the cluster is in read-only mode
    // 2. every write initiated before setting it to read-only mode is complete
    m_configuration_version = adm->m_coord.config()->version();

    // now figure out the servers to take a backup on
    adm->m_coord.config()->get_all_addresses(&m_servers);
    std::sort(m_servers.rbegin(), m_servers.rend());
    return callback_daemon_backup(adm, id);
}

void
backup_state_machine :: callback_daemon_backup(admin* adm, int64_t id)
{
    if (!common_callback(adm, id))
    {
        return;
    }

    if (m_backup)
    {
        m_backups << m_backup << "\n";
        m_backup = NULL;
    }

    if (m_servers.empty())
    {
        std::string path = m_name + ".coordinator.bin";
        m_nested_id = adm->coord_backup(path.c_str(), &m_nested_rc);

        if (!check_nested(adm))
        {
            return;
        }

        adm->m_multi_ops[m_nested_id] = this;
        m_state = COORD_BACKUP;
        return;
    }

    server_id sid = m_servers.back().first;
    po6::net::location loc = m_servers.back().second;
    m_servers.pop_back();
    m_nested_id = adm->raw_backup(sid, m_name.c_str(), &m_nested_rc, &m_backup);
    m_backups << sid.get() << " " << loc.address << " ";

    if (!check_nested(adm))
    {
        return;
    }

    adm->m_multi_ops[m_nested_id] = this;
    m_state = DAEMON_BACKUP;
}

void
backup_state_machine :: callback_coord_backup(admin* adm, int64_t id)
{
    if (!common_callback(adm, id))
    {
        return;
    }

    m_nested_id = adm->wait_until_stable(&m_nested_rc);

    if (!check_nested(adm))
    {
        return;
    }

    adm->m_multi_ops[m_nested_id] = this;
    m_state = WAIT_TO_QUIESCE_AGAIN;
}

void
backup_state_machine :: callback_wait_to_quiesce_again(admin* adm, int64_t id)
{
    if (!common_callback(adm, id))
    {
        return;
    }

    if (m_configuration_version != adm->m_coord.config()->version())
    {
        YIELDING_ERROR(INTERNAL) << "configuration changed while taking backup";
        backout(adm);
    }

    m_nested_id = adm->read_only(0, &m_nested_rc);

    if (!check_nested(adm))
    {
        return;
    }

    adm->m_multi_ops[m_nested_id] = this;
    m_state = SET_READ_WRITE;
}

void
backup_state_machine :: callback_set_read_write(admin* adm, int64_t id)
{
    if (!common_callback(adm, id))
    {
        return;
    }

    this->set_status(HYPERDEX_ADMIN_SUCCESS);
    this->set_error(e::error());
    m_state = DONE;
}

void
backup_state_machine :: callback_backout(admin*, int64_t)
{
    m_state = ERROR;
}


text:
import os, shutil, time, sys, requests, argparse, subprocess, signal
from multiprocessing import Pool, cpu_count
import numpy as np
import scipy, scipy.misc
from scipy import ndimage

BASE_NORB_URL = 'http://www.cs.nyu.edu/~ylclab/data/norb-v1.0-small/'
SM_NORB_BASE_TR = BASE_NORB_URL + 'smallnorb-5x46789x9x18x6x2x96x96'
SM_NORB_BASE_TE = BASE_NORB_URL + 'smallnorb-5x01235x9x18x6x2x96x96'
SM_NORB_TR_DATA = SM_NORB_BASE_TR + '-training-dat.mat.gz'
SM_NORB_TR_LABELS = SM_NORB_BASE_TR + '-training-cat.mat.gz'
SM_NORB_TR_INFO = SM_NORB_BASE_TR + '-training-info.mat.gz'
SM_NORB_TE_DATA = SM_NORB_BASE_TE + '-testing-dat.mat.gz'
SM_NORB_TE_LABELS = SM_NORB_BASE_TE + '-testing-cat.mat.gz'
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))

IM_FORMAT = '.png'
MAT_SHAPE = (24300,2,96,96)
NUM_CLASSES = 5
M_VAL = 4000
DOWNSCALE_FACTOR = (1. / 3)
TR_CATS = [4,6,7,8,9]

def crop_and_rescale(im, cr_dim):
    h = im.shape[0]
    w = im.shape[1]
    rescale_factor = float(h) / ( h - (2*cr_dim) )# assuming square input
    if len(im.shape) == 3:
        cr_im = im[cr_dim:(h-cr_dim),cr_dim:(w-cr_dim),:]
        rescaled_im = np.zeros((h,w,3))
        downscaled_im = np.zeros((int(h*DOWNSCALE_FACTOR),int(w*DOWNSCALE_FACTOR),3))
        for c in range(im.shape[2]):
            rescaled_im[:,:,c] = ndimage.interpolation.zoom(cr_im[:,:,c], rescale_factor)
            downscaled_im[:,:,c] = ndimage.interpolation.zoom(rescaled_im[:,:,c], DOWNSCALE_FACTOR)
    else:
        cr_im = im[cr_dim:(h-cr_dim),cr_dim:(w-cr_dim)]
        rescaled_im = ndimage.interpolation.zoom(cr_im, rescale_factor)
        downscaled_im = ndimage.interpolation.zoom(rescaled_im, DOWNSCALE_FACTOR)
    return downscaled_im

def rotate_im(im, degree):
    h = im.shape[0]
    w = im.shape[1]
    # to get the background color simply by taking mean of first row
    if len(im.shape) == 3:
        av_bg_val = np.mean(im[0,0,:])
    else:
        av_bg_val = np.mean(im[0,:])
    rot_im = ndimage.interpolation.rotate(im, degree, reshape=False, mode='constant', cval=av_bg_val)
    if len(im.shape) == 3:
        downscaled_im = np.zeros((int(h*DOWNSCALE_FACTOR),int(w*DOWNSCALE_FACTOR),3))
        for c in range(im.shape[2]):
            downscaled_im[:,:,c] = ndimage.interpolation.zoom(rot_im[:,:,c], DOWNSCALE_FACTOR)
    else:
        downscaled_im = ndimage.interpolation.zoom(rot_im, DOWNSCALE_FACTOR)
    return downscaled_im

def get_val_indices_uniform(m_total, m_val):
    all_idxs = np.arange(m_total)
    samps_per_class = m_val / NUM_CLASSES
    val_idxs = np.array([])
    for i in range(NUM_CLASSES):
        all_class_idxs = all_idxs[( all_idxs % NUM_CLASSES == i)]
        sel_class_idxs = np.random.choice(all_class_idxs, samps_per_class, replace=False)
        val_idxs = np.concatenate((val_idxs,sel_class_idxs))
    np.random.shuffle(val_idxs)
    return val_idxs.astype(np.uint)

def get_val_indices(m_total, m_val, info_mat):
    all_idxs = np.arange(m_total)
    val_idxs = np.array([])
    for i in range(NUM_CLASSES):
        cat_for_val = np.random.choice(TR_CATS,1)[0]
        all_class_idxs = all_idxs[( all_idxs % NUM_CLASSES == i)]
        class_info = info_mat[all_class_idxs]
        sel_class_idxs = np.where(class_info[:,0] == cat_for_val)[0]
        val_idxs = np.concatenate((val_idxs,all_class_idxs[sel_class_idxs]))
    np.random.shuffle(val_idxs)
    return val_idxs.astype(np.uint)

def download_data(data_url, directory='.'):
    file_name = '%s/%s' % (directory, data_url.split('/')[-1])
    if os.path.isfile(file_name):
        return file_name
    try:
        temp_file_name = file_name + '~'
        with open(temp_file_name, "wb") as f:
            print '#######'
            print "Downloading %s" % os.path.basename(file_name)
            start = time.clock()
            response = requests.get(data_url, stream=True)
            total_length = response.headers.get('content-length')

            if total_length is None: # no content length header
                f.write(response.content)
            else:
                dl = 0
                total_length = int(total_length)
                for chunk in response.iter_content(512*1024):
                    dl += len(chunk)
                    f.write(chunk)
                    done = int(50 * dl / total_length)
                    sys.stdout.write("\r[%s%s] %s KBps" % ('=' * done, ' ' * (50-done), dl//(8*1024*(time.clock() - start))))
                    sys.stdout.flush()
            print '\nDone'
        os.rename(temp_file_name, file_name)
    except:
        if os.path.isfile(temp_file_name):
            os.remove(temp_file_name)
        raise

    return file_name

def unarchive_data(file_name, directory='.'):
    # unarchive data and return the list of files
    print 'Unarchiving: %s' % os.path.basename(file_name)
    new_file = '%s/%s' % (directory, os.path.basename(os.path.splitext(file_name)[0]))
    if os.path.isfile(new_file):
        return [new_file]
    contents = [new_file]
    subprocess.check_call(['gzip', '-d', '-k', file_name])
    return contents

class DBWrapper(object):
    @classmethod
    def supported_db_types(cls):
        return [ 'image_data'] # supporting only image_data and not leveldb or lmdb at this stage

    def __init__(self, db_type='image_data'):
        self._db_type = db_type
        self._db = None
        self._txn = None
        if db_type not in DBWrapper.supported_db_types():
            raise Exception('Unsupported db type: ' + db_type)

    def open(self, db_name, mode):
        if self._db is not None:
            raise Exception('DB already open!')
        if mode not in ['r', 'w']:
            raise Exception('Unsupported mode: ' + mode)

        if self._db_type == 'image_data':
            self._db_name = db_name
            self._db_mode = mode
            self._db_index = os.path.join(db_name, 'index.txt')
            if mode == 'r':
                if not os.path.isdir(self._db_name) or not os.path.isfile(self._db_index):
                    raise Exception("DB doesn't exist!")
                with open(self._db_index, 'r') as f:
                    self._index_data = f.read()
            elif mode == 'w':
                try:
                    os.mkdir(self._db_name)
                except:
                    pass
                if os.path.isfile(self._db_index):
                    with open(self._db_index, 'r') as f:
                        self._index_data = f.read()
                else:
                    self._index_data = ''

    def close(self):
        if self._db is not None:
            self._db.close()
    def commit(self):
        if self._txn is not None:
            self._txn.commit()
    def put(self, key, value = 0):
        if self._db_type == 'image_data':

            with open(self._db_index, 'a') as f:
                if len(self._index_data) > 0:
                    self._index_data += '\n'
                    f.write('\n')
                record = '%s %d' % (key, value)
                f.write(record)
                self._index_data += record

def init_worker():
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    np.random.seed(None)

def process_file(params):
    index, data, base_filename, db_name, C, aug_data = params
    label = index % NUM_CLASSES
    if C==1:
        orig_im = data[0,:,:]
        im = ndimage.interpolation.zoom(orig_im, DOWNSCALE_FACTOR)
    elif C==2:
        im = np.zeros((int(MAT_SHAPE[2]*DOWNSCALE_FACTOR),int(MAT_SHAPE[3]*DOWNSCALE_FACTOR),3))
        orig_im = np.zeros((MAT_SHAPE[2],MAT_SHAPE[3],3))
        im[:,:,0] =  ndimage.interpolation.zoom(data[0,:,:], DOWNSCALE_FACTOR)
        im[:,:,1] =  ndimage.interpolation.zoom(data[1,:,:], DOWNSCALE_FACTOR)
        orig_im[:,:,0] =  data[0,:,:]
        orig_im[:,:,1] =  data[1,:,:]
    else:
        print "Error in reading data to db- number of channels must be 1 or 2"
    im_name = '%s_%d%s' % (base_filename, index,IM_FORMAT)
    scipy.misc.toimage(im, cmin=0.0, cmax=255.0).save(os.path.join(db_name,im_name))
    im_names = [im_name]
    if aug_data:
        degrees = [-20, -10, 10, 20]
        crop_dims = [2, 4, 6, 8]
        for i, degree in enumerate(degrees):
            im_name = '%s_%d_%d%s' % (base_filename,index,degree,IM_FORMAT)
            im_names.append(im_name)
            rot_im = rotate_im(orig_im, degree)
            scipy.misc.toimage(rot_im, cmin=0.0, cmax=255.0).save(os.path.join(db_name,im_name))
        for i, crop_dim in enumerate(crop_dims):
            im_name = '%s_%d_%d%s' % (base_filename,index,crop_dim,IM_FORMAT)
            im_names.append(im_name)
            cr_im = crop_and_rescale(orig_im, crop_dim)
            scipy.misc.toimage(cr_im, cmin=0.0, cmax=255.0).save(os.path.join(db_name,im_name))
    return label, im_names

def read_data_to_db(mat_file, mat_shape, indices, db, C=1, aug_data=False):
    pool = Pool(cpu_count() * 2, init_worker)
    base_filename = os.path.basename(db._db_name)
    with open(mat_file[0], 'rb') as f:
        b = f.read()
        data = np.fromstring(b[24:], dtype=np.uint8).reshape(mat_shape)
    results = pool.imap_unordered(process_file,
        [(index, data[index], base_filename, db._db_name, C, aug_data) for index in indices],
        chunksize=10)
    for j, (label, im_names) in enumerate(results):
        sys.stdout.write('\r Generating %d of %d Images' % (j + 1, len(indices)))
        sys.stdout.flush()
        for im_name in im_names:
            db.put(im_name,label)

def create_db( db_path, mat_file, mat_shape, indices, C=1, aug_data=False ):
    if not filter(lambda x: not os.path.isdir(x), [db_path]):
        print '%s already exists' % (db_path)
        return

    try:
        if not os.path.isdir(db_path):
            print 'Creating db at ',db_path
            db = DBWrapper(db_type = 'image_data')
            db.open(db_path, 'w')
            read_data_to_db(mat_file, mat_shape, indices, db, C, aug_data)

        else:
            print '%s already exists' % (db_path)

    except:
        if os.path.isdir(db_path):
            shutil.rmtree(db_path)
        raise
    finally:
        db.commit()
        db.close()

def num_channels(c):
    c = int(c)
    if c not in [1,2]:
        raise ValueError("number of channels must be either 1 or 2")
    return c

if __name__ == '__main__':
    description = ('Script for generating small NORB dataset, with the'
    'options of augmenting the data with scaling and rotation, and the option'
    ' of taking either monocular or binocular image.')
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument(
        "--num_channels",
        help="1 to take only left monocular image, 2 for binocular image."
        " Will be saved in .png format where channel 0,1 are the 2 channels"
        " and third channel is empty.",
        type=num_channels,default=2
    )
    parser.add_argument(
        "--aug_data",
        help="'y' to augment data with rotations in {-20,-10,10,20} degrees "
        " and scaling (up to 15%%)  for each image.",
        type=str,default="n"
    )

    args = parser.parse_args()
    C = args.num_channels
    aug_data = (args.aug_data == "y")
    aug_str = "aug_" if aug_data else ""
    db_type = 'image_data'

    # Paths of datasets
    whole_train_db = os.path.join(SCRIPT_DIR, 'data' , ('%snorb_small_%dD_whole_train_' % (aug_str,C)) + db_type)
    train_db = os.path.join(SCRIPT_DIR, 'data' , ('%snorb_small_%dD_train_' % (aug_str,C)) + db_type)
    validation_db = os.path.join(SCRIPT_DIR, 'data' ,('%snorb_small_%dD_validation_' % (aug_str,C)) + db_type)
    test_db = os.path.join(SCRIPT_DIR, 'data' , ('norb_small_%dD_test_' % (C))+ db_type)
    if not False in [os.path.isdir(db) for db in [whole_train_db, train_db, validation_db, test_db]]:
        print 'All required datasets are present.'
        sys.exit(0)

    print 'Generating databases'
    # Make sure the data directory exists
    try:
        os.mkdir(os.path.join(SCRIPT_DIR, 'data'))
    except:
        pass
    # Download data
    train_img_gz_file = download_data(SM_NORB_TR_DATA, os.path.join(SCRIPT_DIR, 'data'))
    train_label_gz_file = download_data(SM_NORB_TR_LABELS, os.path.join(SCRIPT_DIR, 'data'))
    train_info_gz_file = download_data(SM_NORB_TR_INFO, os.path.join(SCRIPT_DIR, 'data'))
    test_img_gz_file = download_data(SM_NORB_TE_DATA, os.path.join(SCRIPT_DIR, 'data'))
    test_label_gz_file = download_data(SM_NORB_TE_LABELS, os.path.join(SCRIPT_DIR, 'data'))

    train_image_mat_file = unarchive_data(train_img_gz_file, directory=os.path.join(SCRIPT_DIR, 'data'))
    test_image_mat_file = unarchive_data(test_img_gz_file, directory=os.path.join(SCRIPT_DIR, 'data'))

    train_label_mat_file = unarchive_data(train_label_gz_file, directory=os.path.join(SCRIPT_DIR, 'data'))
    test_label_mat_file = unarchive_data(test_label_gz_file, directory=os.path.join(SCRIPT_DIR, 'data'))

    train_info_mat_file = unarchive_data(train_info_gz_file, directory=os.path.join(SCRIPT_DIR, 'data'))[0]

    with open(train_info_mat_file, 'rb') as f:
        b = f.read()
        tr_info = np.fromstring(b[20:], dtype=np.uint32).reshape(24300,4)

    val_idxs = get_val_indices(MAT_SHAPE[0], M_VAL, tr_info)
    train_idxs =  np.setdiff1d(range(MAT_SHAPE[0]), val_idxs)
    np.random.shuffle(train_idxs)
    create_db(validation_db, train_image_mat_file, MAT_SHAPE, val_idxs, C, aug_data)
    create_db(train_db, train_image_mat_file, MAT_SHAPE, train_idxs, C, aug_data)
    create_db(test_db, test_image_mat_file, MAT_SHAPE, np.arange(MAT_SHAPE[0]), C, False)
    create_db(whole_train_db, train_image_mat_file, MAT_SHAPE, np.arange(MAT_SHAPE[0]), C, aug_data)
    print 'Done!'


text:
<?php
/**
 *
 * @author Adelbert D. Silla
 *
 */
namespace HealthCareAbroad\AdvertisementBundle\Form\EventListener;

use HealthCareAbroad\AdvertisementBundle\Form\HighlightFormType;
use HealthCareAbroad\MediaBundle\Entity\Media;

use Doctrine\Common\Collections\ArrayCollection;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AdvertisementPropertyValuesSubscriber implements EventSubscriberInterface
{
    private $factory;
    private $advertisement;

    public function __construct(FormFactoryInterface $factory, $advertisement)
    {
        $this->factory = $factory;
        $this->advertisement = $advertisement;
    }

    public static function getSubscribedEvents()
    {
        return array(FormEvents::POST_SET_DATA => 'postSetData', FormEvents::PRE_BIND => 'preBind');
    }

    /**
     * Transform advertisementPropertyValues form/field type based on advertisementPropertyName
     * Also removes duplicate advertisementPropertyName form/field
     * @param FormEvent $event
     */
    public function postSetData(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        if (null === $data) {
            return;
        }

        $param = $this->advertisement->getInstitution(); // TODO - This param should be dynamic

        foreach($data as $i => $each) {
            $property = $each->getAdvertisementPropertyName();

            if($property->getDataType()->getColumnType() == 'collection' && is_string($each->getValue())) {
                // Remove duplicate advertisementPropertyName form/field
                unset($form[$i]);
            } else {

                // Transform advertisementPropertyValues form/field type based on advertisementPropertyName
                $config = json_decode($property->getPropertyConfig(), true);
                $config['config']['label'] = $property->getLabel();

                $type = $config['isClass'] ? new $config['type']($param) : $config['type'];
                $formField = $this->factory->createNamed('value', $type, null, $config['config']);

                $form->get($i)->add($formField);
            }
        }
    }

    public function preBind(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();
        $mediaClass = get_class(new Media());

        foreach($data as $each) {
            $newData[$each['advertisementPropertyName']] = $each;
        }

        foreach($form->getData() as $i => $each) {
            $property = $each->getAdvertisementPropertyName();
            if(isset($newData[$property->getId()])) {

                if($property->getName() == 'highlights') {
                    foreach($each->getValue() as $i => $highlight) {

                        if(!empty($highlight) && isset($newData[$property->getId()]['value']) && isset($newData[$property->getId()]['value'][$i]) && is_null($newData[$property->getId()]['value'][$i]['icon']) && is_object($highlight['icon']) && get_class($highlight['icon']) == $mediaClass) {
                            $newData[$property->getId()]['value'][$i]['icon'] = $highlight['icon'];
                        }
                    }
                }

                if($property->getName() == 'media_id' && isset($newData[$property->getId()]['value']) && is_null($newData[$property->getId()]['value']) && get_class($each->getValue()) == $mediaClass) {
                    //$newData[$property->getId()]['value'] = $each->getValue()->getId() ? $each->getValue() : '';
                    $newData[$property->getId()]['value'] = $each->getValue();
                }
            }
        }

        $event->setData(array_values($newData));
    }
}


text:
/* eslint-disable complexity, semi, no-param-reassign, no-magic-numbers, require-jsdoc, curly, wrap-regex, eqeqeq,
    new-cap, no-multi-spaces, no-bitwise, no-extra-parens */
// modified for cms purposes - event names, parent resolutions, class names
import $ from 'jquery';

// DROPDOWN CLASS DEFINITION
// =========================

var backdrop = '.cms-dropdown-backdrop';
var toggle = '.cms-dropdown-toggle';
var Dropdown = function (element) {
    $(element).on('click.cms.dropdown', this.toggle);
};

function getParent($this) {
    return $this.closest('.cms-dropdown');
}

function clearMenus(e) {
    if (e && e.which === 3) return;
    $(backdrop).remove();
    $(toggle).each(function () {
        var $this = $(this)
        var $parent = getParent($this)
        var relatedTarget = { relatedTarget: this };

        if (!$parent.hasClass('cms-dropdown-open')) return;

        if (e && e.type == 'click' && (/input|textarea/i).test(e.target.tagName) && $.contains($parent[0], e.target)) {
            return;
        }

        $parent.trigger(e = $.Event('hide.cms.dropdown', relatedTarget))

        if (e.isDefaultPrevented()) {
            return;
        }

        $this.attr('aria-expanded', 'false')
        $parent.removeClass('cms-dropdown-open').trigger($.Event('hidden.cms.dropdown', relatedTarget))
    })
}

Dropdown.prototype.toggle = function (e) {
    var $this = $(this)

    if ($this.is('.cms-btn-disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('cms-dropdown-open')

    clearMenus()

    if (!isActive) {
        if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
            // if mobile we use a backdrop because click events don't delegate
            $(document.createElement('div'))
                .addClass('cms-dropdown-backdrop')
                .insertAfter($(this))
                .on('click', clearMenus)
        }

        var relatedTarget = { relatedTarget: this }

        $parent.trigger(e = $.Event('show.cms.dropdown', relatedTarget))

        if (e.isDefaultPrevented()) return

        $this
            .trigger('focus')
            .attr('aria-expanded', 'true')

        $parent
            .toggleClass('cms-dropdown-open')
            .trigger($.Event('shown.cms.dropdown', relatedTarget))
    }

    return false
}

Dropdown.prototype.keydown = function (e) {
    if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return

    var $this = $(this)

    e.preventDefault()
    e.stopPropagation()

    if ($this.is('.cms-btn-disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('cms-dropdown-open')

    if (!isActive && e.which != 27 || isActive && e.which == 27) {
        if (e.which == 27) $parent.find(toggle).trigger('focus')
        return $this.trigger('click')
    }

    var desc = ' li:not(.cms-btn-disabled):visible a'
    var $items = $parent.find('.cms-dropdown-menu' + desc)

    if (!$items.length) return

    var index = $items.index(e.target)

    if (e.which == 38 && index > 0)                 index--         // up
    if (e.which == 40 && index < $items.length - 1) index++         // down
    if (!~index)                                    index = 0

    $items.eq(index).trigger('focus')
}

// DROPDOWN PLUGIN DEFINITION
// ==========================

function Plugin(option) {
    return this.each(function () {
        var $this = $(this)
        var data  = $this.data('cms.dropdown')

        if (!data) $this.data('cms.dropdown', (data = new Dropdown(this)))
        if (typeof option == 'string') data[option].call($this)
    })
}

var old = $.fn.dropdown

$.fn.dropdown             = Plugin
$.fn.dropdown.Constructor = Dropdown

// DROPDOWN NO CONFLICT
// ====================

$.fn.dropdown.noConflict = function () {
    $.fn.dropdown = old
    return this
}

$(function () {
    $(document)
        .on('click.cms.dropdown.data-api', clearMenus)
        .on('click.cms.dropdown.data-api', '.cms-dropdown form', function (e) {
            e.stopPropagation()
        })
        .on('pointerup.cms.dropdown.data-api', toggle, Dropdown.prototype.toggle)
        .on('keydown.cms.dropdown.data-api', toggle, Dropdown.prototype.keydown)
        .on('keydown.cms.dropdown.data-api', '.cms-dropdown-menu', Dropdown.prototype.keydown)
})


text:
/*
 * proto/v1beta1/grafeas.proto
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * API version: version not set
 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
 */

package grafeas
// DeploymentPlatform : Types of platforms.   - PLATFORM_UNSPECIFIED: Unknown.  - GKE: Google Container Engine.  - FLEX: Google App Engine: Flexible Environment.  - CUSTOM: Custom user-defined platform.
type DeploymentPlatform string

// List of DeploymentPlatform
const (
	PLATFORM_UNSPECIFIED_DeploymentPlatform DeploymentPlatform = "PLATFORM_UNSPECIFIED"
	GKE_DeploymentPlatform DeploymentPlatform = "GKE"
	FLEX_DeploymentPlatform DeploymentPlatform = "FLEX"
	CUSTOM_DeploymentPlatform DeploymentPlatform = "CUSTOM"
)


text:
using System.Data.Entity;
using System.Management.Automation;
using InsanelySimpleBlog.DataModel;

namespace InsanelySimpleBlog.PowerShell
{
    [Cmdlet(VerbsCommon.New, "Deployment")]
    public class NewDeployment : AbstractDatabaseCmdlet
    {
        [Parameter(Mandatory = true, HelpMessage = "The name of the default author")]
        public string Author { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The title of the blog")]
        public string BlogName { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The URL of the page that hosts the blog")]
        public string BlogPageUrl { get; set; }

        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            using (SimpleBlogDbContext context = new SimpleBlogDbContext(GetConnectionString()))
            {
                CreateDatabaseIfNotExists<SimpleBlogDbContext> databaseInitializer = new CreateDatabaseIfNotExists<SimpleBlogDbContext>();
                databaseInitializer.InitializeDatabase(context);

                Author author = new Author
                                    {
                                        Name = Author
                                    };
                context.Authors.Add(author);

                Settings settings = new Settings
                                        {
                                            BlogPageUrl = BlogPageUrl,
                                            Name = BlogName
                                        };
                context.Settings.Add(settings);

                context.SaveChanges();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/menu_top" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical" >

        <ListView
            android:id="@+id/list_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>

    <include layout="@layout/menu_bottom" />

</LinearLayout>


text:
package com.amazonaws.services.alexaforbusiness.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.alexaforbusiness.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * DeleteUserRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteUserRequestMarshaller {

    private static final MarshallingInfo<String> USERARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("UserArn").build();
    private static final MarshallingInfo<String> ENROLLMENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EnrollmentId").build();

    private static final DeleteUserRequestMarshaller instance = new DeleteUserRequestMarshaller();

    public static DeleteUserRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(DeleteUserRequest deleteUserRequest, ProtocolMarshaller protocolMarshaller) {

        if (deleteUserRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(deleteUserRequest.getUserArn(), USERARN_BINDING);
            protocolMarshaller.marshall(deleteUserRequest.getEnrollmentId(), ENROLLMENTID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
class User
  def admin?
    true
  end
end

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def current_user
    User.new
  end

end


text:
using Voxalia.Shared;
using Voxalia.ClientGame.WorldSystem;
using System.Threading;

namespace Voxalia.ClientGame.NetworkSystem.PacketsIn
{
    public class OperationStatusPacketIn: AbstractPacketIn
    {
        public int ChunksStillLoading()
        {
            int c = 0;
            foreach (Chunk chunk in TheClient.TheRegion.LoadedChunks.Values)
            {
                if (chunk.LOADING)
                {
                    c++;
                }
            }
            return c;
        }

        public override bool ParseBytesAndExecute(byte[] data)
        {
            if (data.Length != 2)
            {
                return false;
            }
            switch ((StatusOperation)data[0])
            {
                default:
                    return false;
            }
        }
    }
}