text:
(function() {

function defineCommonExtensionSymbols(apiPrivate)
{
    if (!apiPrivate.audits)
        apiPrivate.audits = {};

    apiPrivate.audits.Severity = {
        Info: "info",
        Warning: "warning",
        Severe: "severe"
    };

    if (!apiPrivate.console)
        apiPrivate.console = {};
    apiPrivate.console.Severity = {
        Tip: "tip",
        Debug: "debug",
        Log: "log",
        Warning: "warning",
        Error: "error"
    };
    apiPrivate.Events = {
        AuditStarted: "audit-started-",
        ButtonClicked: "button-clicked-",
        ConsoleMessageAdded: "console-message-added",
        ElementsPanelObjectSelected: "panel-objectSelected-elements",
        NetworkRequestFinished: "network-request-finished",
        Reset: "reset",
        OpenResource: "open-resource",
        PanelSearch: "panel-search-",
        Reload: "Reload",
        ResourceAdded: "resource-added",
        ResourceContentCommitted: "resource-content-committed",
        TimelineEventRecorded: "timeline-event-recorded",
        ViewShown: "view-shown-",
        ViewHidden: "view-hidden-"
    };
    apiPrivate.Commands = {
        AddAuditCategory: "addAuditCategory",
        AddAuditResult: "addAuditResult",
        AddConsoleMessage: "addConsoleMessage",
        AddRequestHeaders: "addRequestHeaders",
        CreatePanel: "createPanel",
        CreateSidebarPane: "createSidebarPane",
        CreateStatusBarButton: "createStatusBarButton",
        EvaluateOnInspectedPage: "evaluateOnInspectedPage",
        GetConsoleMessages: "getConsoleMessages",
        GetHAR: "getHAR",
        GetPageResources: "getPageResources",
        GetRequestContent: "getRequestContent",
        GetResourceContent: "getResourceContent",
        Subscribe: "subscribe",
        SetOpenResourceHandler: "setOpenResourceHandler",
        SetResourceContent: "setResourceContent",
        SetSidebarContent: "setSidebarContent",
        SetSidebarHeight: "setSidebarHeight",
        SetSidebarPage: "setSidebarPage",
        StopAuditCategoryRun: "stopAuditCategoryRun",
        Unsubscribe: "unsubscribe",
        UpdateButton: "updateButton",
        InspectedURLChanged: "inspectedURLChanged"
    };
}

function injectedExtensionAPI(injectedScriptId)
{

var apiPrivate = {};

defineCommonExtensionSymbols(apiPrivate);

var commands = apiPrivate.Commands;
var events = apiPrivate.Events;

// Here and below, all constructors are private to API implementation.
// For a public type Foo, if internal fields are present, these are on
// a private FooImpl type, an instance of FooImpl is used in a closure
// by Foo consutrctor to re-bind publicly exported members to an instance
// of Foo.

/**
 * @constructor
 */
function EventSinkImpl(type, customDispatch)
{
    this._type = type;
    this._listeners = [];
    this._customDispatch = customDispatch;
}

EventSinkImpl.prototype = {
    addListener: function(callback)
    {
        if (typeof callback !== "function")
            throw "addListener: callback is not a function";
        if (this._listeners.length === 0)
            extensionServer.sendRequest({ command: commands.Subscribe, type: this._type });
        this._listeners.push(callback);
        extensionServer.registerHandler("notify-" + this._type, this._dispatch.bind(this));
    },

    removeListener: function(callback)
    {
        var listeners = this._listeners;

        for (var i = 0; i < listeners.length; ++i) {
            if (listeners[i] === callback) {
                listeners.splice(i, 1);
                break;
            }
        }
        if (this._listeners.length === 0)
            extensionServer.sendRequest({ command: commands.Unsubscribe, type: this._type });
    },

    _fire: function()
    {
        var listeners = this._listeners.slice();
        for (var i = 0; i < listeners.length; ++i)
            listeners[i].apply(null, arguments);
    },

    _dispatch: function(request)
    {
         if (this._customDispatch)
             this._customDispatch.call(this, request);
         else
             this._fire.apply(this, request.arguments);
    }
}

/**
 * @constructor
 */
function InspectorExtensionAPI()
{
    this.audits = new Audits();
    this.inspectedWindow = new InspectedWindow();
    this.panels = new Panels();
    this.network = new Network();
    defineDeprecatedProperty(this, "webInspector", "resources", "network");
    this.timeline = new Timeline();
    this.console = new ConsoleAPI();

    this.onReset = new EventSink(events.Reset);
}

/**
 * @constructor
 */
InspectorExtensionAPI.prototype = {
    log: function(message)
    {
        extensionServer.sendRequest({ command: commands.Log, message: message });
    }
}

/**
 * @constructor
 */
function ConsoleAPI()
{
    this.onMessageAdded = new EventSink(events.ConsoleMessageAdded);
}

ConsoleAPI.prototype = {
    getMessages: function(callback)
    {
        extensionServer.sendRequest({ command: commands.GetConsoleMessages }, callback);
    },

    addMessage: function(severity, text, url, line)
    {
        extensionServer.sendRequest({ command: commands.AddConsoleMessage, severity: severity, text: text, url: url, line: line });
    },

    get Severity()
    {
        return apiPrivate.console.Severity;
    }
}

/**
 * @constructor
 */
function Network()
{
    function dispatchRequestEvent(message)
    {
        var request = message.arguments[1];
        request.__proto__ = new Request(message.arguments[0]);
        this._fire(request);
    }
    this.onRequestFinished = new EventSink(events.NetworkRequestFinished, dispatchRequestEvent);
    defineDeprecatedProperty(this, "network", "onFinished", "onRequestFinished");
    this.onNavigated = new EventSink(events.InspectedURLChanged);
}

Network.prototype = {
    getHAR: function(callback)
    {
        function callbackWrapper(result)
        {
            var entries = (result && result.entries) || [];
            for (var i = 0; i < entries.length; ++i) {
                entries[i].__proto__ = new Request(entries[i]._requestId);
                delete entries[i]._requestId;
            }
            callback(result);
        }
        return extensionServer.sendRequest({ command: commands.GetHAR }, callback && callbackWrapper);
    },

    addRequestHeaders: function(headers)
    {
        return extensionServer.sendRequest({ command: commands.AddRequestHeaders, headers: headers, extensionId: window.location.hostname });
    }
}

/**
 * @constructor
 */
function RequestImpl(id)
{
    this._id = id;
}

RequestImpl.prototype = {
    getContent: function(callback)
    {
        function callbackWrapper(response)
        {
            callback(response.content, response.encoding);
        }
        extensionServer.sendRequest({ command: commands.GetRequestContent, id: this._id }, callback && callbackWrapper);
    }
}

/**
 * @constructor
 */
function Panels()
{
    var panels = {
        elements: new ElementsPanel()
    };

    function panelGetter(name)
    {
        return panels[name];
    }
    for (var panel in panels)
        this.__defineGetter__(panel, panelGetter.bind(null, panel));
}

Panels.prototype = {
    create: function(title, icon, page, callback)
    {
        var id = "extension-panel-" + extensionServer.nextObjectId();
        var request = {
            command: commands.CreatePanel,
            id: id,
            title: title,
            icon: icon,
            page: page
        };
        extensionServer.sendRequest(request, callback && callback.bind(this, new ExtensionPanel(id)));
    },

    setOpenResourceHandler: function(callback)
    {
        var hadHandler = extensionServer.hasHandler(events.OpenResource);

        if (!callback)
            extensionServer.unregisterHandler(events.OpenResource);
        else {
            function callbackWrapper(message)
            {
                callback.call(null, message.resource, message.lineNumber);
            }
            extensionServer.registerHandler(events.OpenResource, callbackWrapper);
        }
        // Only send command if we either removed an existing handler or added handler and had none before.
        if (hadHandler === !callback)
            extensionServer.sendRequest({ command: commands.SetOpenResourceHandler, "handlerPresent": !!callback });
    }
}

/**
 * @constructor
 */
function ExtensionViewImpl(id)
{
    this._id = id;

    function dispatchShowEvent(message)
    {
        var frameIndex = message.arguments[0];
        this._fire(window.top.frames[frameIndex]);
    }
    this.onShown = new EventSink(events.ViewShown + id, dispatchShowEvent);
    this.onHidden = new EventSink(events.ViewHidden + id);
}

/**
 * @constructor
 */
function PanelWithSidebarImpl(id)
{
    this._id = id;
}

PanelWithSidebarImpl.prototype = {
    createSidebarPane: function(title, callback)
    {
        var id = "extension-sidebar-" + extensionServer.nextObjectId();
        var request = {
            command: commands.CreateSidebarPane,
            panel: this._id,
            id: id,
            title: title
        };
        function callbackWrapper()
        {
            callback(new ExtensionSidebarPane(id));
        }
        extensionServer.sendRequest(request, callback && callbackWrapper);
    }
}

PanelWithSidebarImpl.prototype.__proto__ = ExtensionViewImpl.prototype;

/**
 * @constructor
 * @extends {PanelWithSidebar}
 */
function ElementsPanel()
{
    var id = "elements";
    PanelWithSidebar.call(this, id);
    this.onSelectionChanged = new EventSink(events.ElementsPanelObjectSelected);
}

/**
 * @constructor
 * @extends {ExtensionViewImpl}
 */
function ExtensionPanelImpl(id)
{
    ExtensionViewImpl.call(this, id);
    this.onSearch = new EventSink(events.PanelSearch + id);
}

ExtensionPanelImpl.prototype = {
    createStatusBarButton: function(iconPath, tooltipText, disabled)
    {
        var id = "button-" + extensionServer.nextObjectId();
        var request = {
            command: commands.CreateStatusBarButton,
            panel: this._id,
            id: id,
            icon: iconPath,
            tooltip: tooltipText,
            disabled: !!disabled
        };
        extensionServer.sendRequest(request);
        return new Button(id);
    }
};

ExtensionPanelImpl.prototype.__proto__ = ExtensionViewImpl.prototype;

/**
 * @constructor
 * @extends {ExtensionViewImpl}
 */
function ExtensionSidebarPaneImpl(id)
{
    ExtensionViewImpl.call(this, id);
}

ExtensionSidebarPaneImpl.prototype = {
    setHeight: function(height)
    {
        extensionServer.sendRequest({ command: commands.SetSidebarHeight, id: this._id, height: height });
    },

    setExpression: function(expression, rootTitle, evaluateOptions)
    {
        var callback = extractCallbackArgument(arguments);
        var request = {
            command: commands.SetSidebarContent,
            id: this._id,
            expression: expression,
            rootTitle: rootTitle,
            evaluateOnPage: true,
        };
        if (typeof evaluateOptions === "object")
            request.evaluateOptions = evaluateOptions;
        extensionServer.sendRequest(request, callback);
    },

    setObject: function(jsonObject, rootTitle, callback)
    {
        extensionServer.sendRequest({ command: commands.SetSidebarContent, id: this._id, expression: jsonObject, rootTitle: rootTitle }, callback);
    },

    setPage: function(page)
    {
        extensionServer.sendRequest({ command: commands.SetSidebarPage, id: this._id, page: page });
    }
}

/**
 * @constructor
 */
function ButtonImpl(id)
{
    this._id = id;
    this.onClicked = new EventSink(events.ButtonClicked + id);
}

ButtonImpl.prototype = {
    update: function(iconPath, tooltipText, disabled)
    {
        var request = {
            command: commands.UpdateButton,
            id: this._id,
            icon: iconPath,
            tooltip: tooltipText,
            disabled: !!disabled
        };
        extensionServer.sendRequest(request);
    }
};

/**
 * @constructor
 */
function Audits()
{
}

Audits.prototype = {
    addCategory: function(displayName, resultCount)
    {
        var id = "extension-audit-category-" + extensionServer.nextObjectId();
        extensionServer.sendRequest({ command: commands.AddAuditCategory, id: id, displayName: displayName, resultCount: resultCount });
        return new AuditCategory(id);
    }
}

/**
 * @constructor
 */
function AuditCategoryImpl(id)
{
    function dispatchAuditEvent(request)
    {
        var auditResult = new AuditResult(request.arguments[0]);
        try {
            this._fire(auditResult);
        } catch (e) {
            console.error("Uncaught exception in extension audit event handler: " + e);
            auditResult.done();
        }
    }
    this._id = id;
    this.onAuditStarted = new EventSink(events.AuditStarted + id, dispatchAuditEvent);
}

/**
 * @constructor
 */
function AuditResultImpl(id)
{
    this._id = id;

    this.createURL = this._nodeFactory.bind(null, "url");
    this.createSnippet = this._nodeFactory.bind(null, "snippet");
    this.createText = this._nodeFactory.bind(null, "text");
    this.createObject = this._nodeFactory.bind(null, "object");
    this.createNode = this._nodeFactory.bind(null, "node");
}

AuditResultImpl.prototype = {
    addResult: function(displayName, description, severity, details)
    {
        // shorthand for specifying details directly in addResult().
        if (details && !(details instanceof AuditResultNode))
            details = new AuditResultNode(details instanceof Array ? details : [details]);

        var request = {
            command: commands.AddAuditResult,
            resultId: this._id,
            displayName: displayName,
            description: description,
            severity: severity,
            details: details
        };
        extensionServer.sendRequest(request);
    },

    createResult: function()
    {
        return new AuditResultNode(Array.prototype.slice.call(arguments));
    },

    done: function()
    {
        extensionServer.sendRequest({ command: commands.StopAuditCategoryRun, resultId: this._id });
    },

    get Severity()
    {
        return apiPrivate.audits.Severity;
    },

    createResourceLink: function(url, lineNumber)
    {
        return {
            type: "resourceLink",
            arguments: [url, lineNumber && lineNumber - 1]
        };
    },

    _nodeFactory: function(type)
    {
        return {
            type: type,
            arguments: Array.prototype.slice.call(arguments, 1)
        };
    }
}

/**
 * @constructor
 */
function AuditResultNode(contents)
{
    this.contents = contents;
    this.children = [];
    this.expanded = false;
}

AuditResultNode.prototype = {
    addChild: function()
    {
        var node = new AuditResultNode(Array.prototype.slice.call(arguments));
        this.children.push(node);
        return node;
    }
};

/**
 * @constructor
 */
function InspectedWindow()
{
    function dispatchResourceEvent(message)
    {
        this._fire(new Resource(message.arguments[0]));
    }
    function dispatchResourceContentEvent(message)
    {
        this._fire(new Resource(message.arguments[0]), message.arguments[1]);
    }
    this.onResourceAdded = new EventSink(events.ResourceAdded, dispatchResourceEvent);
    this.onResourceContentCommitted = new EventSink(events.ResourceContentCommitted, dispatchResourceContentEvent);
}

InspectedWindow.prototype = {
    reload: function(optionsOrUserAgent)
    {
        var options = null;
        if (typeof optionsOrUserAgent === "object")
            options = optionsOrUserAgent;
        else if (typeof optionsOrUserAgent === "string") {
            options = { userAgent: optionsOrUserAgent };
            console.warn("Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. " +
                         "Use inspectedWindow.reload({ userAgent: value}) instead.");
        }
        return extensionServer.sendRequest({ command: commands.Reload, options: options });
    },

    eval: function(expression, evaluateOptions)
    {
        var callback = extractCallbackArgument(arguments);
        function callbackWrapper(result)
        {
            callback(result.value, result.isException);
        }
        var request = {
            command: commands.EvaluateOnInspectedPage,
            expression: expression
        };
        if (typeof evaluateOptions === "object")
            request.evaluateOptions = evaluateOptions;
        return extensionServer.sendRequest(request, callback && callbackWrapper);
    },

    getResources: function(callback)
    {
        function wrapResource(resourceData)
        {
            return new Resource(resourceData);
        }
        function callbackWrapper(resources)
        {
            callback(resources.map(wrapResource));
        }
        return extensionServer.sendRequest({ command: commands.GetPageResources }, callback && callbackWrapper);
    }
}

/**
 * @constructor
 */
function ResourceImpl(resourceData)
{
    this._url = resourceData.url
    this._type = resourceData.type;
}

ResourceImpl.prototype = {
    get url()
    {
        return this._url;
    },

    get type()
    {
        return this._type;
    },

    getContent: function(callback)
    {
        function callbackWrapper(response)
        {
            callback(response.content, response.encoding);
        }

        return extensionServer.sendRequest({ command: commands.GetResourceContent, url: this._url }, callback && callbackWrapper);
    },

    setContent: function(content, commit, callback)
    {
        return extensionServer.sendRequest({ command: commands.SetResourceContent, url: this._url, content: content, commit: commit }, callback);
    }
}

/**
 * @constructor
 */
function TimelineImpl()
{
    this.onEventRecorded = new EventSink(events.TimelineEventRecorded);
}

/**
 * @constructor
 */
function ExtensionServerClient()
{
    this._callbacks = {};
    this._handlers = {};
    this._lastRequestId = 0;
    this._lastObjectId = 0;

    this.registerHandler("callback", this._onCallback.bind(this));

    var channel = new MessageChannel();
    this._port = channel.port1;
    this._port.addEventListener("message", this._onMessage.bind(this), false);
    this._port.start();

    top.postMessage("registerExtension", [ channel.port2 ], "*");
}

ExtensionServerClient.prototype = {
    sendRequest: function(message, callback)
    {
        if (typeof callback === "function")
            message.requestId = this._registerCallback(callback);
        return this._port.postMessage(message);
    },

    hasHandler: function(command)
    {
        return !!this._handlers[command];
    },

    registerHandler: function(command, handler)
    {
        this._handlers[command] = handler;
    },

    unregisterHandler: function(command)
    {
        delete this._handlers[command];
    },

    nextObjectId: function()
    {
        return injectedScriptId + "_" + ++this._lastObjectId;
    },

    _registerCallback: function(callback)
    {
        var id = ++this._lastRequestId;
        this._callbacks[id] = callback;
        return id;
    },

    _onCallback: function(request)
    {
        if (request.requestId in this._callbacks) {
            var callback = this._callbacks[request.requestId];
            delete this._callbacks[request.requestId];
            callback(request.result);
        }
    },

    _onMessage: function(event)
    {
        var request = event.data;
        var handler = this._handlers[request.command];
        if (handler)
            handler.call(this, request);
    }
}

function populateInterfaceClass(interface, implementation)
{
    for (var member in implementation) {
        if (member.charAt(0) === "_")
            continue;
        var descriptor = null;
        // Traverse prototype chain until we find the owner.
        for (var owner = implementation; owner && !descriptor; owner = owner.__proto__)
            descriptor = Object.getOwnPropertyDescriptor(owner, member);
        if (!descriptor)
            continue;
        if (typeof descriptor.value === "function")
            interface[member] = descriptor.value.bind(implementation);
        else if (typeof descriptor.get === "function")
            interface.__defineGetter__(member, descriptor.get.bind(implementation));
        else
            Object.defineProperty(interface, member, descriptor);
    }
}

function declareInterfaceClass(implConstructor)
{
    return function()
    {
        var impl = { __proto__: implConstructor.prototype };
        implConstructor.apply(impl, arguments);
        populateInterfaceClass(this, impl);
    }
}

function defineDeprecatedProperty(object, className, oldName, newName)
{
    var warningGiven = false;
    function getter()
    {
        if (!warningGiven) {
            console.warn(className + "." + oldName + " is deprecated. Use " + className + "." + newName + " instead");
            warningGiven = true;
        }
        return object[newName];
    }
    object.__defineGetter__(oldName, getter);
}

function extractCallbackArgument(args)
{
    var lastArgument = args[args.length - 1];
    return typeof lastArgument === "function" ? lastArgument : undefined;
}

var AuditCategory = declareInterfaceClass(AuditCategoryImpl);
var AuditResult = declareInterfaceClass(AuditResultImpl);
var Button = declareInterfaceClass(ButtonImpl);
var EventSink = declareInterfaceClass(EventSinkImpl);
var ExtensionPanel = declareInterfaceClass(ExtensionPanelImpl);
var ExtensionSidebarPane = declareInterfaceClass(ExtensionSidebarPaneImpl);
var PanelWithSidebar = declareInterfaceClass(PanelWithSidebarImpl);
var Request = declareInterfaceClass(RequestImpl);
var Resource = declareInterfaceClass(ResourceImpl);
var Timeline = declareInterfaceClass(TimelineImpl);

var extensionServer = new ExtensionServerClient();

return new InspectorExtensionAPI();
}

// Default implementation; platforms will override.
function buildPlatformExtensionAPI(extensionInfo)
{
    function platformExtensionAPI(coreAPI)
    {
        window.webInspector = coreAPI;
    }
    return platformExtensionAPI.toString();
}

function buildExtensionAPIInjectedScript(extensionInfo)
{
    return "(function(injectedScriptHost, inspectedWindow, injectedScriptId){ " +
        defineCommonExtensionSymbols.toString() + ";" +
        injectedExtensionAPI.toString() + ";" +
        buildPlatformExtensionAPI(extensionInfo) + ";" +
        "platformExtensionAPI(injectedExtensionAPI(injectedScriptId));" +
        "return {};" +
        "})";
}
/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

function platformExtensionAPI(coreAPI)
{
    function getTabId()
    {
        return tabId;
    }
    chrome = window.chrome || {};
    // Override chrome.devtools as a workaround for a error-throwing getter being exposed
    // in extension pages loaded into a non-extension process (only happens for remote client
    // extensions)
    var devtools_descriptor = Object.getOwnPropertyDescriptor(chrome, "devtools");
    if (!devtools_descriptor || devtools_descriptor.get)
        Object.defineProperty(chrome, "devtools", { value: {}, enumerable: true });
    // Only expose tabId on chrome.devtools.inspectedWindow, not webInspector.inspectedWindow.
    chrome.devtools.inspectedWindow = {};
    chrome.devtools.inspectedWindow.__defineGetter__("tabId", getTabId);
    chrome.devtools.inspectedWindow.__proto__ = coreAPI.inspectedWindow;
    chrome.devtools.network = coreAPI.network;
    chrome.devtools.panels = coreAPI.panels;

    // default to expose experimental APIs for now.
    if (extensionInfo.exposeExperimentalAPIs !== false) {
        chrome.experimental = chrome.experimental || {};
        chrome.experimental.devtools = chrome.experimental.devtools || {};

        var properties = Object.getOwnPropertyNames(coreAPI);
        for (var i = 0; i < properties.length; ++i) {
            var descriptor = Object.getOwnPropertyDescriptor(coreAPI, properties[i]);
            Object.defineProperty(chrome.experimental.devtools, properties[i], descriptor);
        }
        chrome.experimental.devtools.inspectedWindow = chrome.devtools.inspectedWindow;
    }
    if (extensionInfo.exposeWebInspectorNamespace)
        window.webInspector = coreAPI;
}

        var tabId;
        var extensionInfo = {};
        platformExtensionAPI(injectedExtensionAPI("remote-" + top.frames.length));
    })();


