text:
local log = require "util.logger".init("stanzarouter")

local hosts = _G.prosody.hosts;
local tostring = tostring;
local st = require "util.stanza";
local jid_split = require "util.jid".split;
local jid_prepped_split = require "util.jid".prepped_split;

local full_sessions = _G.prosody.full_sessions;
local bare_sessions = _G.prosody.bare_sessions;

local core_post_stanza, core_process_stanza, core_route_stanza;

function deprecated_warning(f)
	_G[f] = function(...)
		log("warn", "Using the global %s() is deprecated, use module:send() or prosody.%s(). %s", f, f, debug.traceback());
		return prosody[f](...);
	end
end
deprecated_warning"core_post_stanza";
deprecated_warning"core_process_stanza";
deprecated_warning"core_route_stanza";

local function handle_unhandled_stanza(host, origin, stanza)
	local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns or "jabber:client", origin.type;
	if name == "iq" and xmlns == "jabber:client" then
		if stanza.attr.type == "get" or stanza.attr.type == "set" then
			xmlns = stanza.tags[1].attr.xmlns or "jabber:client";
			log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
		else
			log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
			return true;
		end
	end
	if stanza.attr.xmlns == nil and origin.send then
		log("debug", "Unhandled %s stanza: %s; xmlns=%s", origin.type, stanza.name, xmlns); -- we didn't handle it
		if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
			origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
		end
	elseif not((name == "features" or name == "error") and xmlns == "http://etherx.jabber.org/streams") then -- FIXME remove check once we handle S2S features
		log("warn", "Unhandled %s stream element or stanza: %s; xmlns=%s: %s", origin.type, stanza.name, xmlns, tostring(stanza)); -- we didn't handle it
		origin:close("unsupported-stanza-type");
	end
end

local iq_types = { set=true, get=true, result=true, error=true };
function core_process_stanza(origin, stanza)
	(origin.log or log)("debug", "Received[%s]: %s", origin.type, stanza:top_tag())

	-- TODO verify validity of stanza (as well as JID validity)
	if stanza.attr.type == "error" and #stanza.tags == 0 then return; end -- TODO invalid stanza, log
	if stanza.name == "iq" then
		if not stanza.attr.id then stanza.attr.id = ""; end -- COMPAT Jabiru doesn't send the id attribute on roster requests
		if not iq_types[stanza.attr.type] or ((stanza.attr.type == "set" or stanza.attr.type == "get") and (#stanza.tags ~= 1)) then
			origin.send(st.error_reply(stanza, "modify", "bad-request", "Invalid IQ type or incorrect number of children"));
			return;
		end
	end

	if origin.type == "c2s" and not stanza.attr.xmlns then
		if not origin.full_jid
			and not(stanza.name == "iq" and stanza.attr.type == "set" and stanza.tags[1] and stanza.tags[1].name == "bind"
					and stanza.tags[1].attr.xmlns == "urn:ietf:params:xml:ns:xmpp-bind") then
			-- authenticated client isn't bound and current stanza is not a bind request
			if stanza.attr.type ~= "result" and stanza.attr.type ~= "error" then
				origin.send(st.error_reply(stanza, "auth", "not-authorized")); -- FIXME maybe allow stanzas to account or server
			end
			return;
		end

		-- TODO also, stanzas should be returned to their original state before the function ends
		stanza.attr.from = origin.full_jid;
	end
	local to, xmlns = stanza.attr.to, stanza.attr.xmlns;
	local from = stanza.attr.from;
	local node, host, resource;
	local from_node, from_host, from_resource;
	local to_bare, from_bare;
	if to then
		if full_sessions[to] or bare_sessions[to] or hosts[to] then
			node, host = jid_split(to); -- TODO only the host is needed, optimize
		else
			node, host, resource = jid_prepped_split(to);
			if not host then
				log("warn", "Received stanza with invalid destination JID: %s", to);
				if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
					origin.send(st.error_reply(stanza, "modify", "jid-malformed", "The destination address is invalid: "..to));
				end
				return;
			end
			to_bare = node and (node.."@"..host) or host; -- bare JID
			if resource then to = to_bare.."/"..resource; else to = to_bare; end
			stanza.attr.to = to;
		end
	end
	if from and not origin.full_jid then
		-- We only stamp the 'from' on c2s stanzas, so we still need to check validity
		from_node, from_host, from_resource = jid_prepped_split(from);
		if not from_host then
			log("warn", "Received stanza with invalid source JID: %s", from);
			if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
				origin.send(st.error_reply(stanza, "modify", "jid-malformed", "The source address is invalid: "..from));
			end
			return;
		end
		from_bare = from_node and (from_node.."@"..from_host) or from_host; -- bare JID
		if from_resource then from = from_bare.."/"..from_resource; else from = from_bare; end
		stanza.attr.from = from;
	end

	if (origin.type == "s2sin" or origin.type == "c2s" or origin.type == "component") and xmlns == nil then
		if origin.type == "s2sin" and not origin.dummy then
			local host_status = origin.hosts[from_host];
			if not host_status or not host_status.authed then -- remote server trying to impersonate some other server?
				log("warn", "Received a stanza claiming to be from %s, over a stream authed for %s!", from_host, origin.from_host);
				origin:close("not-authorized");
				return;
			elseif not hosts[host] then
				log("warn", "Remote server %s sent us a stanza for %s, closing stream", origin.from_host, host);
				origin:close("host-unknown");
				return;
			end
		end
		core_post_stanza(origin, stanza, origin.full_jid);
	else
		local h = hosts[stanza.attr.to or origin.host or origin.to_host];
		if h then
			local event;
			if xmlns == nil then
				if stanza.name == "iq" and (stanza.attr.type == "set" or stanza.attr.type == "get") then
					event = "stanza/iq/"..stanza.tags[1].attr.xmlns..":"..stanza.tags[1].name;
				else
					event = "stanza/"..stanza.name;
				end
			else
				event = "stanza/"..xmlns..":"..stanza.name;
			end
			if h.events.fire_event(event, {origin = origin, stanza = stanza}) then return; end
		end
		if host and not hosts[host] then host = nil; end -- COMPAT: workaround for a Pidgin bug which sets 'to' to the SRV result
		handle_unhandled_stanza(host or origin.host or origin.to_host, origin, stanza);
	end
end

function core_post_stanza(origin, stanza, preevents)
	local to = stanza.attr.to;
	local node, host, resource = jid_split(to);
	local to_bare = node and (node.."@"..host) or host; -- bare JID

	local to_type, to_self;
	if node then
		if resource then
			to_type = '/full';
		else
			to_type = '/bare';
			if node == origin.username and host == origin.host then
				stanza.attr.to = nil;
				to_self = true;
			end
		end
	else
		if host then
			to_type = '/host';
		else
			to_type = '/bare';
			to_self = true;
		end
	end

	local event_data = {origin=origin, stanza=stanza};
	if preevents then -- c2s connection
		if hosts[origin.host].events.fire_event('pre-'..stanza.name..to_type, event_data) then return; end -- do preprocessing
	end
	local h = hosts[to_bare] or hosts[host or origin.host];
	if h then
		if h.events.fire_event(stanza.name..to_type, event_data) then return; end -- do processing
		if to_self and h.events.fire_event(stanza.name..'/self', event_data) then return; end -- do processing
		handle_unhandled_stanza(h.host, origin, stanza);
	else
		core_route_stanza(origin, stanza);
	end
end

function core_route_stanza(origin, stanza)
	local node, host, resource = jid_split(stanza.attr.to);
	local from_node, from_host, from_resource = jid_split(stanza.attr.from);

	-- Auto-detect origin if not specified
	origin = origin or hosts[from_host];
	if not origin then return false; end

	if hosts[host] then
		-- old stanza routing code removed
		core_post_stanza(origin, stanza);
	else
		log("debug", "Routing to remote...");
		local host_session = hosts[from_host];
		if not host_session then
			log("error", "No hosts[from_host] (please report): %s", tostring(stanza));
		else
			local xmlns = stanza.attr.xmlns;
			stanza.attr.xmlns = nil;
			local routed = host_session.events.fire_event("route/remote", { origin = origin, stanza = stanza, from_host = from_host, to_host = host });
			stanza.attr.xmlns = xmlns; -- reset
			if not routed then
				log("debug", "... no, just kidding.");
				if stanza.attr.type == "error" or (stanza.name == "iq" and stanza.attr.type == "result") then return; end
				core_route_stanza(host_session, st.error_reply(stanza, "cancel", "not-allowed", "Communication with remote domains is not enabled"));
			end
		end
	end
end
prosody.core_process_stanza = core_process_stanza;
prosody.core_post_stanza = core_post_stanza;
prosody.core_route_stanza = core_route_stanza;


text:
import os.path as path
from datetime import datetime, date, timedelta

from flask import (
    render_template, Response, request, session, redirect, url_for, flash,
    send_from_directory, g)
from flask.ext.login import (
    current_user, login_user, logout_user, login_required, UserMixin)
from passlib.hash import bcrypt

from app_mailreg import app, login_manager, db
from app_mailreg.forms import *
from app_mailreg.models import *

class User(UserMixin):

    def is_authenticated(self):
        return True

    def is_active(self):
        return self.userdb.active

    def is_anonymous(self):
        return self.anonymous

    def get_id(self):
        return self.id

    def authenticate(self):
        try:
            return bcrypt.verify(self.password, self.userdb.hash)
        except Exception:
            return False

    def __init__(self, id, password=None, userdb=None):
        self.id = unicode(id)
        self.userdb = userdb if userdb else UserDB.query.filter_by(
            name_user=self.id).first()
        self.anonymous = False if self.userdb else True
        self.password = password

@login_manager.user_loader
def load_user(id):
    u = UserDB.query.filter_by(name_user=id).first()
    return User(u.name_user, userdb=u) if u else None

@app.route("/login", methods=["GET", "POST"])
def login():
    form = LoginForm(request.form)
    if request.method == "POST":
        u = User(request.form["username"], password=request.form["password"])
        if u.anonymous:
            flash("Login failed: username not recognized or invalid password")
        else:
            if u.authenticate():
                login_user(u, remember=True)
                flash("Login successful")
                return redirect(url_for("index"))
            else:
                flash("Login failed: username not recognized or invalid password")
    return render_template("login.html", user=current_user, form=form)

@app.route("/logout")
@login_required
def logout():
    logout_user()
    flash("You had been logged out")
    return redirect(url_for("index"))

login_manager.login_view = "login"

@app.route("/")
def index():
    return render_template("base_template.html", current_user=current_user)

@app.route("/register", methods=["GET", "POST"])
def register():
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        flash("Registration successful")
        return redirect(url_for("index"))
    return render_template("register.html", form=form)

@app.route("/admin")
@login_required
def admin():
    return ""

@app.route("/favicon.ico")
def favicon():
    """Fallback for serving favicon.ico on older browsers not supporting
    <link> tags and expecting the icon file from application root.

    """
    return send_from_directory(
        path.join(app.root_path, "static"),
        "favicon.ico",
        mimetype="image/vnd.microsoft.icon")

redpajama_set_name: RedPajamaGithub


text:
void kll::FlatShader::Reload()
{
    mShader.unload();

    const string SHADER_NAME = "shaders/flat";
    bool loaded = mShader.load(SHADER_NAME);
}

void kll::FlatShader::Begin()
{
    mShader.begin();
}

void kll::FlatShader::End()
{
    mShader.end();
}


text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test;

import android.test.suitebuilder.annotation.MediumTest;

import org.chromium.android_webview.AwContents;
import org.chromium.android_webview.test.util.CommonResources;
import org.chromium.android_webview.test.util.JSUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer;
import org.chromium.net.test.util.TestWebServer;

import java.util.concurrent.CountDownLatch;

/**
 * Tests for the ContentViewClient.onPageFinished() method.
 */
public class ClientOnPageFinishedTest extends AwTestBase {

    private TestAwContentsClient mContentsClient;
    private AwContents mAwContents;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        setTestAwContentsClient(new TestAwContentsClient());
    }

    private void setTestAwContentsClient(TestAwContentsClient contentsClient) throws Exception {
        mContentsClient = contentsClient;
        final AwTestContainerView testContainerView =
                createAwTestContainerViewOnMainSync(mContentsClient);
        mAwContents = testContainerView.getAwContents();
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testPassesCorrectUrl() throws Throwable {
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mContentsClient.getOnPageFinishedHelper();

        String html = "Simple page.";
        int currentCallCount = onPageFinishedHelper.getCallCount();
        loadDataAsync(mAwContents, html, "text/html", false);

        onPageFinishedHelper.waitForCallback(currentCallCount);
        assertEquals("data:text/html," + html, onPageFinishedHelper.getUrl());
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testCalledAfterError() throws Throwable {
        class LocalTestClient extends TestAwContentsClient {
            private boolean mIsOnReceivedErrorCalled = false;
            private boolean mIsOnPageFinishedCalled = false;
            private boolean mAllowAboutBlank = false;

            @Override
            public void onReceivedError(int errorCode, String description, String failingUrl) {
                assertEquals("onReceivedError called twice for " + failingUrl,
                        false, mIsOnReceivedErrorCalled);
                mIsOnReceivedErrorCalled = true;
                assertEquals("onPageFinished called before onReceivedError for " + failingUrl,
                        false, mIsOnPageFinishedCalled);
                super.onReceivedError(errorCode, description, failingUrl);
            }

            @Override
            public void onPageFinished(String url) {
                if (mAllowAboutBlank && "about:blank".equals(url)) {
                    super.onPageFinished(url);
                    return;
                }
                assertEquals("onPageFinished called twice for " + url,
                        false, mIsOnPageFinishedCalled);
                mIsOnPageFinishedCalled = true;
                assertEquals("onReceivedError not called before onPageFinished for " + url,
                        true, mIsOnReceivedErrorCalled);
                super.onPageFinished(url);
            }

            void setAllowAboutBlank() {
                mAllowAboutBlank = true;
            }
        }
        LocalTestClient testContentsClient = new LocalTestClient();
        setTestAwContentsClient(testContentsClient);

        TestCallbackHelperContainer.OnReceivedErrorHelper onReceivedErrorHelper =
                mContentsClient.getOnReceivedErrorHelper();
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mContentsClient.getOnPageFinishedHelper();

        String invalidUrl = "http://localhost:7/non_existent";
        loadUrlSync(mAwContents, onPageFinishedHelper, invalidUrl);

        assertEquals(invalidUrl, onReceivedErrorHelper.getFailingUrl());
        assertEquals(invalidUrl, onPageFinishedHelper.getUrl());

        // Rather than wait a fixed time to see that another onPageFinished callback isn't issued
        // we load a valid page. Since callbacks arrive sequentially, this will ensure that
        // any extra calls of onPageFinished / onReceivedError will arrive to our client.
        testContentsClient.setAllowAboutBlank();
        loadUrlSync(mAwContents, onPageFinishedHelper, "about:blank");
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testCalledAfterRedirectedUrlIsOverridden() throws Throwable {
        /*
         * If url1 is redirected url2, and url2 load is overridden, onPageFinished should still be
         * called for url2.
         * Steps:
         * 1. load url1. url1 onPageStarted
         * 2. server redirects url1 to url2. url2 onPageStarted
         * 3. shouldOverridedUrlLoading called for url2 and returns true
         * 4. url2 onPageFinishedCalled
         */

        TestWebServer webServer = TestWebServer.start();
        try {
            final String redirectTargetPath = "/redirect_target.html";
            final String redirectTargetUrl = webServer.setResponse(redirectTargetPath,
                    "hello world", null);
            final String redirectUrl = webServer.setRedirect("/302.html", redirectTargetUrl);

            final TestAwContentsClient.ShouldOverrideUrlLoadingHelper urlOverrideHelper =
                    mContentsClient.getShouldOverrideUrlLoadingHelper();
            // Override the load of redirectTargetUrl
            urlOverrideHelper.setShouldOverrideUrlLoadingReturnValue(true);

            TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                    mContentsClient.getOnPageFinishedHelper();

            final int currentOnPageFinishedCallCount = onPageFinishedHelper.getCallCount();
            loadUrlAsync(mAwContents, redirectUrl);

            onPageFinishedHelper.waitForCallback(currentOnPageFinishedCallCount);
            // onPageFinished needs to be called for redirectTargetUrl, but not for redirectUrl
            assertEquals(redirectTargetUrl, onPageFinishedHelper.getUrl());
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testNotCalledForValidSubresources() throws Throwable {
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mContentsClient.getOnPageFinishedHelper();

        TestWebServer webServer = TestWebServer.start();
        try {
            final String testHtml = "HeaderBody";
            final String testPath = "/test.html";
            final String syncPath = "/sync.html";

            final String testUrl = webServer.setResponse(testPath, testHtml, null);
            final String syncUrl = webServer.setResponse(syncPath, testHtml, null);

            assertEquals(0, onPageFinishedHelper.getCallCount());
            final int pageWithSubresourcesCallCount = onPageFinishedHelper.getCallCount();
            loadDataAsync(mAwContents,
                          "",
                          "text/html",
                          false);

            onPageFinishedHelper.waitForCallback(pageWithSubresourcesCallCount);

            // Rather than wait a fixed time to see that an onPageFinished callback isn't issued
            // we load another valid page. Since callbacks arrive sequentially if the next callback
            // we get is for the synchronizationUrl we know that the previous load did not schedule
            // a callback for the iframe.
            final int synchronizationPageCallCount = onPageFinishedHelper.getCallCount();
            loadUrlAsync(mAwContents, syncUrl);

            onPageFinishedHelper.waitForCallback(synchronizationPageCallCount);
            assertEquals(syncUrl, onPageFinishedHelper.getUrl());
            assertEquals(2, onPageFinishedHelper.getCallCount());
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testNotCalledForHistoryApi() throws Throwable {
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mContentsClient.getOnPageFinishedHelper();
        enableJavaScriptOnUiThread(mAwContents);

        TestWebServer webServer = TestWebServer.start();
        try {
            final String testHtml = "HeaderBody";
            final String testPath = "/test.html";
            final String historyPath = "/history.html";
            final String syncPath = "/sync.html";

            final String testUrl = webServer.setResponse(testPath, testHtml, null);
            final String historyUrl = webServer.getResponseUrl(historyPath);
            final String syncUrl = webServer.setResponse(syncPath, testHtml, null);

            assertEquals(0, onPageFinishedHelper.getCallCount());
            loadUrlSync(mAwContents, onPageFinishedHelper, testUrl);

            executeJavaScriptAndWaitForResult(mAwContents, mContentsClient,
                    "history.pushState(null, null, '" + historyUrl + "');");

            // Rather than wait a fixed time to see that an onPageFinished callback isn't issued
            // we load another valid page. Since callbacks arrive sequentially if the next callback
            // we get is for the synchronizationUrl we know that the previous load did not schedule
            // a callback for the iframe.
            final int synchronizationPageCallCount = onPageFinishedHelper.getCallCount();
            loadUrlAsync(mAwContents, syncUrl);

            onPageFinishedHelper.waitForCallback(synchronizationPageCallCount);
            assertEquals(syncUrl, onPageFinishedHelper.getUrl());
            assertEquals(2, onPageFinishedHelper.getCallCount());
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testCalledForHrefNavigations() throws Throwable {
        doTestOnPageFinishedCalledForHrefNavigations(false);
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testCalledForHrefNavigationsWithBaseUrl() throws Throwable {
        doTestOnPageFinishedCalledForHrefNavigations(true);
    }

    private void doTestOnPageFinishedCalledForHrefNavigations(boolean useBaseUrl) throws Throwable {
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mContentsClient.getOnPageFinishedHelper();
        TestCallbackHelperContainer.OnPageStartedHelper onPageStartedHelper =
                mContentsClient.getOnPageStartedHelper();
        enableJavaScriptOnUiThread(mAwContents);

        TestWebServer webServer = TestWebServer.start();
        try {
            final String testHtml = CommonResources.makeHtmlPageFrom("",
                    "anchor");
            final String testPath = "/test.html";
            final String testUrl = webServer.setResponse(testPath, testHtml, null);

            if (useBaseUrl) {
                loadDataWithBaseUrlSync(mAwContents, onPageFinishedHelper,
                        testHtml, "text/html", false, webServer.getBaseUrl(), null);
            } else {
                loadUrlSync(mAwContents, onPageFinishedHelper, testUrl);
            }

            int onPageFinishedCallCount = onPageFinishedHelper.getCallCount();
            int onPageStartedCallCount = onPageStartedHelper.getCallCount();

            JSUtils.clickOnLinkUsingJs(this, mAwContents,
                    mContentsClient.getOnEvaluateJavaScriptResultHelper(), "link");

            onPageFinishedHelper.waitForCallback(onPageFinishedCallCount);
            assertEquals(onPageStartedCallCount, onPageStartedHelper.getCallCount());

            onPageFinishedCallCount = onPageFinishedHelper.getCallCount();
            onPageStartedCallCount = onPageStartedHelper.getCallCount();

            executeJavaScriptAndWaitForResult(mAwContents, mContentsClient,
                    "window.history.go(-1)");

            onPageFinishedHelper.waitForCallback(onPageFinishedCallCount);
            assertEquals(onPageStartedCallCount, onPageStartedHelper.getCallCount());
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testNotCalledOnDomModificationForBlankWebView() throws Throwable {
        TestWebServer webServer = TestWebServer.start();
        try {
            doTestOnPageFinishedNotCalledOnDomMutation(webServer, null);
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testNotCalledOnDomModificationAfterNonCommittedLoadFromApi()
            throws Throwable {
        enableJavaScriptOnUiThread(mAwContents);
        TestWebServer webServer = TestWebServer.start();
        try {
            final String noContentUrl = webServer.setResponseWithNoContentStatus("/nocontent.html");
            loadUrlAsync(mAwContents, noContentUrl);
            doTestOnPageFinishedNotCalledOnDomMutation(webServer, noContentUrl);
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testNotCalledOnDomModificationWithJavascriptUrlAfterNonCommittedLoadFromApi()
            throws Throwable {
        enableJavaScriptOnUiThread(mAwContents);
        TestWebServer webServer = TestWebServer.start();
        try {
            final CountDownLatch latch = new CountDownLatch(1);
            final String url = webServer.setResponseWithRunnableAction(
                    "/about.html", CommonResources.ABOUT_HTML, null,
                    new Runnable() {
                        @Override
                        public void run() {
                            try {
                                latch.await(WAIT_TIMEOUT_MS,
                                        java.util.concurrent.TimeUnit.MILLISECONDS);
                            } catch (InterruptedException e) {
                                fail("Caught InterruptedException " + e);
                            }
                        }
                    });
            TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                    mContentsClient.getOnPageFinishedHelper();
            final int onPageFinishedCallCount = onPageFinishedHelper.getCallCount();
            loadUrlAsync(mAwContents, url);
            loadUrlAsync(mAwContents,
                    "javascript:(function(){document.body.innerHTML='Hello,%20World!';})()");
            stopLoading(mAwContents);
            // We now have 3 possible outcomes:
            //  - the good one -- onPageFinished only fires for the first load;
            //  - two bad ones:
            //      - onPageFinished fires for the dom mutation, then for the first load. (1)
            //      - onPageFinished fires for the first load, then for the dom mutation; (2)
            // We verify that (1) doesn't happen with the code below. Then we load a sync page,
            // and make sure that we are getting onPageFinished for the sync page, not due
            // to the dom mutation, thus verifying that (2) doesn't happen as well.
            onPageFinishedHelper.waitForCallback(onPageFinishedCallCount);
            assertEquals(url, onPageFinishedHelper.getUrl());
            assertEquals(onPageFinishedCallCount + 1, onPageFinishedHelper.getCallCount());
            latch.countDown();  // Release the server.
            final String syncUrl = webServer.setResponse("/sync.html", "", null);
            loadUrlAsync(mAwContents, syncUrl);
            onPageFinishedHelper.waitForCallback(onPageFinishedCallCount + 1);
            assertEquals(syncUrl, onPageFinishedHelper.getUrl());
            assertEquals(onPageFinishedCallCount + 2, onPageFinishedHelper.getCallCount());
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testNotCalledOnDomModificationAfterLoadUrl() throws Throwable {
        TestWebServer webServer = TestWebServer.start();
        try {
            final String testUrl =
                    webServer.setResponse("/test.html", CommonResources.ABOUT_HTML, null);
            loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), testUrl);
            doTestOnPageFinishedNotCalledOnDomMutation(webServer, null);
        } finally {
            webServer.shutdown();
        }
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testNotCalledOnDomModificationAfterLoadData()
            throws Throwable {
        TestWebServer webServer = TestWebServer.start();
        try {
            loadDataSync(mAwContents, mContentsClient.getOnPageFinishedHelper(),
                    CommonResources.ABOUT_HTML, "text/html", false);
            doTestOnPageFinishedNotCalledOnDomMutation(webServer, null);
        } finally {
            webServer.shutdown();
        }
    }

    private void doTestOnPageFinishedNotCalledOnDomMutation(TestWebServer webServer, String syncUrl)
            throws Throwable {
        enableJavaScriptOnUiThread(mAwContents);
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mContentsClient.getOnPageFinishedHelper();
        final int onPageFinishedCallCount = onPageFinishedHelper.getCallCount();
        // Mutate DOM.
        executeJavaScriptAndWaitForResult(mAwContents, mContentsClient,
                "document.body.innerHTML='Hello, World!'");
        // Rather than wait a fixed time to see that an onPageFinished callback isn't issued
        // we load another valid page. Since callbacks arrive sequentially if the next callback
        // we get is for the synchronizationUrl we know that DOM mutation did not schedule
        // a callback for the iframe.
        if (syncUrl == null) {
            syncUrl = webServer.setResponse("/sync.html", "", null);
            loadUrlAsync(mAwContents, syncUrl);
        }
        onPageFinishedHelper.waitForCallback(onPageFinishedCallCount);
        assertEquals(syncUrl, onPageFinishedHelper.getUrl());
        assertEquals(onPageFinishedCallCount + 1, onPageFinishedHelper.getCallCount());
    }

    @MediumTest
    @Feature({"AndroidWebView"})
    public void testCalledAfter204Reply() throws Throwable {
        TestWebServer webServer = TestWebServer.start();
        try {
            final String url = webServer.setResponseWithNoContentStatus("/page.html");
            TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                    mContentsClient.getOnPageFinishedHelper();
            int currentCallCount = onPageFinishedHelper.getCallCount();
            loadUrlAsync(mAwContents, url);
            onPageFinishedHelper.waitForCallback(currentCallCount);
            assertEquals(url, onPageFinishedHelper.getUrl());
        } finally {
            webServer.shutdown();
        }
    }
}


text:
ClassFileStream* ClassPathDirEntry::open_stream(std::string name) {
	std::string filename = path() + "/" + name;
	std::ifstream ifs(filename, std::ios::binary);
	ifs.seekg(0, ifs.end);
	int len = ifs.tellg();
	ifs.seekg(0,ifs.beg);
	char* buffer = new char[len];
	ifs.read(buffer, len);
	return new ClassFileStream(name, (byte*)buffer, (byte*)buffer + len);
}

ClassFileStream* ClassPathZipEntry::open_stream(std::string name){
	int err = 0;
	zip* z = zip_open(path().c_str(), 0, &err);
	struct zip_stat stat;
	zip_stat_init(&stat);
	zip_stat(z, name.c_str(), 0, &stat);

	char* buffer = new char[stat.size];
	zip_file* file = zip_fopen(z, name.c_str(), 0);
	zip_fread(file, buffer, stat.size);
	zip_fclose(file);
	return new ClassFileStream(name, (byte*)buffer, (byte*)buffer + stat.size);
}

ClassLoader::ClassLoader(Metadata* meta, std::string path, ClassLoader* father, bool jar):meta_(meta),father_(father){
	if (!jar){
		entry_ = new ClassPathDirEntry(path);
		return;
	}
	struct dirent* file;
    DIR* dir= opendir(path.c_str());
	ClassPathEntry* current = nullptr;
    while (file = readdir(dir)){
        std::string filename = file->d_name;
        if(filename.find(".jar") != std::string::npos){
			ClassPathEntry* zip_entry = new ClassPathZipEntry(path + "/" + filename);
			if(!entry_){
				entry_ = current = zip_entry;
			}else{
				current->next = zip_entry;
				current = zip_entry;
			}
		}
    }
    closedir(dir);
}

ClassPathEntry* ClassLoader::exist(std::string name){
	ClassPathEntry* entry = entry_;
	while(entry){
		std::string path = entry->path();
		if (entry->is_jar_file()){
			int err = 0;
			zip* z = zip_open(path.c_str(), 0, &err);
			int value = zip_name_locate(z, name.c_str(), ZIP_FL_NOCASE);
			if (value != -1) return entry;
		}else{
			std::ifstream stream(path + "/" + name);
			if(stream) return entry;
		}
		entry = entry->next;
	}
	return nullptr;
}

JavaClass* ClassLoader::loadClass(std::string name){
	if(father_){
		JavaClass* clazz = father_->loadClass(name);
		if (clazz) return clazz;
	}

	ClassPathEntry* entry = exist(name);
	if (!entry) return nullptr;
	ClassFileStream *stream = entry->open_stream(name);
	ClassFileParser parser(meta_, stream);
	return parser.Parser();
}


text:
import { LinkModel } from '../../data';
import { MenuItemProps } from '../components/Menu/MenuItem';
import { IconName } from '../types';

/**
 * Delays creating links until we need to open the ContextMenu
 */
export const linkModelToContextMenuItems: (links: () => LinkModel[]) => MenuItemProps[] = (links) => {
  return links().map((link) => {
    return {
      label: link.title,
      ariaLabel: link.title,
      // TODO: rename to href
      url: link.href,
      target: link.target,
      icon: `${link.target === '_self' ? 'link' : 'external-link-alt'}` as IconName,
      onClick: link.onClick,
    };
  });
};


text:
<title>trav package abstract</title>

 Trav_FromSelectEnum2String()

 Given an Enumerated type Returns a string

 Trav_FromSelectString2Enum()

 Given a string it Returns an Enumerated type

 Trav_Main()

 Temporary main program to be used as interface for cmd.

 Trav_MgrInit()

 Create a Manager.

 Trav_MgrOperation()

 Perform an Operation on the Traversal Manager.

 Trav_MgrPrintStats()

 Print Statistics on the Traversal Manager.

 Trav_MgrQuit()

 Closes a Manager.

 Trav_MgrReadAssertFlag()

 Read Assert Flag.

 Trav_MgrReadAssert()

 Read Assert.

 Trav_MgrReadAux()

 Read AUX array

 Trav_MgrReadBackward()

 Read the backward traversal flag

 Trav_MgrReadDdiMgrDefault()

 Read default DDi Mgr

 Trav_MgrReadDdiMgrR()

 Read DDi Mgr R

 Trav_MgrReadDdiMgrTr()

 Read DDi Mgr TR

 Trav_MgrReadEnableDdR()

 Read

 Trav_MgrReadFromSelect()

 Read from selection

 Trav_MgrReadFrom()

 Read from

 Trav_MgrReadI()

 Read PI array

 Trav_MgrReadKeepNew()

 Read the keepNew  flag

 Trav_MgrReadLevel()

 Read Number of Level

 Trav_MgrReadLogPeriod()

 Read the period for verbosity enabling

 Trav_MgrReadMaxIter()

 Read the maximum number of traversal iterations

 Trav_MgrReadMgrAuxFlag()

 Read the flag to indicate that during traversal there is an
    additional auziliary manager

 Trav_MgrReadNS()

 Read NS array

 Trav_MgrReadName()

 Read

 Trav_MgrReadNewi()

 Read newi

 Trav_MgrReadPS()

 Read PS array

 Trav_MgrReadProductPeak()

 Read Product Peak Value

 Trav_MgrReadReached()

 Read reached

 Trav_MgrReadSavePeriodName()

 Read the period for save BDDs enabling

 Trav_MgrReadSavePeriod()

 Read the period for save BDDs enabling

 Trav_MgrReadSmoothVar()

 Read

 Trav_MgrReadSorting()

 Read verbosity

 Trav_MgrReadSquaring()

 Read

 Trav_MgrReadThreshold()

 Read

 Trav_MgrReadTrProfileDynamicEnable()

 Read

 Trav_MgrReadTrProfileMethod()

 Read

 Trav_MgrReadTrProfileThreshold()

 Read

 Trav_MgrReadTr()

 Read transition relation

 Trav_MgrReadVerbosity()

 Read verbosity

 Trav_MgrReadW1()

 Read

 Trav_MgrReadW2()

 Read

 Trav_MgrReadW3()

 Read

 Trav_MgrReadW4()

 Read

 Trav_MgrSetAssertFlag()

 Set Assert Flag.

 Trav_MgrSetAssert()

 Set Assert.

 Trav_MgrSetAux()

 Set the aux array

 Trav_MgrSetBackward()

 Set the backward traversal flag

 Trav_MgrSetDdiMgrDefault()

 Set default DDi Mgr

 Trav_MgrSetDdiMgrR()

 Set DDi Mgr R

 Trav_MgrSetDdiMgrTr()

 Set DDi Mgr TR

 Trav_MgrSetFromSelect()

 Set the from selection

 Trav_MgrSetFrom()

 Read

 Trav_MgrSetI()

 Set the PI array

 Trav_MgrSetKeepNew()

 Set the keepNew flag

 Trav_MgrSetLogPeriod()

 Set the period for verbosity enabling

 Trav_MgrSetMaxIter()

 Set the maximum number of traversal iterations

 Trav_MgrSetMgrAuxFlag()

 Set the flag to indicate that during traversal there is an
    additional auziliary manager

 Trav_MgrSetNS()

 Set the NS array

 Trav_MgrSetName()

 Read

 Trav_MgrSetNewi()

 Set Newi

 Trav_MgrSetPS()

 Set the PS array

 Trav_MgrSetProductPeak()

 Read

 Trav_MgrSetReached()

 Read

 Trav_MgrSetSavePeriodName()

 Set the period for verbosity enabling

 Trav_MgrSetSavePeriod()

 Set the period for verbosity enabling

 Trav_MgrSetSorting()

 Read verbosity

 Trav_MgrSetTrProfileDynamicEnable()

 Read

 Trav_MgrSetTrProfileMethod()

 Set

 Trav_MgrSetTrProfileThreshold()

 Read

 Trav_MgrSetTr()

 Read

 Trav_MgrSetVerbosity()

 Set verbosity

 Trav_MismatchPat()

 Generation of a mismatch input sequence

 Trav_SimulateMain()

 Temporary main program to be used as interface for cmd.

 Trav_TrPartition()

 Partitions the Transition Relation

 Trav_Traversal()

 FSM traversal given a transition relation

 Trav_UnivAlignPat()

 Find a universal alignment sequence

Last updated on 1010515 11h48


text:
export interface FileInput{
    id: string,
    currentFiles: File[],
}


text:
using namespace MPACK::Core;

namespace MPACK
{
	namespace Sound
	{
		PlayController PlayController::s_sentinel;

		PlayController::PlayController()
		{
		}

		PlayController::~PlayController()
		{
		}

		bool PlayController::IsSupported() const
		{
			return true;
		}

		ReturnValue PlayController::Start()
		{
			return RETURN_VALUE_OK;
		}

		ReturnValue PlayController::Resume()
		{
			return RETURN_VALUE_OK;
		}

		ReturnValue PlayController::Pause()
		{
			return RETURN_VALUE_OK;
		}

		ReturnValue PlayController::Stop()
		{
			return RETURN_VALUE_OK;
		}

		int PlayController::GetPosition()
		{
			return 0;
		}

		int PlayController::GetDuration()
		{
			return 0;
		}

		PlayController* PlayController::GetSentinel()
		{
			return &s_sentinel;
		}
	}
}

#endif


text:
import copy
import os

import ddt
import mock
from oslo_utils import units

from cinder import context
from cinder import exception
from cinder.image import image_utils
from cinder.objects import fields
from cinder import test
from cinder.tests.unit import fake_snapshot
from cinder.tests.unit import fake_volume
from cinder.volume.drivers import remotefs
from cinder.volume.drivers.windows import smbfs

@ddt.ddt
class WindowsSmbFsTestCase(test.TestCase):

    _FAKE_SHARE = '//1.2.3.4/share1'
    _FAKE_SHARE_HASH = 'db0bf952c1734092b83e8990bd321131'
    _FAKE_MNT_BASE = r'c:\openstack\mnt'
    _FAKE_MNT_POINT = os.path.join(_FAKE_MNT_BASE, _FAKE_SHARE_HASH)
    _FAKE_VOLUME_ID = '4f711859-4928-4cb7-801a-a50c37ceaccc'
    _FAKE_VOLUME_NAME = 'volume-%s.vhdx' % _FAKE_VOLUME_ID
    _FAKE_SNAPSHOT_ID = '50811859-4928-4cb7-801a-a50c37ceacba'
    _FAKE_SNAPSHOT_NAME = 'volume-%s-%s.vhdx' % (_FAKE_VOLUME_ID,
                                                 _FAKE_SNAPSHOT_ID)
    _FAKE_SNAPSHOT_PATH = os.path.join(_FAKE_MNT_POINT,
                                       _FAKE_SNAPSHOT_NAME)
    _FAKE_VOLUME_SIZE = 1
    _FAKE_TOTAL_SIZE = 2048
    _FAKE_TOTAL_AVAILABLE = 1024
    _FAKE_TOTAL_ALLOCATED = 1024
    _FAKE_SHARE_OPTS = '-o username=Administrator,password=12345'
    _FAKE_VOLUME_PATH = os.path.join(_FAKE_MNT_POINT,
                                     _FAKE_VOLUME_NAME)
    _FAKE_SHARE_OPTS = '-o username=Administrator,password=12345'

    @mock.patch.object(smbfs, 'utilsfactory')
    @mock.patch.object(smbfs, 'remotefs_brick')
    def setUp(self, mock_remotefs, mock_utilsfactory):
        super(WindowsSmbFsTestCase, self).setUp()

        self.context = context.get_admin_context()

        self._FAKE_SMBFS_CONFIG = mock.MagicMock(
            smbfs_shares_config=mock.sentinel.share_config_file,
            smbfs_default_volume_format='vhdx',
            nas_volume_prov_type='thin')

        self._smbfs_driver = smbfs.WindowsSmbfsDriver(
            configuration=self._FAKE_SMBFS_CONFIG)
        self._smbfs_driver._delete = mock.Mock()
        self._smbfs_driver._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        self._smbfs_driver.base = self._FAKE_MNT_BASE

        self._diskutils = self._smbfs_driver._diskutils
        self._vhdutils = self._smbfs_driver._vhdutils

        self.volume = self._simple_volume()
        self.snapshot = self._simple_snapshot(volume=self.volume)

    def _simple_volume(self, **kwargs):
        updates = {'id': self._FAKE_VOLUME_ID,
                   'size': self._FAKE_VOLUME_SIZE,
                   'provider_location': self._FAKE_SHARE}
        updates.update(kwargs)
        ctxt = context.get_admin_context()
        return fake_volume.fake_volume_obj(ctxt, **updates)

    def _simple_snapshot(self, **kwargs):
        volume = kwargs.pop('volume', None) or self._simple_volume()
        ctxt = context.get_admin_context()
        updates = {'id': self._FAKE_SNAPSHOT_ID,
                   'volume_size': volume.size,
                   'volume_id': volume.id}
        updates.update(kwargs)
        snapshot = fake_snapshot.fake_snapshot_obj(ctxt, **updates)
        snapshot.volume = volume
        return snapshot

    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_check_os_platform')
    @mock.patch.object(remotefs.RemoteFSSnapDriverDistributed, 'do_setup')
    @mock.patch('os.path.exists')
    @mock.patch('os.path.isabs')
    @mock.patch.object(image_utils, 'check_qemu_img_version')
    def _test_setup(self, mock_check_qemu_img_version,
                    mock_is_abs, mock_exists,
                    mock_remotefs_do_setup,
                    mock_check_os_platform,
                    config, share_config_exists=True):
        mock_exists.return_value = share_config_exists
        fake_ensure_mounted = mock.MagicMock()
        self._smbfs_driver._ensure_shares_mounted = fake_ensure_mounted
        self._smbfs_driver._setup_pool_mappings = mock.Mock()
        self._smbfs_driver.configuration = config

        if not (config.smbfs_shares_config and share_config_exists):
            self.assertRaises(exception.SmbfsException,
                              self._smbfs_driver.do_setup,
                              mock.sentinel.context)
        else:
            self._smbfs_driver.do_setup(mock.sentinel.context)

            mock_check_qemu_img_version.assert_called_once_with(
                self._smbfs_driver._MINIMUM_QEMU_IMG_VERSION)
            mock_is_abs.assert_called_once_with(self._smbfs_driver.base)
            self.assertEqual({}, self._smbfs_driver.shares)
            fake_ensure_mounted.assert_called_once_with()
            self._smbfs_driver._setup_pool_mappings.assert_called_once_with()

        self.assertTrue(self._smbfs_driver._thin_provisioning_support)
        mock_check_os_platform.assert_called_once_with()

    def test_setup_pools(self):
        pool_mappings = {
            '//ip/share0': 'pool0',
            '//ip/share1': 'pool1',
        }
        self._smbfs_driver.configuration.smbfs_pool_mappings = pool_mappings
        self._smbfs_driver.shares = {
            '//ip/share0': None,
            '//ip/share1': None,
            '//ip/share2': None
        }

        expected_pool_mappings = pool_mappings.copy()
        expected_pool_mappings['//ip/share2'] = 'share2'

        self._smbfs_driver._setup_pool_mappings()
        self.assertEqual(expected_pool_mappings,
                         self._smbfs_driver._pool_mappings)

    def test_setup_pool_duplicates(self):
        self._smbfs_driver.configuration.smbfs_pool_mappings = {
            'share0': 'pool0',
            'share1': 'pool0'
        }
        self.assertRaises(exception.SmbfsException,
                          self._smbfs_driver._setup_pool_mappings)

    def test_initialize_connection(self):
        self._smbfs_driver.get_active_image_from_info = mock.Mock(
            return_value=self._FAKE_VOLUME_NAME)
        self._smbfs_driver._get_mount_point_base = mock.Mock(
            return_value=self._FAKE_MNT_BASE)
        self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}
        self._smbfs_driver.get_volume_format = mock.Mock(
            return_value=mock.sentinel.format)

        fake_data = {'export': self._FAKE_SHARE,
                     'format': mock.sentinel.format,
                     'name': self._FAKE_VOLUME_NAME,
                     'options': self._FAKE_SHARE_OPTS}
        expected = {
            'driver_volume_type': 'smbfs',
            'data': fake_data,
            'mount_point_base': self._FAKE_MNT_BASE}
        ret_val = self._smbfs_driver.initialize_connection(
            self.volume, None)

        self.assertEqual(expected, ret_val)

    def test_setup(self):
        self._test_setup(config=self._FAKE_SMBFS_CONFIG)

    def test_setup_missing_shares_config_option(self):
        fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
        fake_config.smbfs_shares_config = None
        self._test_setup(config=fake_config,
                         share_config_exists=False)

    def test_setup_missing_shares_config_file(self):
        self._test_setup(config=self._FAKE_SMBFS_CONFIG,
                         share_config_exists=False)

    @mock.patch.object(smbfs, 'context')
    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       '_get_pool_name_from_share')
    def test_get_total_allocated(self, mock_get_pool_name, mock_ctxt):
        fake_pool_name = 'pool0'
        fake_host_name = 'fake_host@fake_backend'
        fake_vol_sz_sum = 5

        mock_db = mock.Mock()
        mock_db.volume_data_get_for_host.return_value = [
            mock.sentinel.vol_count, fake_vol_sz_sum]

        self._smbfs_driver.host = fake_host_name
        self._smbfs_driver.db = mock_db

        mock_get_pool_name.return_value = fake_pool_name

        allocated = self._smbfs_driver._get_total_allocated(
            mock.sentinel.share)
        self.assertEqual(fake_vol_sz_sum << 30,
                         allocated)

        mock_get_pool_name.assert_called_once_with(mock.sentinel.share)
        mock_db.volume_data_get_for_host.assert_called_once_with(
            context=mock_ctxt.get_admin_context.return_value,
            host='fake_host@fake_backend#pool0')

    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       '_get_local_volume_path_template')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_lookup_local_volume_path')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, 'get_volume_format')
    def _test_get_volume_path(self, mock_get_volume_format, mock_lookup_volume,
                              mock_get_path_template, volume_exists=True):
        drv = self._smbfs_driver
        (mock_get_path_template.return_value,
         ext) = os.path.splitext(self._FAKE_VOLUME_PATH)
        volume_format = ext.strip('.')

        mock_lookup_volume.return_value = (
            self._FAKE_VOLUME_PATH if volume_exists else None)
        mock_get_volume_format.return_value = volume_format

        ret_val = drv.local_path(self.volume)

        if volume_exists:
            self.assertFalse(mock_get_volume_format.called)
        else:
            mock_get_volume_format.assert_called_once_with(self.volume)
        self.assertEqual(self._FAKE_VOLUME_PATH, ret_val)

    def test_get_existing_volume_path(self):
        self._test_get_volume_path()

    def test_get_new_volume_path(self):
        self._test_get_volume_path(volume_exists=False)

    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_local_volume_dir')
    def test_get_local_volume_path_template(self, mock_get_local_dir):
        mock_get_local_dir.return_value = self._FAKE_MNT_POINT
        ret_val = self._smbfs_driver._get_local_volume_path_template(
            self.volume)
        exp_template = os.path.splitext(self._FAKE_VOLUME_PATH)[0]
        self.assertEqual(exp_template, ret_val)

    @mock.patch('os.path.exists')
    def test_lookup_local_volume_path(self, mock_exists):
        expected_path = self._FAKE_VOLUME_PATH + '.vhdx'
        mock_exists.side_effect = lambda x: x == expected_path

        ret_val = self._smbfs_driver._lookup_local_volume_path(
            self._FAKE_VOLUME_PATH)

        extensions = [
            ".%s" % ext
            for ext in self._smbfs_driver._VALID_IMAGE_EXTENSIONS]
        possible_paths = [self._FAKE_VOLUME_PATH + ext
                          for ext in extensions]
        mock_exists.assert_has_calls(
            [mock.call(path) for path in possible_paths])
        self.assertEqual(expected_path, ret_val)

    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       '_get_local_volume_path_template')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_lookup_local_volume_path')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_get_volume_format_spec')
    def _test_get_volume_format(self, mock_get_format_spec,
                                mock_lookup_volume, mock_get_path_template,
                                qemu_format=False, volume_format='vhdx',
                                expected_vol_fmt=None,
                                volume_exists=True):
        expected_vol_fmt = expected_vol_fmt or volume_format

        vol_path = '%s.%s' % (os.path.splitext(self._FAKE_VOLUME_PATH)[0],
                              volume_format)
        mock_get_path_template.return_value = vol_path
        mock_lookup_volume.return_value = (
            vol_path if volume_exists else None)

        mock_get_format_spec.return_value = volume_format

        supported_fmts = self._smbfs_driver._SUPPORTED_IMAGE_FORMATS
        if volume_format.lower() not in supported_fmts:
            self.assertRaises(exception.SmbfsException,
                              self._smbfs_driver.get_volume_format,
                              self.volume,
                              qemu_format)

        else:
            ret_val = self._smbfs_driver.get_volume_format(self.volume,
                                                           qemu_format)

            if volume_exists:
                self.assertFalse(mock_get_format_spec.called)
            else:
                mock_get_format_spec.assert_called_once_with(self.volume)

            self.assertEqual(expected_vol_fmt, ret_val)

    def test_get_volume_format_invalid_extension(self):
        self._test_get_volume_format(volume_format='fake')

    def test_get_existing_vhdx_volume_format(self):
        self._test_get_volume_format()

    def test_get_new_vhd_volume_format(self):
        fmt = 'vhd'
        self._test_get_volume_format(volume_format=fmt,
                                     volume_exists=False,
                                     expected_vol_fmt=fmt)

    def test_get_new_vhd_legacy_volume_format(self):
        img_fmt = 'vhd'
        expected_fmt = 'vpc'
        self._test_get_volume_format(volume_format=img_fmt,
                                     volume_exists=False,
                                     qemu_format=True,
                                     expected_vol_fmt=expected_fmt)

    @ddt.data([False, False],
              [True, True],
              [False, True])
    @ddt.unpack
    def test_get_volume_format_spec(self,
                                    volume_meta_contains_fmt,
                                    volume_type_contains_fmt):
        self._smbfs_driver.configuration = copy.copy(self._FAKE_SMBFS_CONFIG)

        fake_vol_meta_fmt = 'vhd'
        fake_vol_type_fmt = 'vhdx'

        volume_metadata = {}
        volume_type_extra_specs = {}

        if volume_meta_contains_fmt:
            volume_metadata['volume_format'] = fake_vol_meta_fmt
        elif volume_type_contains_fmt:
            volume_type_extra_specs['smbfs:volume_format'] = fake_vol_type_fmt

        volume_type = fake_volume.fake_volume_type_obj(self.context)
        volume = fake_volume.fake_volume_obj(self.context)
        # Optional arguments are not set in _from_db_object,
        # so have to set explicitly here
        volume.volume_type = volume_type
        volume.metadata = volume_metadata
        # Same for extra_specs and VolumeType
        volume_type.extra_specs = volume_type_extra_specs

        resulted_fmt = self._smbfs_driver._get_volume_format_spec(volume)

        if volume_meta_contains_fmt:
            expected_fmt = fake_vol_meta_fmt
        elif volume_type_contains_fmt:
            expected_fmt = fake_vol_type_fmt
        else:
            expected_fmt = self._FAKE_SMBFS_CONFIG.smbfs_default_volume_format

        self.assertEqual(expected_fmt, resulted_fmt)

    @mock.patch.object(remotefs.RemoteFSSnapDriverDistributed,
                       'create_volume')
    def test_create_volume_base(self, mock_create_volume):
        self._smbfs_driver.create_volume(self.volume)
        mock_create_volume.assert_called_once_with(self.volume)

    @mock.patch('os.path.exists')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_get_vhd_type')
    def _test_create_volume(self, mock_get_vhd_type, mock_exists,
                            volume_exists=False, volume_format='vhdx'):
        mock_exists.return_value = volume_exists
        self._smbfs_driver.create_vhd = mock.MagicMock()
        fake_create = self._smbfs_driver._vhdutils.create_vhd
        self._smbfs_driver.get_volume_format = mock.Mock(
            return_value=volume_format)

        volume = self._simple_volume()
        if volume_exists or volume_format not in ('vhd', 'vhdx'):
            self.assertRaises(exception.InvalidVolume,
                              self._smbfs_driver._do_create_volume,
                              volume)
        else:
            fake_vol_path = self._FAKE_VOLUME_PATH
            self._smbfs_driver._do_create_volume(volume)
            fake_create.assert_called_once_with(
                fake_vol_path, mock_get_vhd_type.return_value,
                max_internal_size=volume.size << 30)

    def test_create_volume(self):
        self._test_create_volume()

    def test_create_existing_volume(self):
        self._test_create_volume(True)

    def test_create_volume_invalid_volume(self):
        self._test_create_volume(volume_format="qcow")

    def test_delete_volume(self):
        drv = self._smbfs_driver
        fake_vol_info = self._FAKE_VOLUME_PATH + '.info'

        drv._ensure_share_mounted = mock.MagicMock()
        fake_ensure_mounted = drv._ensure_share_mounted

        drv._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        drv.get_active_image_from_info = mock.Mock(
            return_value=self._FAKE_VOLUME_NAME)
        drv._delete = mock.Mock()
        drv._local_path_volume_info = mock.Mock(
            return_value=fake_vol_info)

        with mock.patch('os.path.exists', lambda x: True):
            drv.delete_volume(self.volume)

            fake_ensure_mounted.assert_called_once_with(self._FAKE_SHARE)
            drv._delete.assert_any_call(
                self._FAKE_VOLUME_PATH)
            drv._delete.assert_any_call(fake_vol_info)

    def test_ensure_mounted(self):
        self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}

        self._smbfs_driver._ensure_share_mounted(self._FAKE_SHARE)
        self._smbfs_driver._remotefsclient.mount.assert_called_once_with(
            self._FAKE_SHARE, self._FAKE_SHARE_OPTS)

    def test_get_capacity_info(self):
        self._diskutils.get_disk_capacity.return_value = (
            self._FAKE_TOTAL_SIZE, self._FAKE_TOTAL_AVAILABLE)
        self._smbfs_driver._get_mount_point_for_share = mock.Mock(
            return_value=mock.sentinel.mnt_point)
        self._smbfs_driver._get_total_allocated = mock.Mock(
            return_value=self._FAKE_TOTAL_ALLOCATED)

        ret_val = self._smbfs_driver._get_capacity_info(self._FAKE_SHARE)
        expected_ret_val = [int(x) for x in [self._FAKE_TOTAL_SIZE,
                            self._FAKE_TOTAL_AVAILABLE,
                            self._FAKE_TOTAL_ALLOCATED]]
        self.assertEqual(expected_ret_val, ret_val)

        self._smbfs_driver._get_mount_point_for_share.assert_called_once_with(
            self._FAKE_SHARE)
        self._diskutils.get_disk_capacity.assert_called_once_with(
            mock.sentinel.mnt_point)
        self._smbfs_driver._get_total_allocated.assert_called_once_with(
            self._FAKE_SHARE)

    def _test_get_img_info(self, backing_file=None):
        self._smbfs_driver._vhdutils.get_vhd_parent_path.return_value = (
            backing_file)

        image_info = self._smbfs_driver._qemu_img_info(self._FAKE_VOLUME_PATH)
        self.assertEqual(self._FAKE_VOLUME_NAME,
                         image_info.image)
        backing_file_name = backing_file and os.path.basename(backing_file)
        self.assertEqual(backing_file_name, image_info.backing_file)

    def test_get_img_info_without_backing_file(self):
        self._test_get_img_info()

    def test_get_snapshot_info(self):
        self._test_get_img_info(self._FAKE_VOLUME_PATH)

    @ddt.data('attached', 'detached')
    def test_create_snapshot(self, attach_status):
        snapshot = self._simple_snapshot()
        snapshot.volume.attach_status = attach_status

        self._smbfs_driver._vhdutils.create_differencing_vhd = (
            mock.Mock())
        self._smbfs_driver._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)

        fake_create_diff = (
            self._smbfs_driver._vhdutils.create_differencing_vhd)

        self._smbfs_driver._do_create_snapshot(
            snapshot,
            os.path.basename(self._FAKE_VOLUME_PATH),
            self._FAKE_SNAPSHOT_PATH)

        if attach_status != 'attached':
            fake_create_diff.assert_called_once_with(self._FAKE_SNAPSHOT_PATH,
                                                     self._FAKE_VOLUME_PATH)
        else:
            fake_create_diff.assert_not_called()

    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       '_check_extend_volume_support')
    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       '_local_path_active_image')
    def test_extend_volume(self, mock_get_active_img,
                           mock_check_ext_support):
        volume = fake_volume.fake_volume_obj(self.context)
        new_size = volume.size + 1

        self._smbfs_driver.extend_volume(volume, new_size)

        mock_check_ext_support.assert_called_once_with(volume, new_size)
        mock_get_active_img.assert_called_once_with(volume)
        self._vhdutils.resize_vhd.assert_called_once_with(
            mock_get_active_img.return_value,
            new_size * units.Gi,
            is_file_max_size=False)

    @ddt.data({'snapshots_exist': True},
              {'vol_fmt': smbfs.WindowsSmbfsDriver._DISK_FORMAT_VHD,
               'snapshots_exist': True,
               'expected_exc': exception.InvalidVolume})
    @ddt.unpack
    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       'get_volume_format')
    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       '_snapshots_exist')
    def test_check_extend_support(self, mock_snapshots_exist,
                                  mock_get_volume_format,
                                  vol_fmt=None, snapshots_exist=False,
                                  share_eligible=True,
                                  expected_exc=None):
        vol_fmt = vol_fmt or self._smbfs_driver._DISK_FORMAT_VHDX

        volume = fake_volume.fake_volume_obj(
            self.context, provider_location='fake_provider_location')
        new_size = volume.size + 1

        mock_snapshots_exist.return_value = snapshots_exist
        mock_get_volume_format.return_value = vol_fmt

        if expected_exc:
            self.assertRaises(expected_exc,
                              self._smbfs_driver._check_extend_volume_support,
                              volume, new_size)
        else:
            self._smbfs_driver._check_extend_volume_support(volume, new_size)

            mock_get_volume_format.assert_called_once_with(volume)
            mock_snapshots_exist.assert_called_once_with(volume)

    @ddt.data({},
              {'delete_latest': True},
              {'attach_status': 'detached'},
              {'snap_info_contains_snap_id': False})
    @ddt.unpack
    @mock.patch.object(remotefs.RemoteFSSnapDriverDistributed,
                       '_delete_snapshot')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_local_volume_dir')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_local_path_volume_info')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_write_info_file')
    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_read_info_file')
    @mock.patch.object(smbfs.WindowsSmbfsDriver,
                       '_nova_assisted_vol_snap_delete')
    def test_delete_snapshot(self, mock_nova_assisted_snap_del,
                             mock_read_info_file, mock_write_info_file,
                             mock_local_path_volume_info,
                             mock_get_local_dir,
                             mock_remotefs_snap_delete,
                             attach_status='attached',
                             snap_info_contains_snap_id=True,
                             delete_latest=False):
        snapshot = self._simple_snapshot()
        snapshot.volume.attach_status = attach_status

        fake_snap_file = 'snap_file'
        fake_snap_parent_path = os.path.join(self._FAKE_MNT_POINT,
                                             'snap_file_parent')
        active_img = 'active_img' if not delete_latest else fake_snap_file

        snap_info = dict(active=active_img)
        if snap_info_contains_snap_id:
            snap_info[snapshot.id] = fake_snap_file

        mock_info_path = mock_local_path_volume_info.return_value
        mock_read_info_file.return_value = snap_info
        mock_get_local_dir.return_value = self._FAKE_MNT_POINT
        self._vhdutils.get_vhd_parent_path.return_value = (
            fake_snap_parent_path)

        expected_delete_info = {'file_to_merge': fake_snap_file,
                                'volume_id': snapshot.volume.id}

        self._smbfs_driver._delete_snapshot(snapshot)

        if attach_status != 'attached':
            mock_remotefs_snap_delete.assert_called_once_with(snapshot)
        elif snap_info_contains_snap_id:
            mock_local_path_volume_info.assert_called_once_with(
                snapshot.volume)
            mock_read_info_file.assert_called_once_with(
                mock_info_path, empty_if_missing=True)
            mock_nova_assisted_snap_del.assert_called_once_with(
                snapshot._context, snapshot, expected_delete_info)

            exp_merged_img_path = os.path.join(self._FAKE_MNT_POINT,
                                               fake_snap_file)
            self._smbfs_driver._delete.assert_called_once_with(
                exp_merged_img_path)

            if delete_latest:
                self._vhdutils.get_vhd_parent_path.assert_called_once_with(
                    exp_merged_img_path)
                exp_active = os.path.basename(fake_snap_parent_path)
            else:
                exp_active = active_img

            self.assertEqual(exp_active, snap_info['active'])
            self.assertNotIn(snap_info, snapshot.id)
            mock_write_info_file.assert_called_once_with(mock_info_path,
                                                         snap_info)

        if attach_status != 'attached' or not snap_info_contains_snap_id:
            mock_nova_assisted_snap_del.assert_not_called()
            mock_write_info_file.assert_not_called()

    def test_create_volume_from_unavailable_snapshot(self):
        self.snapshot.status = fields.SnapshotStatus.ERROR
        self.assertRaises(
            exception.InvalidSnapshot,
            self._smbfs_driver.create_volume_from_snapshot,
            self.volume, self.snapshot)

    @ddt.data(True, False)
    def test_copy_volume_to_image(self, has_parent=False):
        drv = self._smbfs_driver

        fake_image_meta = {'id': 'fake-image-id'}
        fake_img_format = self._smbfs_driver._DISK_FORMAT_VHDX

        if has_parent:
            fake_volume_path = self._FAKE_SNAPSHOT_PATH
            fake_parent_path = self._FAKE_VOLUME_PATH
        else:
            fake_volume_path = self._FAKE_VOLUME_PATH
            fake_parent_path = None

        fake_active_image = os.path.basename(fake_volume_path)

        drv.get_active_image_from_info = mock.Mock(
            return_value=fake_active_image)
        drv._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        drv.get_volume_format = mock.Mock(
            return_value=fake_img_format)
        drv._vhdutils.get_vhd_parent_path.return_value = (
            fake_parent_path)

        with mock.patch.object(image_utils, 'upload_volume') as (
                fake_upload_volume):
            volume = self._simple_volume()
            drv.copy_volume_to_image(
                mock.sentinel.context, volume,
                mock.sentinel.image_service, fake_image_meta)

            if has_parent:
                fake_temp_image_name = '%s.temp_image.%s.%s' % (
                    volume.id,
                    fake_image_meta['id'],
                    fake_img_format)
                fake_temp_image_path = os.path.join(
                    self._FAKE_MNT_POINT,
                    fake_temp_image_name)
                fake_active_image_path = os.path.join(
                    self._FAKE_MNT_POINT,
                    fake_active_image)
                upload_path = fake_temp_image_path

                drv._vhdutils.convert_vhd.assert_called_once_with(
                    fake_active_image_path,
                    fake_temp_image_path)
                drv._delete.assert_called_once_with(
                    fake_temp_image_path)
            else:
                upload_path = fake_volume_path

            fake_upload_volume.assert_called_once_with(
                mock.sentinel.context, mock.sentinel.image_service,
                fake_image_meta, upload_path, fake_img_format)

    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_get_vhd_type')
    def test_copy_image_to_volume(self, mock_get_vhd_type):
        drv = self._smbfs_driver

        drv.get_volume_format = mock.Mock(
            return_value=mock.sentinel.volume_format)
        drv.local_path = mock.Mock(
            return_value=self._FAKE_VOLUME_PATH)
        drv.configuration = mock.MagicMock()
        drv.configuration.volume_dd_blocksize = mock.sentinel.block_size

        with mock.patch.object(image_utils,
                               'fetch_to_volume_format') as fake_fetch:
            volume = self._simple_volume()
            drv.copy_image_to_volume(
                mock.sentinel.context, volume,
                mock.sentinel.image_service,
                mock.sentinel.image_id)
            fake_fetch.assert_called_once_with(
                mock.sentinel.context,
                mock.sentinel.image_service,
                mock.sentinel.image_id,
                self._FAKE_VOLUME_PATH, mock.sentinel.volume_format,
                mock.sentinel.block_size,
                mock_get_vhd_type.return_value)
            drv._vhdutils.resize_vhd.assert_called_once_with(
                self._FAKE_VOLUME_PATH,
                volume.size * units.Gi,
                is_file_max_size=False)

    @mock.patch.object(smbfs.WindowsSmbfsDriver, '_get_vhd_type')
    def test_copy_volume_from_snapshot(self, mock_get_vhd_type):
        drv = self._smbfs_driver
        snapshot = self._simple_snapshot()
        fake_volume_info = {
            snapshot.id: 'fake_snapshot_file_name'}
        fake_img_info = mock.MagicMock()
        fake_img_info.backing_file = self._FAKE_VOLUME_NAME

        drv._local_path_volume_info = mock.Mock(
            return_value=self._FAKE_VOLUME_PATH + '.info')
        drv._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        drv._read_info_file = mock.Mock(
            return_value=fake_volume_info)
        drv._qemu_img_info = mock.Mock(
            return_value=fake_img_info)
        drv.local_path = mock.Mock(
            return_value=mock.sentinel.new_volume_path)

        volume = self._simple_volume()
        drv._copy_volume_from_snapshot(snapshot,
                                       volume, volume.size)

        drv._delete.assert_called_once_with(mock.sentinel.new_volume_path)
        drv._vhdutils.convert_vhd.assert_called_once_with(
            self._FAKE_VOLUME_PATH,
            mock.sentinel.new_volume_path,
            vhd_type=mock_get_vhd_type.return_value)
        drv._vhdutils.resize_vhd.assert_called_once_with(
            mock.sentinel.new_volume_path,
            volume.size * units.Gi,
            is_file_max_size=False)

    def test_rebase_img(self):
        drv = self._smbfs_driver
        drv._rebase_img(
            self._FAKE_SNAPSHOT_PATH,
            self._FAKE_VOLUME_NAME, 'vhdx')
        drv._vhdutils.reconnect_parent_vhd.assert_called_once_with(
            self._FAKE_SNAPSHOT_PATH, self._FAKE_VOLUME_PATH)

    def test_copy_volume_image(self):
        self._smbfs_driver._copy_volume_image(mock.sentinel.src,
                                              mock.sentinel.dest)
        self._smbfs_driver._pathutils.copy.assert_called_once_with(
            mock.sentinel.src, mock.sentinel.dest)

    def test_get_pool_name_from_share(self):
        self._smbfs_driver._pool_mappings = {
            mock.sentinel.share: mock.sentinel.pool}

        pool = self._smbfs_driver._get_pool_name_from_share(
            mock.sentinel.share)
        self.assertEqual(mock.sentinel.pool, pool)

    def test_get_share_from_pool_name(self):
        self._smbfs_driver._pool_mappings = {
            mock.sentinel.share: mock.sentinel.pool}

        share = self._smbfs_driver._get_share_from_pool_name(
            mock.sentinel.pool)
        self.assertEqual(mock.sentinel.share, share)

    def test_get_pool_name_from_share_exception(self):
        self._smbfs_driver._pool_mappings = {}

        self.assertRaises(exception.SmbfsException,
                          self._smbfs_driver._get_share_from_pool_name,
                          mock.sentinel.pool)

    def test_get_vhd_type(self):
        drv = self._smbfs_driver

        mock_type = drv._get_vhd_type(qemu_subformat=True)
        self.assertEqual(mock_type, 'dynamic')

        mock_type = drv._get_vhd_type(qemu_subformat=False)
        self.assertEqual(mock_type, 3)

        self._smbfs_driver.configuration.nas_volume_prov_type = (
            'thick')

        mock_type = drv._get_vhd_type(qemu_subformat=True)
        self.assertEqual(mock_type, 'fixed')

    def test_get_managed_vol_expected_path(self):
        self._vhdutils.get_vhd_format.return_value = 'vhdx'
        vol_location = dict(vol_local_path=mock.sentinel.image_path,
                            mountpoint=self._FAKE_MNT_POINT)

        path = self._smbfs_driver._get_managed_vol_expected_path(
            self.volume, vol_location)
        self.assertEqual(self._FAKE_VOLUME_PATH, path)

        self._vhdutils.get_vhd_format.assert_called_once_with(
            mock.sentinel.image_path)


text:
function dtiExtractSingleShell(dMRI, bvecs, bvals, brange, outname)
% Extract one shell of data from a multibvalue dataset
%
% dtiExtractSingleShell(dMRI, bvecs, bvals, brange, outname)
im = readFileNifti(dMRI)
b = dlmread(bvals);
bv = dlmread(bvecs);
if size(bv,2) > size(bv,1)
    bv = bv';
end
if size(b,2) > size(b,1)
    b = b';
end
% Scale small b values to 0
b(b<=10)=0;
% Find dMRI volumes with bvalues in the specified range (or equal to zero)
v = (b > brange(1) & b < brange(2)) | b == 0;
% Extract image volumes and corresponding bvals
im.data = im.data(:,:,:,v); im.dim(4)=sum(v); im.fname = [outname '.nii.gz'];
b = b(v); bv = bv(v,:);
% Write out new nifti and corresponding bvals and bvecs
writeFileNifti(im);
dlmwrite([outname '.bvals'],b');
dlmwrite([outname '.bvecs'],bv');


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Connecter = (function () {
    function Connecter(container, particle) {
        this.container = container;
        this.particle = particle;
    }
    Connecter.prototype.connect = function (destParticle) {
        var container = this.container;
        var options = container.options;
        var particle = this.particle;
        if (options.interactivity.events.onHover.enable && container.interactivity.status == 'mousemove') {
            var xDiff = Math.abs(particle.position.x - destParticle.position.x);
            var yDiff = Math.abs(particle.position.y - destParticle.position.y);
            var mousePos = container.interactivity.mouse.position || { x: 0, y: 0 };
            var xCoreDiff = Math.abs(particle.position.x - mousePos.x);
            var yCoreDiff = Math.abs(particle.position.y - mousePos.y);
            var distMax = Math.abs(container.retina.connectModeDistance);
            var connectAreaRadius = Math.abs(container.retina.connectModeRadius);
            if (xDiff < distMax && yDiff < distMax && xCoreDiff < connectAreaRadius && yCoreDiff < connectAreaRadius) {
                container.canvas.drawConnectLine(particle, destParticle);
            }
        }
    };
    return Connecter;
}());
exports.Connecter = Connecter;


text:
import { ChangeDetectorRef, ComponentRef, ElementRef, NgZone, Renderer } from '@angular/core';
import { Location } from '@angular/common';
import { App } from '../components/app/app';
import { IonicApp } from '../components/app/app-root';
import { Config } from '../config/config';
import { DeepLinker } from '../navigation/deep-linker';
import { Menu } from '../components/menu/menu';
import { DeepLinkConfig } from '../navigation/nav-util';
import { OverlayPortal } from '../components/nav/overlay-portal';
import { Platform } from '../platform/platform';
import { QueryParams } from '../platform/query-params';
import { Tab } from '../components/tabs/tab';
import { Tabs } from '../components/tabs/tabs';
import { TransitionController } from '../transitions/transition-controller';
import { ViewController } from '../navigation/view-controller';
import { NavControllerBase } from '../navigation/nav-controller-base';
import { Haptic } from './haptic';
export declare const mockConfig: (config?: any, url?: string, platform?: Platform) => Config;
export declare const mockQueryParams: (url?: string) => QueryParams;
export declare const mockPlatform: () => Platform;
export declare const mockApp: (config?: Config, platform?: Platform) => App;
export declare const mockIonicApp: (app: App, config: Config, platform: Platform) => IonicApp;
export declare const mockTrasitionController: (config: Config) => TransitionController;
export declare const mockZone: () => NgZone;
export declare const mockChangeDetectorRef: () => ChangeDetectorRef;
export declare class MockElementRef implements ElementRef {
    nativeElement: any;
}
export declare class MockElement {
    children: any[];
    classList: ClassList;
    attributes: {
        [name: string]: any;
    };
    style: {
        [property: string]: any;
    };
    clientWidth: number;
    clientHeight: number;
    clientTop: number;
    clientLeft: number;
    offsetWidth: number;
    offsetHeight: number;
    offsetTop: number;
    offsetLeft: number;
    scrollTop: number;
    scrollHeight: number;
    className: string;
    hasAttribute(name: string): boolean;
    getAttribute(name: string): any;
    setAttribute(name: string, val: any): void;
    removeAttribute(name: string): void;
}
export declare class ClassList {
    classes: string[];
    add(className: string): void;
    remove(className: string): void;
    toggle(className: string): void;
    contains(className: string): boolean;
}
export declare const mockElementRef: () => ElementRef;
export declare class MockRenderer {
    setElementAttribute(renderElement: MockElement, name: string, val: any): void;
    setElementClass(renderElement: MockElement, className: string, isAdd: boolean): void;
    setElementStyle(renderElement: MockElement, styleName: string, styleValue: string): void;
}
export declare const mockRenderer: () => Renderer;
export declare const mockLocation: () => Location;
export declare const mockView: (component?: any, data?: any) => ViewController;
export declare const mockViews: (nav: NavControllerBase, views: ViewController[]) => void;
export declare const mockComponentRef: () => ComponentRef<any>;
export declare const mockDeepLinker: (linkConfig?: DeepLinkConfig, app?: App) => DeepLinker;
export declare const mockNavController: () => NavControllerBase;
export declare const mockOverlayPortal: (app: App, config: Config, platform: Platform) => OverlayPortal;
export declare const mockTab: (parentTabs: Tabs) => Tab;
export declare const mockTabs: (app?: App) => Tabs;
export declare const mockMenu: () => Menu;
export declare const mockDeepLinkConfig: (links?: any[]) => DeepLinkConfig;
export declare const mockHaptic: () => Haptic;
export declare class MockView {
}
export declare class MockView1 {
}
export declare class MockView2 {
}
export declare class MockView3 {
}
export declare class MockView4 {
}
export declare class MockView5 {
}
export declare function noop(): any;


text:
package com.melotic.api.dto;

import com.fasterxml.jackson.annotation.JsonCreator;

public class DealOrderId
{
    public final Integer key;

    @JsonCreator public DealOrderId(int key)
    {
        this.key = key;
    }

    @Override public int hashCode()
    {
        return key.hashCode();
    }

    @Override public boolean equals(Object other)
    {
        return (other instanceof DealOrderId) && key.equals(((DealOrderId) other).key);
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe "Mechanizer" do
  it "retains access to the last page loaded" do
    mech = AmazonSellerCentral.mechanizer
    mech.login_to_seller_central
    mech.last_page.body.should =~ /BLINQ/
  end

  it "logs in and returns the home page" do
    mech = AmazonSellerCentral.mechanizer
    mech.login_to_seller_central.should be_true
  end

  it "raises a LinkNotFoundError if the requested link doesn't exist" do
    mech = AmazonSellerCentral.mechanizer
    mech.login_to_seller_central
    lambda {
      mech.follow_link_with(:text => "Foo")
    }.should raise_exception(AmazonSellerCentral::Mechanizer::LinkNotFoundError)
  end

  it "resets to a nil agent" do
    mech = AmazonSellerCentral.mechanizer
    mech.login_to_seller_central
    lambda {
      mech.follow_link_with(:text => "Feedback")
    }.should_not raise_exception
    AmazonSellerCentral.mechanizer.reset!

    mech = AmazonSellerCentral.mechanizer
    mech.login_to_seller_central
    mech.reset!
    lambda {
      mech.follow_link_with(:text => "Feedback")
    }.should raise_exception(AmazonSellerCentral::Mechanizer::AgentResetError)
    AmazonSellerCentral.mechanizer.last_page.should be_nil
  end

  it "logs in twice successfully" do
    mech = AmazonSellerCentral.mechanizer
    mech.login_to_seller_central
    mech.last_page.body.should =~ /BLINQ/
    mech.follow_link_with :text => "Feedback"

    mech.reset!
    mech.login_to_seller_central
    mech.last_page.body.should =~ /BLINQ/
  end

end


text:
package jbaldassari.rtb;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.avro.util.Utf8;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;

/**
 * Simulates a real-time bidding auction.
 */
public class AuctionSimulationTest extends AbstractBidderTest {
  private static final int NUM_REQUESTS = 10;
  private static final long DELAY_STEP_MILLIS = 100;
  private static final Logger logger =
      Logger.getLogger(AuctionSimulationTest.class);

  @Test
  public void runAuction() throws Exception {
    // Start servers for each participant in the auction
    // Each server will have a specific constant bid and delay associated
    // with it equal to the bidder index * DELAY_STEP_MILLIS.
    // Bidder 0 will have a delay of 0, Bidder 1 will have a delay of
    // DELAY_STEP_MILLIS, and so on.
    Map<CharSequence, Bidder.Callback> bidders =
      new LinkedHashMap<CharSequence, Bidder.Callback>();
    for (int ii = 0; ii < NUM_REQUESTS; ii++) {
      CharSequence bidderId = new Utf8("Bidder " + (ii + 1));
      long constantBid = 100000L * (ii + 1);
      long delayMillis = DELAY_STEP_MILLIS * (ii + 1);
      logger.info("Creating bidder " + bidderId + " with constant bid " +
          constantBid + " micro-dollars CPM and delay of " +
          delayMillis + "ms");
      bidders.put(bidderId, startServerAndGetClient(new DelayInjectingBidder(
          new ConstantBidder(SNIPPET, constantBid), delayMillis)));
    }

    // Start an auction with a long timeout.
    // All bidders should respond before the auction ends, so
    // the highest bidder (Bidder 10) should win.
    Auction auction1 = new Auction(bidRequest, bidders,
        10, TimeUnit.SECONDS);
    AuctionResult result1 = auction1.call();
    if (result1.getIsWon()) {
      logger.info("Winner is: " + result1.getWinningBidderId() +
          " with a bid of $" +
          (result1.getWinningBid().getMaxBidMicroCpm() / 1e6) + " CPM.");
    }
    else {
      logger.info("No winners.");
    }
    Assert.assertEquals(bidRequest.getAuctionId(), result1.getAuctionId());
    Assert.assertTrue(result1.getIsWon());
    Assert.assertEquals(new Utf8("Bidder 10"), result1.getWinningBidderId());
    validateBidResponse(bidRequest, result1.getWinningBid());

    // Start an auction with a timeout smaller than the delay configured for
    // some bidders.
    // With 500ms < delay < 600ms, only bidders 1-5 should respond in time.
    // Bidder 5 should win because it has the highest bid of the bidders that
    // responded before the auction ended.
    Auction auction2 = new Auction(bidRequest, bidders,
        550, TimeUnit.MILLISECONDS);
    AuctionResult result2 = auction2.call();
    if (result2.getIsWon()) {
      logger.info("Winner is: " + result2.getWinningBidderId() +
          " with a bid of $" +
          (result2.getWinningBid().getMaxBidMicroCpm() / 1e6) + " CPM.");
    }
    else {
      logger.info("No winners.");
    }
    Assert.assertEquals(bidRequest.getAuctionId(), result2.getAuctionId());
    Assert.assertTrue(result2.getIsWon());
    Assert.assertEquals(new Utf8("Bidder 5"), result2.getWinningBidderId());
    validateBidResponse(bidRequest, result2.getWinningBid());

    // Wait for the rest of the RPCs to complete so that the connections
    // can be torn down gracefully:
    Thread.sleep(2000L);
  }
}


text:
import template from './accountingAccountsView.html';
import controller from './accountingAccountsView.controller';
import './accountingAccountsView.styl';

let accountingAccountsViewComponent = {
  restrict: 'E',
  bindings: {},
  template,
  controller
};

export default accountingAccountsViewComponent;


text:
FROM kartoza/django-base
MAINTAINER Tim Sutton<tim@kartoza.com>

RUN apt-get update -y; apt-get -y --force-yes install yui-compressor

# This section taken on 2 July 2015 from
# https://docs.docker.com/examples/running_ssh_service/
# Sudo is needed by pycharm when it tries to pip install packages
RUN apt-get update -y; apt-get install -y openssh-server sudo
RUN mkdir /var/run/sshd
RUN echo 'root:docker' | chpasswd
# Comment out PermitRootLogin setting, whatever it is
RUN sed -i 's/^PermitRootLogin */#PermitRootLogin /' /etc/ssh/sshd_config
# Write out PermitRootLogin setting at the end
RUN echo "PermitRootLogin yes" >> /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

# End of cut & paste section

# Open port 8080 as we will be running our uwsgi socket on that
EXPOSE 8080

ADD sitecustomize.py /usr/local/lib/python2.7/site-packages/sitecustomize.py
ADD REQUIREMENTS.txt /REQUIREMENTS.txt
ADD REQUIREMENTS-dev.txt /REQUIREMENTS-dev.txt
RUN pip install -r /REQUIREMENTS.txt
RUN pip install -r /REQUIREMENTS-dev.txt
ADD bashrc /root/.bashrc

# Install Gettext
RUN apt-get update -y; apt-get install -y gettext

# --------------------------------------------------------
# Open ports as needed
# --------------------------------------------------------

# Open port 8080 as we will be running our django dev server on
EXPOSE 8080
# Open port 22 as we will be using a remote interpreter from pycharm
EXPOSE 22
# Open port 8088 for celery worker debugging
EXPOSE 8088

CMD ["/usr/sbin/sshd", "-D"]


text:
// Copyright (C) 2014 The Android Open Source Project
//
// 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.

package com.google.gerrit.extensions.common;

public class AvatarInfo {
  /**
   * Size in pixels the UI prefers an avatar image to be.
   *
   * The web UI prefers avatar images to be square, both
   * the height and width of the image should be this size.
   * The height is the more important dimension to match
   * than the width.
   */
  public static final int DEFAULT_SIZE = 26;

  public String url;
  public Integer height;
  public Integer width;
}


text:
<?php

class CosmoCommerce_Cosmo99Bill_Model_Source_Language
{
    public function toOptionArray()
    {
        return array(
            array('value' => 'EN', 'label' => Mage::helper('cosmo99bill')->__('English')),
            array('value' => 'FR', 'label' => Mage::helper('cosmo99bill')->__('French')),
            array('value' => 'DE', 'label' => Mage::helper('cosmo99bill')->__('German')),
            array('value' => 'IT', 'label' => Mage::helper('cosmo99bill')->__('Italian')),
            array('value' => 'ES', 'label' => Mage::helper('cosmo99bill')->__('Spain')),
            array('value' => 'NL', 'label' => Mage::helper('cosmo99bill')->__('Dutch')),
        );
    }
}


text:
namespace google_apis {
namespace {

const int kMaxResults = 4;
const char kQuery[] = "testing-query";
const char kFields[] = "testing-fields";
const char kTestUserAgent[] = "test-user-agent";

const char kSuccessResource[] =
    "{\n"
    " \"kind\": \"drive#fileList\",\n"
    " \"etag\": \"etag\",\n"
    " \"items\": []\n"
    "}\n";

const char kResponseTooLargeErrorResource[] =
    "{\n"
    " \"error\": {\n"
    "  \"errors\": [\n"
    "   {\n"
    "    \"reason\": \"responseTooLarge\"\n"
    "   }\n"
    "  ]\n"
    " }\n"
    "}\n";

const char kQuotaExceededErrorResource[] =
    "{\n"
    " \"error\": {\n"
    "  \"errors\": [\n"
    "   {\n"
    "    \"reason\": \"quotaExceeded\"\n"
    "   }\n"
    "  ]\n"
    " }\n"
    "}\n";

}  // namespace

class FilesListRequestRunnerTest : public testing::Test {
 public:
  FilesListRequestRunnerTest() {}

  void SetUp() override {
    request_context_getter_ =
        new net::TestURLRequestContextGetter(message_loop_.task_runner());

    request_sender_.reset(
        new RequestSender(new DummyAuthService, request_context_getter_.get(),
                          message_loop_.task_runner(), kTestUserAgent));

    test_server_.RegisterRequestHandler(
        base::Bind(&FilesListRequestRunnerTest::OnFilesListRequest,
                   base::Unretained(this), test_server_.base_url()));
    ASSERT_TRUE(test_server_.Start());

    runner_.reset(new FilesListRequestRunner(
        request_sender_.get(),
        google_apis::DriveApiUrlGenerator(test_server_.base_url(),
                                          test_server_.GetURL("/download/"),
                                          test_server_.GetURL("/thumbnail/"))));
  }

  void TearDown() override {
    on_completed_callback_ = base::Closure();
    http_request_.reset();
    response_error_.reset();
    response_entry_.reset();
  }

  // Called when the request is completed and no more backoff retries will
  // happen.
  void OnCompleted(DriveApiErrorCode error, scoped_ptr<FileList> entry) {
    response_error_.reset(new DriveApiErrorCode(error));
    response_entry_ = std::move(entry);
    on_completed_callback_.Run();
  }

 protected:
  // Sets a fake Drive API server response to be returned for the upcoming HTTP
  // request.
  void SetFakeServerResponse(net::HttpStatusCode code,
                             const std::string& content) {
    fake_server_response_.reset(new net::test_server::BasicHttpResponse);
    fake_server_response_->set_code(code);
    fake_server_response_->set_content(content);
    fake_server_response_->set_content_type("application/json");
  }

  // Handles a HTTP request to the Drive API server and returns a fake response.
  scoped_ptr<net::test_server::HttpResponse> OnFilesListRequest(
      const GURL& base_url,
      const net::test_server::HttpRequest& request) {
    http_request_.reset(new net::test_server::HttpRequest(request));
    return std::move(fake_server_response_);
  }

  base::MessageLoopForIO message_loop_;  // Test server needs IO thread.
  scoped_ptr<RequestSender> request_sender_;
  net::EmbeddedTestServer test_server_;
  scoped_ptr<FilesListRequestRunner> runner_;
  scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
  base::Closure on_completed_callback_;

  // Response set by test cases to be returned from the HTTP server.
  scoped_ptr<net::test_server::BasicHttpResponse> fake_server_response_;

  // A requests and a response stored for verification in test cases.
  scoped_ptr<net::test_server::HttpRequest> http_request_;
  scoped_ptr<DriveApiErrorCode> response_error_;
  scoped_ptr<FileList> response_entry_;
};

TEST_F(FilesListRequestRunnerTest, Success_NoBackoff) {
  SetFakeServerResponse(net::HTTP_OK, kSuccessResource);
  runner_->CreateAndStartWithSizeBackoff(
      kMaxResults, kQuery, kFields,
      base::Bind(&FilesListRequestRunnerTest::OnCompleted,
                 base::Unretained(this)));

  base::RunLoop run_loop;
  on_completed_callback_ = run_loop.QuitClosure();
  run_loop.Run();

  ASSERT_TRUE(http_request_.get());
  EXPECT_EQ(
      "/drive/v2/files?maxResults=4&q=testing-query&fields=testing-fields",
      http_request_->relative_url);

  ASSERT_TRUE(response_error_.get());
  EXPECT_EQ(HTTP_SUCCESS, *response_error_);
  EXPECT_TRUE(response_entry_.get());
}

TEST_F(FilesListRequestRunnerTest, Success_Backoff) {
  SetFakeServerResponse(net::HTTP_INTERNAL_SERVER_ERROR,
                        kResponseTooLargeErrorResource);
  runner_->CreateAndStartWithSizeBackoff(
      kMaxResults, kQuery, kFields,
      base::Bind(&FilesListRequestRunnerTest::OnCompleted,
                 base::Unretained(this)));
  {
    base::RunLoop run_loop;
    runner_->SetRequestCompletedCallbackForTesting(run_loop.QuitClosure());
    run_loop.Run();

    ASSERT_TRUE(http_request_.get());
    EXPECT_EQ(
        "/drive/v2/files?maxResults=4&q=testing-query&fields=testing-fields",
        http_request_->relative_url);
    EXPECT_FALSE(response_error_.get());
  }

  // Backoff will decreasing the number of results by 2, which will succeed.
  {
    SetFakeServerResponse(net::HTTP_OK, kSuccessResource);

    base::RunLoop run_loop;
    on_completed_callback_ = run_loop.QuitClosure();
    run_loop.Run();

    ASSERT_TRUE(http_request_.get());
    EXPECT_EQ(
        "/drive/v2/files?maxResults=2&q=testing-query&fields=testing-fields",
        http_request_->relative_url);

    ASSERT_TRUE(response_error_.get());
    EXPECT_EQ(HTTP_SUCCESS, *response_error_);
    EXPECT_TRUE(response_entry_.get());
  }
}

TEST_F(FilesListRequestRunnerTest, Failure_TooManyBackoffs) {
  SetFakeServerResponse(net::HTTP_INTERNAL_SERVER_ERROR,
                        kResponseTooLargeErrorResource);
  runner_->CreateAndStartWithSizeBackoff(
      kMaxResults, kQuery, kFields,
      base::Bind(&FilesListRequestRunnerTest::OnCompleted,
                 base::Unretained(this)));
  {
    base::RunLoop run_loop;
    runner_->SetRequestCompletedCallbackForTesting(run_loop.QuitClosure());
    run_loop.Run();

    ASSERT_TRUE(http_request_.get());
    EXPECT_EQ(
        "/drive/v2/files?maxResults=4&q=testing-query&fields=testing-fields",
        http_request_->relative_url);
    EXPECT_FALSE(response_error_.get());
  }

  // Backoff will decreasing the number of results by 2, which will still fail
  // due to too large response.
  {
    SetFakeServerResponse(net::HTTP_INTERNAL_SERVER_ERROR,
                          kResponseTooLargeErrorResource);

    base::RunLoop run_loop;
    runner_->SetRequestCompletedCallbackForTesting(run_loop.QuitClosure());
    run_loop.Run();

    ASSERT_TRUE(http_request_.get());
    EXPECT_EQ(
        "/drive/v2/files?maxResults=2&q=testing-query&fields=testing-fields",
        http_request_->relative_url);
    EXPECT_FALSE(response_error_.get());
  }

  // The last backoff, decreasing the number of results to 1.
  {
    SetFakeServerResponse(net::HTTP_INTERNAL_SERVER_ERROR,
                          kResponseTooLargeErrorResource);

    base::RunLoop run_loop;
    on_completed_callback_ = run_loop.QuitClosure();
    run_loop.Run();

    ASSERT_TRUE(http_request_.get());
    EXPECT_EQ(
        "/drive/v2/files?maxResults=1&q=testing-query&fields=testing-fields",
        http_request_->relative_url);

    ASSERT_TRUE(response_error_.get());
    EXPECT_EQ(DRIVE_RESPONSE_TOO_LARGE, *response_error_);
    EXPECT_FALSE(response_entry_.get());
  }
}

TEST_F(FilesListRequestRunnerTest, Failure_AnotherError) {
  SetFakeServerResponse(net::HTTP_INTERNAL_SERVER_ERROR,
                        kQuotaExceededErrorResource);
  runner_->CreateAndStartWithSizeBackoff(
      kMaxResults, kQuery, kFields,
      base::Bind(&FilesListRequestRunnerTest::OnCompleted,
                 base::Unretained(this)));

  base::RunLoop run_loop;
  on_completed_callback_ = run_loop.QuitClosure();
  run_loop.Run();

  ASSERT_TRUE(http_request_.get());
  EXPECT_EQ(
      "/drive/v2/files?maxResults=4&q=testing-query&fields=testing-fields",
      http_request_->relative_url);

  // There must be no backoff in case of an error different than
  // DRIVE_RESPONSE_TOO_LARGE.
  ASSERT_TRUE(response_error_.get());
  EXPECT_EQ(DRIVE_NO_SPACE, *response_error_);
  EXPECT_FALSE(response_entry_.get());
}

}  // namespace google_apis


text:
package org.cloudfoundry.client.v2.spacequotadefinitions;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.client.v2.PaginatedResponse;
import org.immutables.value.Value;

/**
 * The response payload for the List Space Quota Definitions operation
 */
@JsonDeserialize
@Value.Immutable
abstract class _ListSpaceQuotaDefinitionsResponse extends PaginatedResponse<SpaceQuotaDefinitionResource> {

}


text:
<?php

namespace OAuthServer\Model\Storage;

use Cake\ORM\Entity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Storage\SessionInterface;

class SessionStorage extends AbstractStorage implements SessionInterface
{
    /**
     * {@inheritdoc}
     */
    public function getByAccessToken(AccessTokenEntity $accessToken)
    {
        $this->loadModel('OAuthServer.Sessions');
        $result = $this->Sessions->find()
            ->matching('AccessTokens', function ($q) use ($accessToken) {
                return $q->where([
                            'oauth_token' => $accessToken->getId()
                        ]);
            })
            ->first();

        if ($result) {
            $session = new SessionEntity($this->server);
            $session->setId($result->id);
            $session->setOwner($result->owner_model, $result->owner_id);

            return $session;
        }

        return;
    }

    /**
     * {@inheritdoc}
     */
    public function getByAuthCode(AuthCodeEntity $authCode)
    {
        $this->loadModel('OAuthServer.Sessions');
        $result = $this->Sessions->find()
            ->matching('AuthCodes', function ($q) use ($authCode) {
                return $q->where([
                            'code' => $authCode->getId()
                        ]);
            })
            ->first();

        if ($result) {
            $session = new SessionEntity($this->server);
            $session->setId($result->id);
            $session->setOwner($result->owner_model, $result->owner_id);

            return $session;
        }

        return;
    }

    /**
     * {@inheritdoc}
     */
    public function getScopes(SessionEntity $session)
    {
        $this->loadModel('OAuthServer.SessionScopes');
        $result = $this->SessionScopes->find()
            ->contain([
                    'Scopes'
                ])
            ->where([
                    'session_id' => $session->getId()
                ])
            ->map(function (Entity $scope) {
                return (new ScopeEntity($this->server))->hydrate([
                        'id' => $scope->scope->id,
                        'description' => $scope->scope->description,
                    ]);
            });

        return $result->toArray();
    }

    /**
     * {@inheritdoc}
     */
    public function create($ownerType, $ownerId, $clientId, $clientRedirectUri = null)
    {
        $this->loadModel('OAuthServer.Sessions');
        $session = $this->Sessions->newEntity([
                'owner_model' => $ownerType,
                'owner_id' => $ownerId,
                'client_id' => $clientId,
            ]);
        $this->Sessions->save($session);

        return $session->id;
    }

    /**
     * {@inheritdoc}
     */
    public function associateScope(SessionEntity $session, ScopeEntity $scope)
    {
        $this->loadModel('OAuthServer.SessionScopes');
        $sessionScope = $this->SessionScopes->newEntity([
                'session_id' => $session->getId(),
                'scope_id' => $scope->getId(),
            ]);
        $this->SessionScopes->save($sessionScope);
    }
}