text:
/* ============================================================
 * Control compile time options.
 *
 * Largely, these are options that are designed to make mosquitto run more
 * easily in restrictive environments by removing features.
 * ============================================================ */

/* Uncomment to compile with tcpd/libwrap support. */
//#define WITH_WRAP

/* Compile with database upgrading support? If disabled, mosquitto won't
 * automatically upgrade old database versions. */
//#define WITH_DB_UPGRADE

/* Compile with memory tracking support? If disabled, mosquitto won't track
 * heap memory usage nor export '$SYS/broker/heap/current size', but will use
 * slightly less memory and CPU time. */
#define WITH_MEMORY_TRACKING

/* Compile with the ability to upgrade from old style sqlite persistent
 * databases to the new mosquitto format. This means a dependency on sqlite. It
 * isn't needed for new installations.
 * Not available on Windows.
 */
#ifndef WIN32
#define WITH_SQLITE_UPGRADE
#endif

/* Compile with persistent database support. This allows the broker to store
 * retained messages and durable subscriptions to a file periodically and on
 * shutdown. This is usually desirable (and is suggested by the MQTT spec), but
 * it can be disabled by commenting out this define if required.
 * Not available on Windows.
 */
#ifndef WIN32
#define WITH_PERSISTENCE
#endif

/* Compile with 32-bit integer database IDs instead of 64-bit integers. May be
 * useful in embedded systems or where be64toh()/htobe64() aren't available.
 * There is the potential for bad things to happen after the IDs wrap around.
 * This is especially likely if there are old retained messages. Note that at a
 * sustained rate of 10,000 messages/s, the database ID would overflow every 5
 * days. It is also worth noting that a broker compiled with 64-bit DB IDs will
 * not load a persistent database file saved from a 32-bit DB ID broker and
 * vice versa.
 */
//#define WITH_32BIT_DBID

/* ============================================================
 * Compatibility defines
 *
 * Generally for Windows native support.
 * ============================================================ */
#ifdef WIN32
#define snprintf sprintf_s
#define strcasecmp strcmpi
#endif

redpajama_set_name: RedPajamaGithub


text:
package com.braintreegateway.integrationtest;

import com.braintreegateway.Plan;
import com.braintreegateway.util.NodeWrapperFactory;

public class PlanFixture {
    public static final Plan PLAN_WITHOUT_TRIAL = new Plan(NodeWrapperFactory.instance.create(
                "<plan>" +
                "<billing-day-of-month>1</billing-day-of-month>" +
                "<billing-frequency>1</billing-frequency>" +
                "<currency-iso-code>USD</currency-iso-code>" +
                "<description>java test plan</description>" +
                "<id>integration_trialless_plan</id>" +
                "<name>Plan for integration tests -- without a trial</name>" +
                "<number-of-billing-cycles>12</number-of-billing-cycles>" +
                "<price>12.34</price>" +
                "<trial-duration>1</trial-duration>" +
                "<trial-duration-unit>day</trial-duration-unit>" +
                "<trial-period>false</trial-period>" +
                "</plan>"));

    public static final Plan PLAN_WITH_TRIAL = new Plan(NodeWrapperFactory.instance.create(
                "<plan>" +
                "<billing-day-of-month>1</billing-day-of-month>" +
                "<billing-frequency>2</billing-frequency>" +
                "<currency-iso-code>USD</currency-iso-code>" +
                "<description>java test plan</description>" +
                "<id>integration_trial_plan</id>" +
                "<name>Plan for integration tests -- with a trial</name>" +
                "<number-of-billing-cycles>12</number-of-billing-cycles>" +
                "<price>43.21</price>" +
                "<trial-duration>2</trial-duration>" +
                "<trial-duration-unit>day</trial-duration-unit>" +
                "<trial-period>true</trial-period>" +
                "</plan>"));

    public static final Plan BILLING_DAY_OF_MONTH_PLAN = new Plan(NodeWrapperFactory.instance.create(
                "<plan>" +
                "<billing-day-of-month>1</billing-day-of-month>" +
                "<billing-frequency>2</billing-frequency>" +
                "<currency-iso-code>USD</currency-iso-code>" +
                "<description>java test plan</description>" +
                "<id>integration_plan_with_billing_day_of_month</id>" +
                "<name>Plan for integration tests -- with billing day of month</name>" +
                "<number-of-billing-cycles>12</number-of-billing-cycles>" +
                "<price>8.88</price>" +
                "<trial-duration>1</trial-duration>" +
                "<trial-duration-unit>day</trial-duration-unit>" +
                "<trial-period>false</trial-period>" +
                "</plan>"));

    public static final Plan ADD_ON_DISCOUNT_PLAN = new Plan(NodeWrapperFactory.instance.create(
                "<plan>" +
                "<billing-day-of-month>1</billing-day-of-month>" +
                "<billing-frequency>2</billing-frequency>" +
                "<currency-iso-code>USD</currency-iso-code>" +
                "<description>java test plan</description>" +
                "<id>integration_plan_with_add_ons_and_discounts</id>" +
                "<name>Plan for integration tests -- with add-ons and discounts</name>" +
                "<number-of-billing-cycles>12</number-of-billing-cycles>" +
                "<price>9.99</price>" +
                "<trial-duration>1</trial-duration>" +
                "<trial-duration-unit>day</trial-duration-unit>" +
                "<trial-period>true</trial-period>" +
                "</plan>"));
}


text:
/*
Problem 11. Prefix "test"

Write a program that deletes from a text file all words that start with the prefix test.
Words contain only the symbols 0…9, a…z, A…Z, _.
 */

using System;
using System.IO;
using System.Text.RegularExpressions;
class RemovePrefix
{
    static void Main()
    {
        string file = @"..\..\file.txt";
        string output = @"..\..\output.txt";

        Regex regex = new Regex(@"\btest[\w\d]*");
        string line = null;

        try
        {
            StreamReader reader = new StreamReader(file);
            using (reader)
            {
                line = reader.ReadToEnd();
                line = regex.Replace(line, "");
            }
            StreamWriter writer = new StreamWriter(output);
            using (writer)
            {
                writer.WriteLine(line);
            }
            Console.WriteLine("Successesful replacing!");
        }
        catch (Exception)
        {
            Console.WriteLine("Error!");
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory
                android:title="@string/login">
                <Preference
		                android:key="pref_account_create"
                    	android:name="pref_account_create"
                    	android:title="@string/pref_account_create_title">
                    <intent android:action="android.intent.action.VIEW"
                            android:data="https://pasty.cc/user/create/" />
                </Preference>
		        <EditTextPreference
		                android:name="pref_username"
		                android:defaultValue="@string/pref_username_default"
		                android:title="@string/pref_username_title"
		                android:singleLine="true"
		                android:key="pref_username" />
		        <EditTextPreference
		                android:name="pref_password"
		                android:defaultValue="@string/pref_password_default"
		                android:title="@string/pref_password_title"
		                android:singleLine="true"
						android:password="true"
		                android:key="pref_password" />
        </PreferenceCategory>
        <PreferenceCategory
                android:title="@string/behaviour">
                <CheckBoxPreference
                        android:title="@string/pref_paste_clipboard_title"
                        android:defaultValue="true"
                        android:summary="@string/pref_paste_clipboard_sum"
                        android:key="pref_paste_clipboard" />
                <CheckBoxPreference
                        android:title="@string/pref_clickable_links_title"
                        android:defaultValue="false"
                        android:summary="@string/pref_clickable_links_sum"
                        android:key="pref_clickable_links" />
                <PreferenceScreen
				        android:key="pref_cat_push"
				        android:title="@string/pref_push_title"
				        android:persistent="false">
                    <CheckBoxPreference
                            android:title="@string/pref_push_title"
                            android:defaultValue="false"
                            android:summary="@string/pref_push_sum"
                            android:key="pref_push_gcm" />
                    <CheckBoxPreference
                            android:title="@string/pref_push_copy_to_clipboard_title"
                            android:defaultValue="false"
                            android:summary="@string/pref_push_copy_to_clipboard_sum"
                            android:key="pref_push_copy_to_clipboard"
                            android:dependency="pref_push_gcm" />
                    <CheckBoxPreference
                            android:title="@string/pref_push_notify_title"
                            android:defaultValue="true"
                            android:summary="@string/pref_push_notify_sum"
                            android:key="pref_push_notify"
                            android:dependency="pref_push_gcm" />
                </PreferenceScreen>
        </PreferenceCategory>
        <PreferenceCategory
                android:title="@string/network">
                <CheckBoxPreference
                        android:title="@string/pref_usehttps_title"
                        android:defaultValue="true"
                        android:summary="@string/pref_usehttps_sum"
                        android:key="pref_usehttps" />
        </PreferenceCategory>
        <PreferenceCategory
                android:title="@string/about">
                <Preference
		                android:key="pref_tos"
		                android:title="@string/pref_tos_title" >
                    <intent android:action="android.intent.action.VIEW"
                            android:data="https://pasty.cc/tos/" />
                </Preference>
                <Preference
		                android:key="pref_privacy"
		                android:title="@string/pref_privacy_title">
                    <intent android:action="android.intent.action.VIEW"
                            android:data="http://electricdynamite.de/privacy.html" />
                </Preference>
                <Preference
		                android:key="pref_version"
		                android:title="@string/pref_version_title" />
        </PreferenceCategory>
</PreferenceScreen>


text:
<?php

/**
 * Exception thrown when generating an ID for a persistent object failed.
 *
 * @package PersistentObject
 * @version //autogen//
 */
class ezcPersistentIdentifierGenerationException extends ezcPersistentObjectException
{

    /**
     * Constructs a new ezcPersistentIdentifierGenerationException for the class
     * $class with the optional message $msg.
     *
     * @param string $class
     * @param string $msg
     * @return void
     */
    public function __construct( $class, $msg = null )
    {
        $info = "Could not create an identifier for the object of type '$class'.";
        if ( $info != null )
        {
            $info .= " $msg";
        }
        parent::__construct( $info );
    }
}
?>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioSourceDestroy : MonoBehaviour {

    AudioSource myAudioSource;

    private void Start()
    {
        myAudioSource = GetComponent<AudioSource>();
    }

    private void Update()
    {
        if (!myAudioSource.isPlaying)
        {
            Destroy(gameObject);
        }
    }
}


text:
package io.trydent.stp.item;

public interface ImportedItem extends Item {
  static ImportedItem of(final Price price) {
    return new ImportedItemImpl(new ItemImpl(price.value()));
  }

  static <I extends TaxedItem & Item> ImportedItem fromTaxed(final I item) {
    return new ImportedItemImpl(item);
  }
}


text:
<!DOCTYPE html>

    <title>Place Autocomplete</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

on2tr
Phone: +1957780625
33062
... xx reviews, yy stars and $ prices.

    <input hidden id="origin-input" class="controls" type="text"
           placeholder="Enter an origin location">

    <input id="destination-input" class="controls" type="text"
           placeholder="Enter a destination location">

        <input type="radio" name="type" id="changemode-walking">
        Walking

        <input type="radio" name="type" id="changemode-transit">
        Transit

        <input type="radio" name="type" id="changemode-driving" checked="checked">
        Driving


text: tools/scripts to package keyvi


text:
from collections import deque
from test.support import run_unittest
import unittest

class base_set:
    def __init__(self, el):
        self.el = el

class myset(base_set):
    def __contains__(self, el):
        return self.el == el

class seq(base_set):
    def __getitem__(self, n):
        return [self.el][n]

class TestContains(unittest.TestCase):
    def test_common_tests(self):
        a = base_set(1)
        b = myset(1)
        c = seq(1)
        self.assert_(1 in b)
        self.assert_(0 not in b)
        self.assert_(1 in c)
        self.assert_(0 not in c)
        self.assertRaises(TypeError, lambda: 1 in a)
        self.assertRaises(TypeError, lambda: 1 not in a)

        # test char in string
        self.assert_('c' in 'abc')
        self.assert_('d' not in 'abc')

        self.assert_('' in '')
        self.assert_('' in 'abc')

        self.assertRaises(TypeError, lambda: None in 'abc')

    def test_builtin_sequence_types(self):
        # a collection of tests on builtin sequence types
        a = range(10)
        for i in a:
            self.assert_(i in a)
        self.assert_(16 not in a)
        self.assert_(a not in a)

        a = tuple(a)
        for i in a:
            self.assert_(i in a)
        self.assert_(16 not in a)
        self.assert_(a not in a)

        class Deviant1:
            """Behaves strangely when compared

            This class is designed to make sure that the contains code
            works when the list is modified during the check.
            """
            aList = range(15)
            def __cmp__(self, other):
                if other == 12:
                    self.aList.remove(12)
                    self.aList.remove(13)
                    self.aList.remove(14)
                return 1

        self.assert_(Deviant1() not in Deviant1.aList)

        class Deviant2:
            """Behaves strangely when compared

            This class raises an exception during comparison.  That in
            turn causes the comparison to fail with a TypeError.
            """
            def __cmp__(self, other):
                if other == 4:
                    raise RuntimeError("gotcha")

        try:
            self.assert_(Deviant2() not in a)
        except TypeError:
            pass

    def test_nonreflexive(self):
        # containment and equality tests involving elements that are
        # not necessarily equal to themselves

        class MyNonReflexive(object):
            def __eq__(self, other):
                return False
            def __hash__(self):
                return 28

        values = float('nan'), 1, None, 'abc', MyNonReflexive()
        constructors = list, tuple, dict.fromkeys, set, frozenset, deque
        for constructor in constructors:
            container = constructor(values)
            for elem in container:
                self.assert_(elem in container)
            self.assert_(container == constructor(values))
            self.assert_(container == container)

def test_main():
    run_unittest(TestContains)

if __name__ == '__main__':
    test_main()


text:
package legends.xml.handlers;

import java.lang.reflect.InvocationTargetException;

public interface StringConsumer {
	public void accept(String string)
			throws InvocationTargetException, IllegalAccessException, IllegalArgumentException;
}


text:
/**
 * Traverse a schema, applying a function(schema,path) on every sub schema
 * i.e. every property of an object.
 */
export function traverseSchema(schema, fn, path, ignoreArrays) {
  ignoreArrays = ignoreArrays === undefined ? true : ignoreArrays;

  path = path || [];

  const traverse = function(schemaObject: any, processorFunction: Function, pathArray: Array<string>) {
    processorFunction(schemaObject, pathArray);
    if (schemaObject.properties) {
      Object.keys(schemaObject.properties).forEach((name) => {
        const currentPath = pathArray.slice();
        currentPath.push(name);
        traverse(schemaObject.properties[name], processorFunction, currentPath);
      });
    }

    // Only support type "array" which have a schemaObject as "items".
    if (!ignoreArrays && schemaObject.items) {
      const arrPath = pathArray.slice(); arrPath.push('');
      traverse(schemaObject.items, processorFunction, arrPath);
    }
  };

  traverse(schema, fn, path || []);
}

export function traverseForm(form, fn) {
  fn(form);
  if (form.items) {
    form.items.forEach((f) => {
      traverseForm(f, fn);
    });
  }

  if (form.tabs) {
    form.tabs.forEach((tab) => {
      if (tab.items) {
        tab.items.forEach((f) => {
          traverseForm(f, fn);
        });
      }
    });
  }
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28610_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">QmOUHM— Hum

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PM: A4555 Hum

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">o g xw mwmoow ooflBm HNum .OIZ Hm>k

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2x0 new: Ewing/Hm

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2x0 mom: 2 2mg

    <p class="styleSans24.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">omxm mbmowmmfi $23; Omxm wfiwomg Emma/EH2

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">BIT
BIT
BIT

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">33w Q ~ 2 H
"GE ENE .02

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">56am Sm m N

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">stw 3 m w m

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Egon «R w m gnaw 3m w ¢

    <p class="styleSans35.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PEN mww W; 32 macaw WEE?» a >HD 5mm 2mm MOB EAR mm: ZDM HUME PDQ DDS 004 mm: IEHG

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">866 003-003 a: 0m 3 N62 3.? 3.5m 2me wmbnb

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0036 003.003 a: o S _.mw 24m 8.: Nmoum Ohbd

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">otmdfi 83.00% a: ON mm 0.; who mNSN mow mine

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">mtmdfi oommdovm a: o 3 0.: 2.2 Duo mom 9R"?

    <p class="styleSans3.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
title: First Lesson of Year 8
layout: post
author: padraig.hill
permalink: /first-lesson-of-year-8/
source-id: 10MZU_vAqjGa8-jBZ-vM85gm1T4XOKc5UgzIKLisDE20
published: true
---
**First Lesson of Year 8**

This is the first lesson of year 8 that I will be blogging about.

In this lesson we started using the Raspberry Pi computers. My partner and I tried out a code which was called 'Hello World'. We read what to do in a handbook and followed it step by step. This meant it wasn't very fun and near the end it even got a bit boring. However it was cool to see our creations come to life on the screen before our eyes.

**Pros:** It was cool to see our code working

**Cons:** We started to get a little bored

**Improvements:** We could have been made to work some things out


text:
function flyIn(obj){
  $(obj).next().addClass('flyIn').one('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd',function(){
    $(this).removeClass('flyIn');
  })
}


text:
package net.java.sip.communicator.plugin.contactsourceconfig;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.service.gui.*;

import org.osgi.framework.*;

/**
 *
 * @author Yana Stamcheva
 */
public class ContactSourceConfigForm
    extends TransparentPanel
    implements ServiceListener
{
    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 0L;

    /**
     * The drop down list of contact sources.
     */
    private final JComboBox contactSourceComboBox = new JComboBox();

    /**
     * Creates the <tt>ContactSourceConfigForm</tt>.
     */
    public ContactSourceConfigForm()
    {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        contactSourceComboBox.setRenderer(new ContactSourceRenderer());

        final JPanel centerPanel
            = new TransparentPanel(new BorderLayout(10, 10));
        centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        centerPanel.setPreferredSize(new Dimension(450, 300));

        contactSourceComboBox.addItemListener(new ItemListener()
        {
            public void itemStateChanged(ItemEvent event)
            {
                ConfigurationForm form
                    = (ConfigurationForm) contactSourceComboBox
                        .getSelectedItem();

                centerPanel.removeAll();
                JComponent c = (JComponent) form.getForm();
                c.setOpaque(false);

                centerPanel.add(c, BorderLayout.CENTER);

                centerPanel.revalidate();
                centerPanel.repaint();
            }
        });

        init();

        add(contactSourceComboBox);
        add(Box.createVerticalStrut(10));
        add(centerPanel);

        ContactSourceConfigActivator.bundleContext.addServiceListener(this);
    }

    /**
     * Initializes this panel.
     */
    private void init()
    {
        String osgiFilter = "("
            + ConfigurationForm.FORM_TYPE
            + "="+ConfigurationForm.CONTACT_SOURCE_TYPE+")";

        ServiceReference[] confFormsRefs = null;
        try
        {
            confFormsRefs = ContactSourceConfigActivator.bundleContext
                .getServiceReferences(  ConfigurationForm.class.getName(),
                                        osgiFilter);
        }
        catch (InvalidSyntaxException ex)
        {}

        if(confFormsRefs != null)
        {
            for (int i = 0; i < confFormsRefs.length; i++)
            {
                ConfigurationForm form
                    = (ConfigurationForm) ContactSourceConfigActivator
                        .bundleContext.getService(confFormsRefs[i]);

                Object formComponent = form.getForm();
                if (formComponent instanceof Component)
                    addConfigForm(form);
            }
        }
    }

    /**
     * Handles registration of a new configuration form.
     * @param event the <tt>ServiceEvent</tt> that notified us
     */
    public void serviceChanged(ServiceEvent event)
    {
        ServiceReference serviceRef = event.getServiceReference();

        Object property = serviceRef.getProperty(ConfigurationForm.FORM_TYPE);
        if (property != ConfigurationForm.CONTACT_SOURCE_TYPE)
            return;

        Object sService
            = ContactSourceConfigActivator.bundleContext
                .getService(serviceRef);

        // we don't care if the source service is not a configuration form
        if (!(sService instanceof ConfigurationForm))
            return;

        ConfigurationForm configForm = (ConfigurationForm) sService;

        if (!configForm.isAdvanced())
            return;

        Object formComponent;
        switch (event.getType())
        {
        case ServiceEvent.REGISTERED:
            formComponent = configForm.getForm();
            if (formComponent instanceof Component)
                addConfigForm(configForm);
            break;

        case ServiceEvent.UNREGISTERING:
            formComponent = configForm.getForm();
            if (formComponent instanceof Component)
                remove((Component) formComponent);
            break;
        }
    }

    /**
     * Adds the given form to this configuration panel.
     *
     * @param form the <tt>ConfigurationForm</tt> to add
     */
    private void addConfigForm(ConfigurationForm form)
    {
        int cIndex = form.getIndex();

        if (cIndex >= contactSourceComboBox.getItemCount() || cIndex == -1)
            contactSourceComboBox.addItem(form);
        else
            contactSourceComboBox.insertItemAt(form, cIndex);
    }

    /**
     * The contact source combo box custom renderer.
     */
    private class ContactSourceRenderer extends DefaultListCellRenderer
    {
        /**
         * Serial version UID.
         */
        private static final long serialVersionUID = 0L;

        @Override
        public Component getListCellRendererComponent(
            JList list, Object value, int index,
                boolean isSelected, boolean hasFocus)
        {
            JLabel renderer
                = (JLabel) super.getListCellRendererComponent(
                    list, value, index, isSelected, hasFocus);

            if (value != null)
            {
                ConfigurationForm form = (ConfigurationForm) value;

                renderer.setText(form.getTitle());
            }

            return renderer;
        }
    }
}


text:
#ifndef _LINUX_TOPOLOGY_H
#define _LINUX_TOPOLOGY_H

#include <linux/cpumask.h>
#include <linux/bitops.h>
#include <linux/mmzone.h>
#include <linux/smp.h>
#include <linux/percpu.h>
#include <asm/topology.h>

#ifndef nr_cpus_node
#define nr_cpus_node(node) cpumask_weight(cpumask_of_node(node))
#endif

#define for_each_node_with_cpus(node)			\
	for_each_online_node(node)			\
		if (nr_cpus_node(node))

int arch_update_cpu_topology(void);

/* Conform to ACPI 2.0 SLIT distance definitions */
#define LOCAL_DISTANCE		10
#define REMOTE_DISTANCE		20
#ifndef node_distance
#define node_distance(from,to)	((from) == (to) ? LOCAL_DISTANCE : REMOTE_DISTANCE)
#endif
#ifndef RECLAIM_DISTANCE
/*
 * If the distance between nodes in a system is larger than RECLAIM_DISTANCE
 * (in whatever arch specific measurement units returned by node_distance())
 * and zone_reclaim_mode is enabled then the VM will only call zone_reclaim()
 * on nodes within this distance.
 */
#define RECLAIM_DISTANCE 30
#endif
#ifndef PENALTY_FOR_NODE_WITH_CPUS
#define PENALTY_FOR_NODE_WITH_CPUS	(1)
#endif

#ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
DECLARE_PER_CPU(int, numa_node);

#ifndef numa_node_id
/* Returns the number of the current Node. */
static inline int numa_node_id(void)
{
	return raw_cpu_read(numa_node);
}
#endif

#ifndef cpu_to_node
static inline int cpu_to_node(int cpu)
{
	return per_cpu(numa_node, cpu);
}
#endif

#ifndef set_numa_node
static inline void set_numa_node(int node)
{
	this_cpu_write(numa_node, node);
}
#endif

#ifndef set_cpu_numa_node
static inline void set_cpu_numa_node(int cpu, int node)
{
	per_cpu(numa_node, cpu) = node;
}
#endif

#else	/* !CONFIG_USE_PERCPU_NUMA_NODE_ID */

/* Returns the number of the current Node. */
#ifndef numa_node_id
static inline int numa_node_id(void)
{
	return cpu_to_node(raw_smp_processor_id());
}
#endif

#endif	/* [!]CONFIG_USE_PERCPU_NUMA_NODE_ID */

#ifdef CONFIG_HAVE_MEMORYLESS_NODES

/*
 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem().
 */
DECLARE_PER_CPU(int, _numa_mem_);
extern int _node_numa_mem_[MAX_NUMNODES];

#ifndef set_numa_mem
static inline void set_numa_mem(int node)
{
	this_cpu_write(_numa_mem_, node);
	_node_numa_mem_[numa_node_id()] = node;
}
#endif

#ifndef node_to_mem_node
static inline int node_to_mem_node(int node)
{
	return _node_numa_mem_[node];
}
#endif

#ifndef numa_mem_id
/* Returns the number of the nearest Node with memory */
static inline int numa_mem_id(void)
{
	return raw_cpu_read(_numa_mem_);
}
#endif

#ifndef cpu_to_mem
static inline int cpu_to_mem(int cpu)
{
	return per_cpu(_numa_mem_, cpu);
}
#endif

#ifndef set_cpu_numa_mem
static inline void set_cpu_numa_mem(int cpu, int node)
{
	per_cpu(_numa_mem_, cpu) = node;
	_node_numa_mem_[cpu_to_node(cpu)] = node;
}
#endif

#else	/* !CONFIG_HAVE_MEMORYLESS_NODES */

#ifndef numa_mem_id
/* Returns the number of the nearest Node with memory */
static inline int numa_mem_id(void)
{
	return numa_node_id();
}
#endif

#ifndef node_to_mem_node
static inline int node_to_mem_node(int node)
{
	return node;
}
#endif

#ifndef cpu_to_mem
static inline int cpu_to_mem(int cpu)
{
	return cpu_to_node(cpu);
}
#endif

#endif	/* [!]CONFIG_HAVE_MEMORYLESS_NODES */

#ifndef topology_physical_package_id
#define topology_physical_package_id(cpu)	((void)(cpu), -1)
#endif
#ifndef topology_core_id
#define topology_core_id(cpu)			((void)(cpu), 0)
#endif
#ifndef topology_sibling_cpumask
#define topology_sibling_cpumask(cpu)		cpumask_of(cpu)
#endif
#ifndef topology_core_cpumask
#define topology_core_cpumask(cpu)		cpumask_of(cpu)
#endif

#ifdef CONFIG_SCHED_SMT
static inline const struct cpumask *cpu_smt_mask(int cpu)
{
	return topology_sibling_cpumask(cpu);
}
#endif

static inline const struct cpumask *cpu_cpu_mask(int cpu)
{
	return cpumask_of_node(cpu_to_node(cpu));
}

#endif /* _LINUX_TOPOLOGY_H */


text:
#pragma once

#ifndef _MSC_VER

	#include <pthread.h>

#else

	#include <windows.h>

#endif

namespace darts
{
/*
	Class: Lock

	A class used to provide generic locking objects works for windows
	and any OS with pthreads.
*/
#ifndef _MSC_VER
class Lock
{
private:
		/* Locking object with pthreads. */
		pthread_mutex_t mutex_;

public:
	/* Creates the lock for use. */
	Lock( void ) { pthread_mutex_init ( &mutex_, NULL ); }

	/* Destroys the lock. */
	~Lock( void ) { pthread_mutex_destroy ( &mutex_ ); }

	/* Waits until the lock is secured. */
	void lock ( void ) { pthread_mutex_lock ( &mutex_ ); }

	/*
			Tries to lock otherwise returns.
			Returns: True if the lock was secured.
	*/
    bool trylock ( void ) { return 0 == pthread_mutex_trylock ( &mutex_ ); }

	/* Yields the lock for others to use. */
    void unlock ( void ) { pthread_mutex_unlock ( &mutex_ ); }
};

#else

class Lock
{
private:
		/* Locking object on windows. */
		HANDLE mutex_;

public:
	/* Creates the lock for use. */
	Lock( void ) { mutex_ = CreateMutex( NULL, FALSE, NULL ); }

	/* Destroys the lock. */
	~Lock( void ) { CloseHandle( mutex_ ); }

	/* Waits until the lock is secured. */
	void lock ( void ) { WaitForSingleObject( mutex_, INFINITE ); }

	/*
			Tries to lock (waits for 1 millisecond) otherwise returns.
			Returns: True if the lock was secured.
	*/
    bool trylock ( void ) { return WAIT_OBJECT_0 == WaitForSingleObject( mutex_, 1 ); }

	/* Yields the lock for others to use. */
    void unlock ( void ) { ReleaseMutex( mutex_ ); }
};

#endif

} // namespace darts


text:
INSERT INTO PORTAL_WIDGET(ID,NAME,URL) VALUES(7,'地图','/widgets/map.html');
INSERT INTO PORTAL_WIDGET(ID,NAME,URL) VALUES(8,'时钟','/widgets/clock.html');
INSERT INTO PORTAL_WIDGET(ID,NAME,URL) VALUES(9,'私信','/rs/msg/widget/msg');


text:
require "spec_helper"
require_relative "../../../lib/octopolo/github"

module Octopolo
  module GitHub
    describe Commit do
      context ".new" do
        let(:commit_data) { stub }

        it "remembers the commit data from GitHub API" do
          commit = Commit.new commit_data
          commit.commit_data.should == commit_data
        end
      end

      context "#author_name" do
        let(:commit) do
          Commit.new stub
        end

        it "fetches the author name from the author" do
          commit.stub(:author => stub(:author_name => "pbyrne"))
          commit.author_name.should == "pbyrne"
        end
      end

      context "#author" do
        let(:commit_data) do
          stub(:author => stub(:login => "pbyrne"))
        end

        it "fetches the User from github" do
          commit = Commit.new commit_data
          GitHub::User.should_receive(:new).with("pbyrne")
          commit.author
        end

        it "gracefully handles a commit without an author" do
          commit = Commit.new author: nil
          User.should_receive(:new).with(GitHub::UNKNOWN_USER)
          commit.author
        end
      end

      context ".for_pull_request pull_request" do
        let(:pull_request) { stub(repo_name: "foo/bar", number: 123) }
        let(:raw_commit1) { stub }
        let(:raw_commits) { [raw_commit1] }
        let(:wrapper_commit) { stub }

        it "fetches from octokit and returns Commit wrappers" do
          GitHub.should_receive(:pull_request_commits).with(pull_request.repo_name, pull_request.number) { raw_commits }
          Commit.should_receive(:new).with(raw_commit1) { wrapper_commit }
          Commit.for_pull_request(pull_request).should == [wrapper_commit]
        end
      end
    end
  end
end


text:
#ifndef __MODEST_CACHE_MGR_H__
#define __MODEST_CACHE_MGR_H__

#include <glib-object.h>
G_BEGIN_DECLS

/* convenience macros */
#define MODEST_TYPE_CACHE_MGR         (modest_cache_mgr_get_type())
#define MODEST_CACHE_MGR(obj)         (G_TYPE_CHECK_INSTANCE_CAST((obj),MODEST_TYPE_CACHE_MGR,ModestCacheMgr))
#define MODEST_CACHE_MGR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),MODEST_TYPE_CACHE_MGR,GObject))
#define MODEST_IS_CACHE_MGR(obj)          (G_TYPE_CHECK_INSTANCE_TYPE((obj),MODEST_TYPE_CACHE_MGR))
#define MODEST_IS_CACHE_MGR_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass),MODEST_TYPE_CACHE_MGR))
#define MODEST_CACHE_MGR_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS((obj),MODEST_TYPE_CACHE_MGR,ModestCacheMgrClass))

typedef struct _ModestCacheMgr      ModestCacheMgr;
typedef struct _ModestCacheMgrClass ModestCacheMgrClass;

struct _ModestCacheMgr {
	 GObject parent;
	/* insert public members, if any */
};

struct _ModestCacheMgrClass {
	GObjectClass parent_class;
};

/*
 * the caches managed by this class
 */
typedef enum {
	MODEST_CACHE_MGR_CACHE_TYPE_DATE_STRING,       /* time_t => string */
	MODEST_CACHE_MGR_CACHE_TYPE_DISPLAY_STRING,    /* gchar* => gchar* */
	MODEST_CACHE_MGR_CACHE_TYPE_PIXBUF,            /* gchar* => GdkPixbuf */
	MODEST_CACHE_MGR_CACHE_TYPE_SEND_QUEUE,        /* TnyAccount* => TnySendQueue* */

	MODEST_CACHE_MGR_CACHE_TYPE_NUM
} ModestCacheMgrCacheType;

/**
 * modest_cache_mgr_get_type:
 *
 * get the GType for ModestCacheMgr
 *
 * Returns: the GType
 */
GType        modest_cache_mgr_get_type    (void) G_GNUC_CONST;

/**
 * modest_cache_mgr_new:
 *
 * instantiate a new cache_mgr object
 *
 * Returns: a new cache_mgr or NULL in case of error
 */
ModestCacheMgr*    modest_cache_mgr_new          (void);

/**
 * modest_cache_mgr_get_cache:
 * @self: a valid cache mgr obj
 * @type: a valid cache mgr cache type
 *
 * get the cache (GHashTable) of the requested type
 *
 * Returns: the requested cache (GHashTable)
 * the returned  hashtable should NOT be destroyed or unref'd.
 */
GHashTable*     modest_cache_mgr_get_cache    (ModestCacheMgr* self, ModestCacheMgrCacheType type);

/**
 * modest_cache_mgr_flush
 * @self: a valid cache mgr obj
 * @type: a valid cache mgr cache type
 *
 * flush the cache (hashtable) of the given type
 */
void            modest_cache_mgr_flush        (ModestCacheMgr *self, ModestCacheMgrCacheType type);

/**
 * modest_cache_mgr_flush
 * @self: a valid cache mgr obj
 *
 * flush all caches
 */
void            modest_cache_mgr_flush_all    (ModestCacheMgr *self);

/**
 * modest_cache_mgr_get_size
 * @self: a valid cache mgr obj
 * @type: a valid cache mgr cache type
 *
 * get the size (number of [key,value]-pairs) in the cache
 *
 * Returns: the size of the give cache type
 */
guint           modest_cache_mgr_get_size     (ModestCacheMgr *self, ModestCacheMgrCacheType type);

G_END_DECLS

#endif /* __MODEST_CACHE_MGR_H__ */


text:
Article 408-1
----
Les biens ou droits d'un mineur ne peuvent être transférés dans un patrimoine
fiduciaire.


text:
import logging
import os

from abc import abstractmethod

class LoggedObject(object):
  @property
  def logger(self):
    logger = logging.getLogger(__name__)
    return logger

class SazabiBotPlugin(LoggedObject):
  @abstractmethod
  async def parse(self, client, message, *args, **kwargs):
    pass


text:
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{ trans('template_asset_library_audio.edit_audio') }}

                <audio class="center-block" style="width:100%;margin-bottom:50px" controls="controls">
                    <source src="{{ $uri }}" type="audio/mpeg">
                </audio>

                {{ trans('template_asset_library_audio.file_type') }} {{ $file_type }}

                {{ trans('template_asset_library_audio.uploaded_on') }} {{ $uploaded_on }}

                {{ trans('template_asset_library_audio.file_size') }} {{ $file_size }}

                {{ trans('template_asset_library_audio.duration') }} {{ $duration }}

                {{ trans('template_asset_library_audio.caption') }}
                <textarea class="form-control" rows="3" id="caption">{{ $caption }}</textarea>
                {{ trans('template_asset_library_audio.caption_help') }}

                {{ trans('template_asset_library_audio.description') }}
                <textarea class="form-control" rows="3" id="description">{{ $description }}</textarea>

    {{ trans('template_asset_library_audio.delete_permanently') }}
    <button type="button" class="btn btn-default save-btn" data-audio-id="{{ $audio_id }}"> {{ trans('template_asset_library_audio.save') }}</button>
    <button type="button" class="btn btn-default insert-btn" data-dismiss="modal" style="display:none" data-audio-id="{{ $audio_id }}"> {{ trans('template_asset_library_audio.insert') }}</button>
    <button type="button" class="btn btn-default" data-dismiss="modal">{{ trans('template_asset_library_audio.close') }}</button>


text:
"""
    Swaggy Jenkins

    Jenkins API clients generated from Swagger / Open API specification  # noqa: E501

    The version of the OpenAPI document: 1.5.1-pre.0
    Contact: blah@cliffano.com
    Generated by: https://openapi-generator.tech
"""

import sys
import unittest

import swaggyjenkins
from swaggyjenkins.model.favorite_impl import FavoriteImpl
globals()['FavoriteImpl'] = FavoriteImpl
from swaggyjenkins.model.user_favorites import UserFavorites

class TestUserFavorites(unittest.TestCase):
    """UserFavorites unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testUserFavorites(self):
        """Test UserFavorites"""
        # FIXME: construct object with mandatory attributes with example values
        # model = UserFavorites()  # noqa: E501
        pass

if __name__ == '__main__':
    unittest.main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
    and other contributors as indicated by the @author tags.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

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

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

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.hawkular.agent</groupId>
    <artifactId>hawkular-swarm-agent-dists</artifactId>
    <version>0.20.2.Final-SNAPSHOT</version>
  </parent>

  <artifactId>hawkular-swarm-agent-dist</artifactId>
  <name>Hawkular Agent: Wildfly Swarm Agent Distribution</name>

  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>org.hawkular.agent</groupId>
      <artifactId>hawkular-swarm-agent-api</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hawkular.agent</groupId>
      <artifactId>hawkular-swarm-agent</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.wildfly.swarm</groupId>
        <artifactId>wildfly-swarm-plugin</artifactId>
        <version>${version.swarm.plugin}</version>
        <configuration>
          <mainClass>org.hawkular.agent.dist.Main</mainClass>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>package</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>


text:
package com.joe.zatuji.view;

import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.joe.zatuji.R;
import com.joe.zatuji.repo.bean.Gallery;
import com.joe.zatuji.view.base.BaseDialog;

/**
 * Created by joe on 16/5/28.
 */
public class GalleryMenuDialog extends BaseDialog implements View.OnClickListener{
    private Window window;
    private Gallery mImg;
    public GalleryMenuDialog(Context context) {
        super(context,R.style.dialog_fullscreen);
    }

    protected int getLayout() {
        window = this.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        return R.layout.dialog_bottom_menu;
    }

    public void show(Gallery gallery) {
        this.mImg = gallery;
        show();
    }
    @Override
    protected void initView() {
//        去掉dialog默认的padding
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setWindowAnimations(R.style.dialog_anim);
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

        //设置dialog的位置在底部
        lp.gravity = Gravity.BOTTOM;
        window.setAttributes(lp);
        TextView mSetFront = (TextView) findViewById(R.id.tv_edit_dialog);
        mSetFront.setOnClickListener(this);
        mSetFront.setText("设为封面");

        TextView mDelete = (TextView) findViewById(R.id.tv_delete_dialog);
        TextView mRecommend = (TextView) findViewById(R.id.tv_recomend_dialog);
        mRecommend.setVisibility(View.VISIBLE);
        mRecommend.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        mDelete.setText("移除");
        findViewById(R.id.tv_cancel_dialog).setOnClickListener(this);
        this.setCanceledOnTouchOutside(true);
    }
    @Override
    protected void initListener() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_cancel_dialog:
                dismiss();
                break;
            case R.id.tv_edit_dialog:
                mListener.onFront(mImg);
                dismiss();
                break;
            case R.id.tv_delete_dialog:
                mListener.onDelete(mImg);
                dismiss();
                break;
            case R.id.tv_recomend_dialog:
                mListener.onRecommend(mImg);
                dismiss();
                break;
        }

    }

    private OnMenuClickListener mListener;
    public GalleryMenuDialog setOnMenuClickListener(OnMenuClickListener mListener){
        this.mListener = mListener;
        return this;
    }

    public interface OnMenuClickListener{
        void onFront(Gallery gallery);
        void onDelete(Gallery gallery);
        void onRecommend(Gallery gallery);
    }

}


text:
package api

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/spf13/viper"
	"github.com/stretchr/testify/require"
)

func Test_rebindHandler(t *testing.T) {
	cases := []struct {
		name                       string
		host                       string
		origin                     string
		expectedCode               int
		listenerKey                string
		listenerAddr               string
		disableCrossOriginKey      string
		disableCrossOriginChecking bool
		errorMessage               string
	}{
		{
			name:         "in general",
			expectedCode: http.StatusOK,
		},
		{
			name:         "rebind",
			host:         "hacker.com",
			expectedCode: http.StatusForbidden,
			errorMessage: "forbidden host\n",
		},
		{
			name:         "invalid host",
			host:         ":::::::::",
			expectedCode: http.StatusBadRequest,
			errorMessage: "bad request\n",
		},
		{
			name:         "custom host",
			host:         "0.0.0.0",
			expectedCode: http.StatusOK,
			listenerKey:  "listener-addr",
			listenerAddr: "0.0.0.0:0000",
		},
		{
			name:                       "disable CORS",
			host:                       "example.com",
			origin:                     "hacker.com",
			expectedCode:               http.StatusOK,
			disableCrossOriginKey:      "disable-origin-check",
			disableCrossOriginChecking: true,
			listenerKey:                "listener-addr",
			listenerAddr:               "example.com:80",
			errorMessage:               "response",
		},
		{
			name:         "fails CORS and invalid host",
			host:         "example.com",
			origin:       "hacker.com",
			expectedCode: http.StatusForbidden,
			errorMessage: "forbidden host: forbidden bad origin\n",
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			if tc.listenerKey != "" {
				viper.Set(tc.listenerKey, tc.listenerAddr)
				defer viper.Set(tc.listenerKey, "")
			}

			if tc.disableCrossOriginKey != "" {
				viper.Set(tc.disableCrossOriginKey, tc.disableCrossOriginChecking)
				defer viper.Set(tc.disableCrossOriginKey, false)
			}
			fake := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprint(w, "response")
			})

			wrapped := rebindHandler(context.TODO(), AcceptedHosts())(fake)

			ts := httptest.NewServer(wrapped)
			defer ts.Close()

			req, err := http.NewRequest(http.MethodGet, ts.URL, nil)
			require.NoError(t, err)

			if tc.origin != "" {
				req.Header["Origin"] = []string{tc.origin}
			}

			if tc.host != "" {
				req.Host = tc.host
			}

			res, err := http.DefaultClient.Do(req)
			require.NoError(t, err)

			if tc.errorMessage != "" {
				message, err := ioutil.ReadAll(res.Body)
				require.NoError(t, err)
				require.Equal(t, tc.errorMessage, string(message))
			}

			require.Equal(t, tc.expectedCode, res.StatusCode)
		})
	}
}

func Test_shouldAllowHost(t *testing.T) {
	cases := []struct {
		name          string
		host          string
		acceptedHosts []string
		expected      bool
	}{
		{
			name:          "0.0.0.0 allow all",
			host:          "192.168.1.1",
			acceptedHosts: []string{"127.0.0.1", "localhost", "0.0.0.0"},
			expected:      true,
		},
		{
			name:          "deny 192.168.1.1",
			host:          "192.168.1.1",
			acceptedHosts: []string{"127.0.0.1", "localhost"},
			expected:      false,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			require.Equal(t, tc.expected, ShouldAllowHost(tc.host, tc.acceptedHosts))
		})
	}
}

func Test_checkSameOrigin(t *testing.T) {
	cases := []struct {
		name     string
		host     string
		origin   string
		expected bool
	}{
		{
			name:     "host/origin match",
			host:     "192.168.1.1:7777",
			origin:   "http://192.168.1.1:7777",
			expected: true,
		},
		{
			name:     "host/origin do not match",
			host:     "192.168.1.1:7777",
			origin:   "http://127.0.0.1:7777",
			expected: false,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			r := &http.Request{
				Host:   tc.host,
				Header: make(http.Header, 1),
			}
			r.Header.Set("Origin", tc.origin)
			require.Equal(t, tc.expected, checkSameOrigin(r))
		})
	}
}


text:
package org.aexlib.gae.datastore;

public interface EntityCollectionProperty<ENTITY extends EntityBase<ENTITY>, COLLECTION_TYPE, PROPERTY_TYPE> extends EntityProperty<ENTITY, COLLECTION_TYPE> {
}


text:
package com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases;

import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.ErrorInfo.CustomMessageGeneratorErrorDescription;
import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.ErrorInfo.PlainTextErrorDescription;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Autogenerated by XGen4J on January 1, 0001.
 */
public class Information {

    private static List<ErrorInfo> errorInfoList;
    private static Map<String, ErrorInfo> idToErrorInfoMap;

    private static final AtomicBoolean loaded = new AtomicBoolean();

    private static void load() {
        if (loaded.compareAndSet(false, true)) {
            errorInfoList = new ArrayList<>();
            idToErrorInfoMap = new HashMap<>();

            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.RootNameError.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.RootNameException.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.RootNameError.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Error.CODE,
                    false
            ));
            errorInfoList.add(new ErrorInfo(
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Error.class,
                    new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Exception.class),
                    com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Error.CODE,
                    false
            ));
            errorInfoList = Collections.unmodifiableList(errorInfoList);

            for (ErrorInfo errorInfo : errorInfoList) {
                idToErrorInfoMap.put(errorInfo.code().id(), errorInfo);
            }

            loaded.set(true);
        }
    }

    public static List<ErrorInfo> list() {
        load();
        return errorInfoList;
    }

    public static ErrorInfo forId(String id) {
        if (id == null) throw new IllegalArgumentException("id");

        load();
        return idToErrorInfoMap.get(id);
    }

}


text:
from __future__ import absolute_import
from datetime import date, datetime  # noqa: F401

from typing import List, Dict  # noqa: F401

from openapi_server.models.base_model_ import Model
from openapi_server import util

class PipelineFolderImpl(Model):
    """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

    Do not edit the class manually.
    """

    def __init__(self, _class=None, display_name=None, full_name=None, name=None, organization=None, number_of_folders=None, number_of_pipelines=None):  # noqa: E501
        """PipelineFolderImpl - a model defined in OpenAPI

        :param _class: The _class of this PipelineFolderImpl.  # noqa: E501
        :type _class: str
        :param display_name: The display_name of this PipelineFolderImpl.  # noqa: E501
        :type display_name: str
        :param full_name: The full_name of this PipelineFolderImpl.  # noqa: E501
        :type full_name: str
        :param name: The name of this PipelineFolderImpl.  # noqa: E501
        :type name: str
        :param organization: The organization of this PipelineFolderImpl.  # noqa: E501
        :type organization: str
        :param number_of_folders: The number_of_folders of this PipelineFolderImpl.  # noqa: E501
        :type number_of_folders: int
        :param number_of_pipelines: The number_of_pipelines of this PipelineFolderImpl.  # noqa: E501
        :type number_of_pipelines: int
        """
        self.openapi_types = {
            '_class': str,
            'display_name': str,
            'full_name': str,
            'name': str,
            'organization': str,
            'number_of_folders': int,
            'number_of_pipelines': int
        }

        self.attribute_map = {
            '_class': '_class',
            'display_name': 'displayName',
            'full_name': 'fullName',
            'name': 'name',
            'organization': 'organization',
            'number_of_folders': 'numberOfFolders',
            'number_of_pipelines': 'numberOfPipelines'
        }

        self.__class = _class
        self._display_name = display_name
        self._full_name = full_name
        self._name = name
        self._organization = organization
        self._number_of_folders = number_of_folders
        self._number_of_pipelines = number_of_pipelines

    @classmethod
    def from_dict(cls, dikt) -> 'PipelineFolderImpl':
        """Returns the dict as a model

        :param dikt: A dict.
        :type: dict
        :return: The PipelineFolderImpl of this PipelineFolderImpl.  # noqa: E501
        :rtype: PipelineFolderImpl
        """
        return util.deserialize_model(dikt, cls)

    @property
    def _class(self):
        """Gets the _class of this PipelineFolderImpl.

        :return: The _class of this PipelineFolderImpl.
        :rtype: str
        """
        return self.__class

    @_class.setter
    def _class(self, _class):
        """Sets the _class of this PipelineFolderImpl.

        :param _class: The _class of this PipelineFolderImpl.
        :type _class: str
        """

        self.__class = _class

    @property
    def display_name(self):
        """Gets the display_name of this PipelineFolderImpl.

        :return: The display_name of this PipelineFolderImpl.
        :rtype: str
        """
        return self._display_name

    @display_name.setter
    def display_name(self, display_name):
        """Sets the display_name of this PipelineFolderImpl.

        :param display_name: The display_name of this PipelineFolderImpl.
        :type display_name: str
        """

        self._display_name = display_name

    @property
    def full_name(self):
        """Gets the full_name of this PipelineFolderImpl.

        :return: The full_name of this PipelineFolderImpl.
        :rtype: str
        """
        return self._full_name

    @full_name.setter
    def full_name(self, full_name):
        """Sets the full_name of this PipelineFolderImpl.

        :param full_name: The full_name of this PipelineFolderImpl.
        :type full_name: str
        """

        self._full_name = full_name

    @property
    def name(self):
        """Gets the name of this PipelineFolderImpl.

        :return: The name of this PipelineFolderImpl.
        :rtype: str
        """
        return self._name

    @name.setter
    def name(self, name):
        """Sets the name of this PipelineFolderImpl.

        :param name: The name of this PipelineFolderImpl.
        :type name: str
        """

        self._name = name

    @property
    def organization(self):
        """Gets the organization of this PipelineFolderImpl.

        :return: The organization of this PipelineFolderImpl.
        :rtype: str
        """
        return self._organization

    @organization.setter
    def organization(self, organization):
        """Sets the organization of this PipelineFolderImpl.

        :param organization: The organization of this PipelineFolderImpl.
        :type organization: str
        """

        self._organization = organization

    @property
    def number_of_folders(self):
        """Gets the number_of_folders of this PipelineFolderImpl.

        :return: The number_of_folders of this PipelineFolderImpl.
        :rtype: int
        """
        return self._number_of_folders

    @number_of_folders.setter
    def number_of_folders(self, number_of_folders):
        """Sets the number_of_folders of this PipelineFolderImpl.

        :param number_of_folders: The number_of_folders of this PipelineFolderImpl.
        :type number_of_folders: int
        """

        self._number_of_folders = number_of_folders

    @property
    def number_of_pipelines(self):
        """Gets the number_of_pipelines of this PipelineFolderImpl.

        :return: The number_of_pipelines of this PipelineFolderImpl.
        :rtype: int
        """
        return self._number_of_pipelines

    @number_of_pipelines.setter
    def number_of_pipelines(self, number_of_pipelines):
        """Sets the number_of_pipelines of this PipelineFolderImpl.

        :param number_of_pipelines: The number_of_pipelines of this PipelineFolderImpl.
        :type number_of_pipelines: int
        """

        self._number_of_pipelines = number_of_pipelines


text:
using NUnit.Framework;
using ServiceStack.Common;
using ServiceStack.ServiceClient.Web;

namespace ServiceStack.WebHost.IntegrationTests.Tests
{
	[TestFixture]
	public class FilterTests
	{
		[Test]
		public void Can_call_service_returning_string()
		{
			var response = Config.ServiceStackBaseUri.CombineWith("hello2/world")
				.DownloadJsonFromUrl();

			Assert.That(response, Is.EqualTo("world"));
		}
	}
}


text:
```groovy
    // core 核心库, 格式:jar和aar
    compile 'com.mcxiaoke.next:core:1.+'
```

## 缓存

```java

        // create memory cache, internally using map
        final IMemoryCache<String,String> memoryCache= MemoryCache.mapCache();
        // create memory cache, internally using lru cache
        // final IMemoryCache<String,String> memoryCache= MemoryCache.lruCache(100);

        memoryCache.put("strKey", "value");
        memoryCache.put("intKey", 123);
        memoryCache.put("boolKey", false);
        memoryCache.put("objKey", new TaskQueue());
        memoryCache.put("boolKey", false);
        // expires in 300 seconds
        memoryCache.put("canExpireKey", "hello, world", 300*1000L);
        final String value = memoryCache.get("strKey");

        final Context context = mockContext();
        // default disc cache, use /data/data/package-name/cache/.disc/ dir
        final DiscCache discCache = new DiscCache(context);
        // use custom /data/data/package-name/cache/json-cache/ dir
        //final DiscCache discCache=new DiscCache(context,"json-cache");
        // use custom /sdcard/Android/data/package-name/cache/json-cache/ dir
        //final DiscCache discCache=new DiscCache(context,"json-cache",DiscCache.MODE_EXTERNAL);

        discCache.setCacheDir("dirName");
        discCache.setCharset("UTF-8");
        discCache.setFileNameGenerator(nameGenerator);
        final byte[] bytes = new byte[100];
        discCache.put("bytes", bytes);
        discCache.put("stream", new ByteArrayInputStream(bytes));
        discCache.put("text", "some text for cache");

        final byte[] bytesValue = discCache.getBytes("bytes");
        final File file = discCache.getFile("stream");
        final String stringValue = discCache.get("text");
        discCache.remove("cacheKey");
        discCache.clear();
        discCache.delete(new FileFilter() {
            @Override
            public boolean accept(final File pathname) {
                return false;
            }
        });

```


text:
package ca.ucalgary.algorithms;

import ca.ucalgary.mapgraph.Intersection;
import static ca.ucalgary.mapgraph.Intersection.*;
import ca.ucalgary.mapgraph.MapGraph;
import ca.ucalgary.mapgraph.Way;
import ca.ucalgary.ui.ZoneBoundary;
import org.jgrapht.alg.EdmondsKarpMaximumFlow;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;

import java.util.*;
import java.util.stream.Stream;

public class MaxFlowAlgorithm implements EvacuationAlgorithm {

    @Override
    public HashMap<Intersection, ProportionalLoadDistributor> solve(MapGraph mapGraph, Set<ZoneBoundary> hotZones, Set<ZoneBoundary> safeZones) {
        double infCap = 100000;

        Collection<Intersection> intersections = mapGraph.getIntersections();
        SimpleDirectedWeightedGraph<Intersection, DefaultWeightedEdge> g = new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);

        g.addVertex(SOURCE);
        g.addVertex(TARGET);
        intersections.forEach(g::addVertex);

        for (Way way : mapGraph.getWays()) {
            double capacity = way.getType().getCapacity();
            ArrayList<Intersection> wayInts = way.getIntersections();

            for (int i = 1; i < wayInts.size(); i++) {
                Intersection u = wayInts.get(i - 1);
                Intersection v = wayInts.get(i);

                try {
                    DefaultWeightedEdge e1 = g.addEdge(u, v);
                    if (e1 != null) {
                        g.setEdgeWeight(e1, capacity);
                    }
                } catch (IllegalArgumentException e) {
                    System.out.println(e);
                }

                try {
                    DefaultWeightedEdge e2 = g.addEdge(v, u);
                    if (e2 != null) {
                        g.setEdgeWeight(e2, capacity);
                    }
                } catch (IllegalArgumentException e) {
                    System.out.println(e);
                }
            }
        }

        for (Intersection intersection : intersections) {
            if (intersection.isInZones(safeZones)) {
                DefaultWeightedEdge e = g.addEdge(intersection, TARGET);
                g.setEdgeWeight(e, infCap);
            } else if (intersection.isInZones(hotZones)) {
                DefaultWeightedEdge e = g.addEdge(SOURCE, intersection);
                g.setEdgeWeight(e, infCap);
            }
        }

        EdmondsKarpMaximumFlow<Intersection, DefaultWeightedEdge> maxFlow = new EdmondsKarpMaximumFlow<>(g, 0.001);
        maxFlow.calculateMaximumFlow(SOURCE, TARGET);

        Map<DefaultWeightedEdge, Double> linksFlow = maxFlow.getMaximumFlow();
        Map<Intersection, List<Map.Entry<DefaultWeightedEdge, Double>>> grouped = new HashMap<>();

        linksFlow.entrySet().forEach(e -> {
            Intersection from = g.getEdgeSource(e.getKey());
            List<Map.Entry<DefaultWeightedEdge, Double>> list = grouped.getOrDefault(from, new ArrayList<>());
            list.add(e);
            grouped.put(from, list);
        });

        HashMap<Intersection, ProportionalLoadDistributor> distMap = new HashMap<>();

        grouped.entrySet().forEach(group -> {
            Intersection from = group.getKey();
            int n = group.getValue().size();
            Intersection tos[] = getTos(group.getValue().stream().map(Map.Entry::getKey), g);
            double[] flows = group.getValue().stream().mapToDouble(Map.Entry::getValue).toArray();
            if (flows.length > 0) {
                distMap.put(from, new ProportionalLoadDistributor(tos, flows));
            }
        });

        return distMap;
    }

    private Intersection[] getTos(Stream<DefaultWeightedEdge> stream, SimpleDirectedWeightedGraph<Intersection, DefaultWeightedEdge> g) {
        Object[] arr = stream.toArray();
        Intersection ends[] = new Intersection[arr.length];

        for (int i = 0; i < arr.length; i++) {
            Intersection end = g.getEdgeTarget((DefaultWeightedEdge) arr[i]);
            ends[i] = end;
        }

        return ends;
    }
}