text:
#ifndef __D3D10MISC_H__
#define __D3D10MISC_H__

#include "d3d10.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef enum D3D10_DRIVER_TYPE {
    D3D10_DRIVER_TYPE_HARDWARE  = 0,
    D3D10_DRIVER_TYPE_REFERENCE = 1,
    D3D10_DRIVER_TYPE_NULL      = 2,
    D3D10_DRIVER_TYPE_SOFTWARE  = 3,
} D3D10_DRIVER_TYPE;

HRESULT WINAPI D3D10CreateDevice(IDXGIAdapter *adapter, D3D10_DRIVER_TYPE driver_type,
        HMODULE swrast, UINT flags, UINT sdk_version, ID3D10Device **device);

HRESULT WINAPI D3D10CreateDeviceAndSwapChain(IDXGIAdapter *adapter, D3D10_DRIVER_TYPE driver_type,
        HMODULE swrast, UINT flags, UINT sdk_version, DXGI_SWAP_CHAIN_DESC *swapchain_desc,
        IDXGISwapChain **swapchain, ID3D10Device **device);

HRESULT WINAPI D3D10CreateBlob(SIZE_T data_size, ID3D10Blob **blob);

#ifdef __cplusplus
}
#endif

#endif /* __D3D10MISC_H__ */

redpajama_set_name: RedPajamaGithub


text:
class PipelineSerializer < BaseSerializer
  InvalidResourceError = Class.new(StandardError)

  entity PipelineEntity

  def with_pagination(request, response)
    tap { @paginator = Gitlab::Serializer::Pagination.new(request, response) }
  end

  def paginated?
    @paginator.present?
  end

  def represent(resource, opts = {})
    if resource.is_a?(ActiveRecord::Relation)
      resource = resource.preload([
        :retryable_builds,
        :cancelable_statuses,
        :trigger_requests,
        :project,
        { pending_builds: :project },
        { manual_actions: :project },
        { artifacts: :project }
      ])
    end

    if paginated?
      super(@paginator.paginate(resource), opts)
    else
      super(resource, opts)
    end
  end

  def represent_status(resource)
    return {} unless resource.present?

    data = represent(resource, { only: [{ details: [:status] }] })
    data.dig(:details, :status) || {}
  end
end


text:
"""
Test for recognizing default settings.

Also helps to keeping them in line.
"""

def test_defaults(default_config):
    """Load defaults config for fullauth."""
    # Config should get created based on fullauth defaults
    assert "fullauth" in default_config.registry
    # also hashalg should be anything but not md5 by default.
    assert default_config.registry["fullauth"]["authtkt"]["hashalg"] != "md5"


text:
<!DOCTYPE html>

    <title>Hello World!</title>
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
    <link href="assets/css/angular-toastr.css" rel="stylesheet" />
    <link href="assets/css/font-awesome.css" rel="stylesheet" />
    <link href="assets/css/weather-icons.css" rel="stylesheet" />
    <link href="assets/css/weather-icons-wind.css" rel="stylesheet" />
    <link href="assets/css/app.css" rel="stylesheet" />

Hello World!


text:
/**
 * @flow
 */
const DirectoryRole: AXObjectModelDefinition = {
  relatedConcepts: [
    {
      module: 'ARIA',
      concept: {
        name: 'directory',
      },
    },
    {
      module: 'HTML',
      concept: {
        name: 'dir',
      },
    },
  ],
  type: 'structure',
};

export default DirectoryRole;


text:
    {% if field.label %}
        {{ field.label }}
    {% endif %}
    {% if style.inline %}

        {% for key, text in field.choices.items %}

                <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}>
                {{ text }}

        {% endfor %}

    {% else %}
        {% for key, text in field.choices.items %}

                <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}>
                {{ text }}

        {% endfor %}
    {% endif %}
    {% if field.errors %}
        {% for error in field.errors %}{{ error }}{% endfor %}
    {% endif %}
    {% if field.help_text %}
        {{ field.help_text }}
    {% endif %}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.apache.guacamole.io.GuacamoleReader (guacamole-common 1.0.0 API)</title>
<meta name="date" content="2018-12-21">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.guacamole.io.GuacamoleReader

Packages that use GuacamoleReader

Package
Description

org.apache.guacamole.io

All classes relating directly to data input or output.

org.apache.guacamole.net

Classes which apply to network-specific concepts, such as low-level sockets
 and tunnels.

org.apache.guacamole.protocol

Classes relating directly to the Guacamole protocol.

Uses of GuacamoleReader in org.apache.guacamole.io

Classes in org.apache.guacamole.io that implement GuacamoleReader

Modifier and Type
Class and Description

class
ReaderGuacamoleReader

A GuacamoleReader which wraps a standard Java Reader, using that Reader as
 the Guacamole instruction stream.

Uses of GuacamoleReader in org.apache.guacamole.net

Methods in org.apache.guacamole.net that return GuacamoleReader

Modifier and Type
Method and Description

GuacamoleReader
AbstractGuacamoleTunnel.acquireReader()

Acquires exclusive read access to the Guacamole instruction stream
 and returns a GuacamoleReader for reading from that stream.

GuacamoleReader
GuacamoleTunnel.acquireReader()

Acquires exclusive read access to the Guacamole instruction stream
 and returns a GuacamoleReader for reading from that stream.

GuacamoleReader
DelegatingGuacamoleTunnel.acquireReader()

GuacamoleReader
InetGuacamoleSocket.getReader()

GuacamoleReader
GuacamoleSocket.getReader()

Returns a GuacamoleReader which can be used to read from the
 Guacamole instruction stream associated with the connection
 represented by this GuacamoleSocket.

GuacamoleReader
SSLGuacamoleSocket.getReader()

Uses of GuacamoleReader in org.apache.guacamole.protocol

Classes in org.apache.guacamole.protocol that implement GuacamoleReader

Modifier and Type
Class and Description

class
FilteredGuacamoleReader

GuacamoleReader which applies a given GuacamoleFilter to observe or alter all
 read instructions.

Methods in org.apache.guacamole.protocol that return GuacamoleReader

Modifier and Type
Method and Description

GuacamoleReader
ConfiguredGuacamoleSocket.getReader()

GuacamoleReader
FilteredGuacamoleSocket.getReader()

GuacamoleReader
FailoverGuacamoleSocket.getReader()

Constructors in org.apache.guacamole.protocol with parameters of type GuacamoleReader

Constructor and Description

FilteredGuacamoleReader(GuacamoleReader reader,
                       GuacamoleFilter filter)

Wraps the given GuacamoleReader, applying the given filter to all read
 instructions.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2018. All rights reserved.


text:
var assert = require('assert');

var cassie = require('../lib/cassie'),
    Schema = cassie.Schema;

var connectOptions = {hosts: ["127.0.0.1:9042"], keyspace: "CassieTest"};
cassie.connect(connectOptions);

var FishSchema = new Schema({
    fish_id: {type: Number, primary: true},
    name: String
});

cassie.model('Fish', FishSchema);

cassie.syncTables(connectOptions, function(err) {
    //Create Example (assuming schemas have been defined and sync'ed - see sync for more information)
    var Fish = cassie.model('Fish');

    var fishee = new Fish({fish_id: 2001, name: 'eevee'});
    fishee.save(function(err) {
        //Handle errors, etc.
    });

//Read Example (assuming schemas have been defined & sync'ed - see sync for more information)
    var Fish = cassie.model('Fish');

    Fish.find({fish_id: {$in: [2000, 2001, 2002, 2003, 2004]}}).exec(function(err, fishes) {
        if (err) console.log(err);

        console.log(fishes.toString());
        var firstFish = fishes[0]; //...
    });

//Update Example (assuming schemas have been defined & sync'ed - see sync for more information)

    var Fish = cassie.model('Fish');

    var fishee2 = new Fish({fish_id: 2002, name: 'eevee'});
    fishee2.save(function(err) {
        if(err) console.log(err);
        //Renaming the fish
        fishee2.name = 'bambie';

        fishee2.save(function(err) {
            //fishee2 has now been renamed (Cassie internally stores a flag to know when you've modified fields - for arrays and maps, you must specified that a field has been modified using the fishee2.markModified('fieldName'); method though (see 'Modeling' for an example).
        });
    });

//Alternatively, you can also send update queries if you know some information about the model

    var Fish = cassie.model('Fish');
    var fish_id3 = 2003; //Assumes fish_id is a number. If uuid, would need to pass uuid as a string

    Fish.update({fish_id: fish_id3}, {name: 'bambie'}, function(err) {
        if(err) console.log(err);
        //Fish with id 2000 has had its name updated
        //If no fish with id exists, returns error
    });

//Fish.update can also take multiple ids in the same way as find: {id: {$in: [1234,1235]} or {id: [1234,1235]}

//Delete Example (assuming schemas have been defined & sync'ed - see sync for more information)

    var Fish = cassie.model('Fish');

    var fishee4 = new Fish({fish_id: 2004, name: 'goldee'});
    fishee4.save(function(err) {
        if(err) console.log(err);

        fishee4.remove(function(err) {
            if(err) console.log(err);
            //Fishee has been removed.
        });
    });

//Alternatively, you can also send delete queries if you know some information about the model (that Cassandra indexes by)

    var Fish = cassie.model('Fish');
    var fish_id5 = 2005; //Assumes fish_id is a number. If uuid, would need to pass uuid as a string

    Fish.remove({fish_id: fish_id5}, 'name', function(err) {
        if(err) console.log(err);
        //Fish with id 2001 has had its name deleted
    });

//To delete entire row, ignore second argument. Ex:
//Fish.remove({id: fish_id5}, function(err) {
//Your callback code
//});

//Fish.remove can also take multiple ids in the same way as find: {id: {$in: [1234,1235]} or {id: [1234,1235]}
});


text:
import { createGlue, doneAllGlues } from "../initializer";
import { expect } from "chai";

describe("bus", () => {
    afterEach(async () => {
        await doneAllGlues();
    });

    it("publish and subscribe for messages from everyone", (done) => {
        Promise.all([
            createGlue("publisherApp1", true),
            createGlue("subscriberApp1", true)
        ]).then(([publisherApp, subscriberApp]) => {
            subscriberApp.bus.subscribe("cars", (data, topic, source) => {
                expect(data).to.eql({ maker: "bmw" });
                expect(topic).to.equal("cars");
                expect(source.application).to.equal("publisherApp1");
                done();
            }).then(() => {
                publisherApp.bus.publish("cars", { maker: "bmw" });
            });
        });
    });

    it("publish and subscribe for messages from specific app", (done) => {
        Promise.all([
            createGlue("publisherApp2", true),
            createGlue("subscriberApp2", true)
        ]).then(([publisherApp, subscriberApp]) => {
            subscriberApp.bus.subscribe("cars", (data, topic, source) => {
                expect(data).to.eql({ maker: "bmw" });
                expect(topic).to.equal("cars");
                expect(source.application).to.equal("publisherApp2");
                done();
            }, { target: { application: "publisherApp2" } }).then(() => {
                publisherApp.bus.publish("cars", { maker: "bmw" }, { target: { application: "subscriberApp2" } });
            });
        });
    });

    it("publish and subscribe for messages with specific routing key", (done) => {
        Promise.all([
            createGlue("publisherApp3", true),
            createGlue("subscriberApp3", true)
        ]).then(([publisherApp, subscriberApp]) => {
            subscriberApp?.bus.subscribe("cars", (data, topic, source) => {
                expect(data).to.eql({ maker: "bmw" });
                expect(topic).to.equal("cars");
                expect(source.application).to.equal("publisherApp3");
                done();
            }, { routingKey: "key" }).then(() => {
                publisherApp?.bus.publish("cars", { maker: "bmw" }, { routingKey: "key" });
            });
        });
    });

    it("publish a message with routing key and receiving it in subscription without routing key", (done) => {
        Promise.all([
            createGlue("publisherApp4", true),
            createGlue("subscriberApp4", true)
        ]).then(([publisherApp, subscriberApp]) => {
            subscriberApp?.bus.subscribe("cars", (data, topic, source) => {
                expect(data).to.eql({ maker: "bmw" });
                expect(topic).to.equal("cars");
                expect(source.application).to.equal("publisherApp4");
                done();
            }).then(() => {
                publisherApp?.bus.publish("cars", { maker: "bmw" }, { routingKey: "key" });
            });
        });
    });

    it("publish a message with without key and receiving it in subscription with routing key", (done) => {
        Promise.all([
            createGlue("publisherApp5", true),
            createGlue("subscriberApp5", true)
        ]).then(([publisherApp, subscriberApp]) => {
            subscriberApp?.bus.subscribe("cars", (data, topic, source) => {
                expect(data).to.eql({ maker: "bmw" });
                expect(topic).to.equal("cars");
                expect(source.application).to.equal("publisherApp5");
                done();
            }, { routingKey: "key" }).then(() => {
                publisherApp?.bus.publish("cars", { maker: "bmw" });
            });
        });
    });

    it("not receiving messages when routing keys do not match", (done) => {
        let callbackCalled = false;
        Promise.all([
            createGlue("publisherApp6", true),
            createGlue("subscriberApp6", true)
        ]).then(([publisherApp, subscriberApp]) => {
            subscriberApp?.bus.subscribe("cars", () => {
                callbackCalled = true;
            }, { routingKey: "key1" }).then(() => {
                publisherApp?.bus.publish("cars", { maker: "bmw" }, { routingKey: "key2" });
            });
        });

        setTimeout(() => {
            expect(callbackCalled).to.equal(false);
            done();
        }, 1000);
    });

    it("not receiving messages when targets do not match", (done) => {
        let callbackCalled = false;
        Promise.all([
            createGlue("publisherApp7", true),
            createGlue("subscriberApp7", true)
        ]).then(([publisherApp, subscriberApp]) => {
            subscriberApp?.bus.subscribe("cars", () => {
                callbackCalled = true;
            }).then(() => {
                publisherApp?.bus.publish("cars", { maker: "bmw" }, { target: { application: "no-existing-app" } });
            });
        });

        setTimeout(() => {
            expect(callbackCalled).to.equal(false);
            done();
        }, 1000);
    });
});


text:
module Jekyll

  class NoTechGeneratorPage < Generator
    safe true

    def generate(site)
      paginate(site)
    end

    def paginate(site)
      posts = site.posts.find_all {|post| post.data['is_non-tech'] == true && post.data['is_extend'] != true}.sort_by {|post| -post.date.to_f}
      num_pages = NoTechPagerPa.calculate_pages(posts, site.config['paginate'].to_i)

      (1..num_pages).each do |page|
        pager = NoTechPagerPa.new(site, page, posts, num_pages)
        dir = File.join(site.config['non-tech_dir'] || 'no-tech', page > 1 ? "page#{page}" : '')
        page = NoTechPagePa.new(site, site.source, dir)
        page.pager = pager
        site.pages << page
      end
    end
  end

  class NoTechPagePa < Page
    def initialize(site, base, dir)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.html'
      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'tech.html')
      self.data['switch'] = 'business'
      self.data['tag'] = 'business'
    end
  end

  class NoTechPagerPa < Jekyll::Paginate::Pager

    def initialize(site, page, all_posts, num_pages = nil)
      super site, page, all_posts, num_pages
    end

    alias_method :original_to_liquid, :to_liquid

    def to_liquid
      liquid = original_to_liquid
      liquid
    end
  end

end


text:
package com.github.ruediste.rise.component.render;

import java.util.Optional;

import com.github.ruediste.rise.component.components.ComponentTemplateBase;
import com.github.ruediste.rise.component.tree.Component;
import com.github.ruediste.rise.integration.RiseCanvas;

public class TestComponent extends Component<TestComponent> {

    private Runnable body;

    @ComponentState
    private String stateValueString;

    @ComponentState
    private Optional<String> stateValueOptional = Optional.empty();

    public static class Template extends ComponentTemplateBase<TestComponent> {

        @Override
        public void doRender(TestComponent component, RiseCanvas<?> html) {
            html.div().rCOMPONENT_ATTRIBUTES(component).render(component.body)._div();
        }
    }

    public TestComponent body(Runnable body) {
        this.body = body;
        return this;
    }

    public String getStateValueString() {
        return stateValueString;
    }

    public TestComponent setStateValueString(String stateValueString) {
        this.stateValueString = stateValueString;
        return this;
    }

    public Optional<String> getStateValueOptional() {
        return stateValueOptional;
    }

    public TestComponent setStateValueOptional(Optional<String> stateValueOptional) {
        this.stateValueOptional = stateValueOptional;
        return this;
    }
}


text:
import {Component} from '@angular/core';

@Component({
    selector: 'navigation',
    templateUrl: './app/modules/navigation.component.template.html'
})
export class NavigationComponent {
  constructor() {
    console.log('navigation module loaded');
  }
}


text:
"""Data specific utilities."""
import warnings
import numpy as np

from ..utils import _var_names
from .converters import convert_to_dataset

def extract_dataset(
    data,
    group="posterior",
    combined=True,
    var_names=None,
    filter_vars=None,
    num_samples=None,
    rng=None,
):
    """Extract an InferenceData group or subset of it.

    .. deprecated:: 0.13
            `extract_dataset` will be removed in ArviZ 0.14, it is replaced by
            `extract` because the latter allows to obtain both DataSets and DataArrays.
    """
    warnings.warn(
        "extract_dataset has been deprecated, please use extract", FutureWarning, stacklevel=2
    )

    data = extract(
        data=data,
        group=group,
        combined=combined,
        var_names=var_names,
        filter_vars=filter_vars,
        num_samples=num_samples,
        rng=rng,
    )
    return data

def extract(
    data,
    group="posterior",
    combined=True,
    var_names=None,
    filter_vars=None,
    num_samples=None,
    keep_dataset=False,
    rng=None,
):
    """Extract an InferenceData group or subset of it.

    Parameters
    ----------
    idata : InferenceData or InferenceData_like
        InferenceData from which to extract the data.
    group : str, optional
        Which InferenceData data group to extract data from.
    combined : bool, optional
        Combine ``chain`` and ``draw`` dimensions into ``sample``. Won't work if
        a dimension named ``sample`` already exists.
    var_names : str or list of str, optional
        Variables to be extracted. Prefix the variables by `~` when you want to exclude them.
    filter_vars: {None, "like", "regex"}, optional
        If `None` (default), interpret var_names as the real variables names. If "like",
        interpret var_names as substrings of the real variables names. If "regex",
        interpret var_names as regular expressions on the real variables names. A la
        `pandas.filter`.
        Like with plotting, sometimes it's easier to subset saying what to exclude
        instead of what to include
    num_samples : int, optional
        Extract only a subset of the samples. Only valid if ``combined=True``
    keep_dataset : bool, optional
        If true, always return a DataSet. If false (default) return a DataArray
        when there is a single variable.
    rng : bool, int, numpy.Generator, optional
        Shuffle the samples, only valid if ``combined=True``. By default,
        samples are shuffled if ``num_samples`` is not ``None``, and are left
        in the same order otherwise. This ensures that subsetting the samples doesn't return
        only samples from a single chain and consecutive draws.

    Returns
    -------
    xarray.DataArray or xarray.Dataset

    Examples
    --------
    The default behaviour is to return the posterior group after stacking the chain and
    draw dimensions.

    .. jupyter-execute::

        import arviz as az
        idata = az.load_arviz_data("centered_eight")
        az.extract(idata)

    You can also indicate a subset to be returned, but in variables and in samples:

    .. jupyter-execute::

        az.extract(idata, var_names="theta", num_samples=100)

    To keep the chain and draw dimensions, use ``combined=False``.

    .. jupyter-execute::

        az.extract(idata, group="prior", combined=False)

    """
    if num_samples is not None and not combined:
        raise ValueError("num_samples is only compatible with combined=True")
    if rng is None:
        rng = num_samples is not None
    if rng is not False and not combined:
        raise ValueError("rng is only compatible with combined=True")
    data = convert_to_dataset(data, group=group)
    var_names = _var_names(var_names, data, filter_vars)
    if var_names is not None:
        if len(var_names) == 1 and not keep_dataset:
            var_names = var_names[0]
        data = data[var_names]
    if combined:
        data = data.stack(sample=("chain", "draw"))
    # 0 is a valid seed se we need to check for rng being exactly boolean
    if rng is not False:
        if rng is True:
            rng = np.random.default_rng()
        # default_rng takes ints or sequences of ints
        try:
            rng = np.random.default_rng(rng)
            random_subset = rng.permutation(np.arange(len(data["sample"])))
        except TypeError as err:
            raise TypeError("Unable to initializate numpy random Generator from rng") from err
        except AttributeError as err:
            raise AttributeError("Unable to use rng to generate a permutation") from err
        data = data.isel(sample=random_subset)
    if num_samples is not None:
        data = data.isel(sample=slice(None, num_samples))
    return data


text:
package dev.jeka.core.api.j2e;

import dev.jeka.core.api.file.JkPathFile;
import dev.jeka.core.api.file.JkPathTree;
import dev.jeka.core.api.system.JkLog;
import dev.jeka.core.api.utils.JkUtilsPath;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class JkJ2eWarArchiver {

    private Path classDir;

    private Path webappDir;

    private List<Path> libs;

    private Path extraStaticResourceDir;

    private JkJ2eWarArchiver() {
    }

    public static JkJ2eWarArchiver of() {
        return new JkJ2eWarArchiver();
    }

    public JkJ2eWarArchiver setClassDir(Path classDir) {
        this.classDir = classDir;
        return this;
    }

    public JkJ2eWarArchiver setWebappDir(Path webappDir) {
        this.webappDir = webappDir;
        return this;
    }

    public JkJ2eWarArchiver setLibs(List<Path> libs) {
        this.libs = libs;
        return this;
    }

    public JkJ2eWarArchiver setExtraStaticResourceDir(Path extraStaticResourceDir) {
        this.extraStaticResourceDir = extraStaticResourceDir;
        return this;
    }

    public void generateWarDir(Path destDir) {
        JkPathTree webappTree = webappDir != null ? JkPathTree.of(webappDir) : null;
        if (webappTree == null || !webappTree.exists() || !webappTree.containFiles()) {
            JkLog.warn(destDir + " is empty or does not exists.");
        } else {
            webappTree.copyTo(destDir);
        }
        if (extraStaticResourceDir != null && Files.exists(extraStaticResourceDir)) {
            JkPathTree.of(extraStaticResourceDir).copyTo(destDir);
        }
        JkPathTree.of(classDir).copyTo(destDir.resolve("WEB-INF/classes"));
        Path libDir = destDir.resolve("lib");
        JkPathTree.of(libDir).deleteContent();
        libs.forEach(path -> JkPathFile.of(path).copyToDir(libDir));
    }

    public void generateWarFile(Path destFile) {
        Path temp = JkUtilsPath.createTempDirectory("jeka-war");
        generateWarDir(temp);
        JkPathTree.of(temp).zipTo(destFile);
        JkPathTree.of(temp).deleteRoot();
    }

}


text:
#include <Corrade/TestSuite/Compare/Container.h>

#include "Magnum/Buffer.h"
#include "Magnum/BufferTexture.h"
#include "Magnum/BufferTextureFormat.h"
#include "Magnum/ImageFormat.h"
#include "Magnum/Test/AbstractOpenGLTester.h"

namespace Magnum { namespace Test {

struct BufferTextureGLTest: AbstractOpenGLTester {
    explicit BufferTextureGLTest();

    void construct();
    void constructNoCreate();
    void wrap();

    void bind();
    void bindImage();

    void setBuffer();
    void setBufferOffset();
};

BufferTextureGLTest::BufferTextureGLTest() {
    addTests({&BufferTextureGLTest::construct,
              &BufferTextureGLTest::constructNoCreate,
              &BufferTextureGLTest::wrap,

              &BufferTextureGLTest::bind,
              &BufferTextureGLTest::bindImage,

              &BufferTextureGLTest::setBuffer,
              &BufferTextureGLTest::setBufferOffset});
}

void BufferTextureGLTest::construct() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_buffer_object>())
        CORRADE_SKIP(Extensions::GL::ARB::texture_buffer_object::string() + std::string(" is not supported."));
    #else
    if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_buffer>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_buffer::string() + std::string(" is not supported."));
    #endif

    {
        BufferTexture texture;

        MAGNUM_VERIFY_NO_ERROR();
        CORRADE_VERIFY(texture.id() > 0);
    }

    MAGNUM_VERIFY_NO_ERROR();
}

void BufferTextureGLTest::constructNoCreate() {
    {
        BufferTexture texture{NoCreate};

        MAGNUM_VERIFY_NO_ERROR();
        CORRADE_COMPARE(texture.id(), 0);
    }

    MAGNUM_VERIFY_NO_ERROR();
}

void BufferTextureGLTest::wrap() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_buffer_object>())
        CORRADE_SKIP(Extensions::GL::ARB::texture_buffer_object::string() + std::string(" is not supported."));
    #else
    if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_buffer>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_buffer::string() + std::string(" is not supported."));
    #endif

    GLuint id;
    glGenTextures(1, &id);

    /* Releasing won't delete anything */
    {
        auto texture = BufferTexture::wrap(id, ObjectFlag::DeleteOnDestruction);
        CORRADE_COMPARE(texture.release(), id);
    }

    /* ...so we can wrap it again */
    BufferTexture::wrap(id);
    glDeleteTextures(1, &id);
}

void BufferTextureGLTest::bind() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_buffer_object>())
        CORRADE_SKIP(Extensions::GL::ARB::texture_buffer_object::string() + std::string(" is not supported."));
    #else
    if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_buffer>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_buffer::string() + std::string(" is not supported."));
    #endif

    BufferTexture texture;
    texture.bind(15);

    MAGNUM_VERIFY_NO_ERROR();

    AbstractTexture::unbind(15);

    MAGNUM_VERIFY_NO_ERROR();

    AbstractTexture::bind(7, {&texture, nullptr, &texture});

    MAGNUM_VERIFY_NO_ERROR();

    AbstractTexture::unbind(7, 3);

    MAGNUM_VERIFY_NO_ERROR();
}

void BufferTextureGLTest::bindImage() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_buffer_object>())
        CORRADE_SKIP(Extensions::GL::ARB::texture_buffer_object::string() + std::string(" is not supported."));
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::shader_image_load_store>())
        CORRADE_SKIP(Extensions::GL::ARB::shader_image_load_store::string() + std::string(" is not supported."));
    #else
    if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_buffer>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_buffer::string() + std::string(" is not supported."));
    if(!Context::current().isVersionSupported(Version::GLES310))
        CORRADE_SKIP("OpenGL ES 3.1 is not supported.");
    #endif

    Buffer buffer;
    buffer.setData({nullptr, 32}, BufferUsage::StaticDraw);

    BufferTexture texture;
    texture.setBuffer(BufferTextureFormat::RGBA8, buffer)
        .bindImage(2, ImageAccess::ReadWrite, ImageFormat::RGBA8);

    MAGNUM_VERIFY_NO_ERROR();

    AbstractTexture::unbindImage(2);

    MAGNUM_VERIFY_NO_ERROR();

    #ifndef MAGNUM_TARGET_GLES
    AbstractTexture::bindImages(1, {&texture, nullptr, &texture});

    MAGNUM_VERIFY_NO_ERROR();

    AbstractTexture::unbindImages(1, 3);

    MAGNUM_VERIFY_NO_ERROR();
    #endif
}

void BufferTextureGLTest::setBuffer() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_buffer_object>())
        CORRADE_SKIP(Extensions::GL::ARB::texture_buffer_object::string() + std::string(" is not supported."));
    #else
    if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_buffer>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_buffer::string() + std::string(" is not supported."));
    #endif

    BufferTexture texture;
    Buffer buffer;
    constexpr UnsignedByte data[] = {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
    };
    buffer.setData(data, BufferUsage::StaticDraw);
    texture.setBuffer(BufferTextureFormat::R8UI, buffer);

    MAGNUM_VERIFY_NO_ERROR();
}

void BufferTextureGLTest::setBufferOffset() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_buffer_object>())
        CORRADE_SKIP(Extensions::GL::ARB::texture_buffer_object::string() + std::string(" is not supported."));
    if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_buffer_range>())
        CORRADE_SKIP(Extensions::GL::ARB::texture_buffer_range::string() + std::string(" is not supported."));
    #else
    if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_buffer>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_buffer::string() + std::string(" is not supported."));
    #endif

    /* Check that we have correct offset alignment */
    CORRADE_INTERNAL_ASSERT(256 % BufferTexture::offsetAlignment() == 0);

    BufferTexture texture;
    Buffer buffer;
    constexpr UnsignedByte data[] = {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
        0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
    };
    buffer.setData({nullptr, 1024}, BufferUsage::StaticDraw);
    buffer.setSubData(256 - 16, data);
    texture.setBuffer(BufferTextureFormat::R8UI, buffer, 256, 8);

    MAGNUM_VERIFY_NO_ERROR();
}

}}

MAGNUM_GL_TEST_MAIN(Magnum::Test::BufferTextureGLTest)


text:
<?php

namespace Plank\Mediable\Tests\Integration\UrlGenerators;

use Plank\Mediable\Exceptions\MediaUrlException;
use Plank\Mediable\Media;
use Plank\Mediable\Tests\TestCase;
use Plank\Mediable\UrlGenerators\UrlGeneratorFactory;
use Plank\Mediable\UrlGenerators\UrlGeneratorInterface;
use stdClass;

class UrlGeneratorFactoryTest extends TestCase
{
    public function test_it_sets_generator_for_driver()
    {
        $factory = new UrlGeneratorFactory;
        $generator = $this->getMockClass(UrlGeneratorInterface::class);

        $media = factory(Media::class)->make(['disk' => 'uploads']);

        $factory->setGeneratorForFilesystemDriver($generator, 'local');
        $result = $factory->create($media);
        $this->assertInstanceOf($generator, $result);
    }

    public function test_it_throws_exception_for_invalid_generator()
    {
        $factory = new UrlGeneratorFactory;
        $class = $this->getMockClass(stdClass::class);
        $this->expectException(MediaUrlException::class);
        $factory->setGeneratorForFilesystemDriver($class, 'foo');
    }

    public function test_it_throws_exception_if_cant_map_to_driver()
    {
        $factory = new UrlGeneratorFactory;
        $media = factory(Media::class)->make();
        $this->expectException(MediaUrlException::class);
        $factory->create($media);
    }
}


text:
package org.codehaus.groovy.ast;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Represents a variable scope. This is primarily used to determine variable sharing
 * across method and closure boundaries.
 */
public class VariableScope  {
    private Map<String, Variable> declaredVariables = Collections.emptyMap();
    private Map<String, Variable> referencedLocalVariables = Collections.emptyMap();
    private Map<String, Variable> referencedClassVariables = Collections.emptyMap();

    private boolean inStaticContext = false;
    private boolean resolvesDynamic = false;
    // Non-null iff this scope corresponds to a class, as opposed to a method, "if" statement,
    // block statement, etc.
    private ClassNode clazzScope;
    private VariableScope parent;

    public VariableScope() {
    }
    public VariableScope(VariableScope parent) {
        this.parent = parent;
    }

    public Variable getDeclaredVariable(String name) {
        return declaredVariables.get(name);
    }

    public boolean isReferencedLocalVariable(String name) {
        return referencedLocalVariables.containsKey(name);
    }

    public boolean isReferencedClassVariable(String name) {
        return referencedClassVariables.containsKey(name);
    }
    public VariableScope getParent() {
        return parent;
    }

    public boolean isInStaticContext() {
        return inStaticContext;
    }

    public void setInStaticContext(boolean inStaticContext) {
        this.inStaticContext = inStaticContext;
    }

    public void setClassScope(ClassNode node) {
        this.clazzScope = node;
    }

    /**
     * Non-null iff this scope corresponds to a class; as opposed to a method, "if" statement,
     * block statement, etc.
     */
    public ClassNode getClassScope(){
        return clazzScope;
    }

    /**
     * Returns true iff this scope corresponds to a class; as opposed to a method, "if" statement,
     * block statement, etc.
     */
    public boolean isClassScope(){
        return clazzScope!=null;
    }

    public boolean isRoot() {
        return parent==null;
    }

    public VariableScope copy() {
        VariableScope copy = new VariableScope();
        copy.clazzScope = clazzScope;
        if (!declaredVariables.isEmpty()) {
          copy.declaredVariables = new LinkedHashMap<String, Variable>(declaredVariables);
        }
        copy.inStaticContext = inStaticContext;
        copy.parent = parent;
        if (!referencedClassVariables.isEmpty()) {
            copy.referencedClassVariables = new LinkedHashMap<String, Variable>(referencedClassVariables);
        }
        if (!referencedLocalVariables.isEmpty()) {
            copy.referencedLocalVariables = new LinkedHashMap<String, Variable>(referencedLocalVariables);
        }
        copy.resolvesDynamic = resolvesDynamic;
        return copy;
    }

    public void putDeclaredVariable(Variable var) {
        if (declaredVariables == Collections.EMPTY_MAP)
          declaredVariables = new LinkedHashMap<String, Variable>();
        declaredVariables.put(var.getName(), var);
    }

    public Iterator<Variable> getReferencedLocalVariablesIterator() {
        return referencedLocalVariables.values().iterator();
    }

    public int getReferencedLocalVariablesCount() {
        return referencedLocalVariables.size();
    }

    public Variable getReferencedLocalVariable(String name) {
        return referencedLocalVariables.get(name);
    }

    public void putReferencedLocalVariable(Variable var) {
        if (referencedLocalVariables == Collections.EMPTY_MAP)
          referencedLocalVariables = new LinkedHashMap<String, Variable>();
        referencedLocalVariables.put(var.getName(), var);
    }

    public void putReferencedClassVariable(Variable var) {
        if (referencedClassVariables == Collections.EMPTY_MAP)
          referencedClassVariables = new LinkedHashMap<String, Variable>();
        referencedClassVariables.put(var.getName(), var);
    }

    public Variable getReferencedClassVariable(String name) {
        return referencedClassVariables.get(name);
    }

    public Object removeReferencedClassVariable(String name) {
        if (referencedClassVariables == Collections.EMPTY_MAP)
          return null;
        else
          return referencedClassVariables.remove(name);
    }

    /**
     * Gets a map containing the class variables referenced
     * by this scope. This not can not be modified.
     * @return a map containing the class variable references
     */
    public Map<String, Variable> getReferencedClassVariables() {
        if (referencedClassVariables == Collections.EMPTY_MAP) {
            return referencedClassVariables;
        } else {
            return Collections.unmodifiableMap(referencedClassVariables);
        }
    }

    /**
     * Gets an iterator for the referenced class variables. The
     * remove operation is not supported.
     * @return an iterator for the referenced class variables
     */
    public Iterator<Variable> getReferencedClassVariablesIterator() {
        return getReferencedClassVariables().values().iterator();
    }

    /**
     * Gets a map containing the variables declared in this scope.
     * This map cannot be modified.
     * @return a map containing the declared variable references
     */
    public Map<String, Variable> getDeclaredVariables() {
        if (declaredVariables == Collections.EMPTY_MAP) {
            return declaredVariables;
        } else {
            return Collections.unmodifiableMap(declaredVariables);
        }
    }

    /**
     * Gets an iterator for the declared class variables. The remove
     * operation is not supported.
     * @return an iterator for the declared variables
     */
    public Iterator<Variable> getDeclaredVariablesIterator() {
        return getDeclaredVariables().values().iterator();
    }
}


text:
var Movie = require('../api/movie')

//index page
exports.index = function *(next) {
    var categories = yield Movie.findAll()
    yield this.render('pages/index', {
        title: 'imooc 首页',
        categories: categories
    })
}

// search page
exports.search = function *(next) {
    var catId = this.query.cat
    var q = this.query.q
    var page = parseInt(req.query.p, 10) || 0
    var count = 2
    var index = page * count

    if (catId) {
        var categories = yield Movie.searchByCategory(catId)
        var category = categories[0] || {}
        var movies = category.movies || []
        var results = movies.slice(index, index + count)

        yield this.render('pages/results', {
            title: 'imooc 结果列表页面',
            keyword: category.name,
            currentPage: (page + 1),
            query: 'cat=' + catId,
            totalPage: Math.ceil(movies.length / count),
            movies: results
        })
    } else {
        var movies = yield Movie.searchByName(q)
        var results = movies.slice(index, index + count)

        yield this.render('pages/results', {
            title: 'imooc 结果列表页面',
            keyword: q,
            currentPage: (page + 1),
            query: 'q=' + q,
            totalPage: Math.ceil(movies.length / count),
            movies: results
        })
    }
}


text:
package com.facebook.buck.jvm.java;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.StepExecutionResult;
import com.facebook.buck.zip.JarBuilder;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSortedSet;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import javax.annotation.Nullable;

/** Creates a JAR file from a collection of directories/ZIP/JAR files. */
public class JarDirectoryStep implements Step {

  private final ProjectFilesystem filesystem;

  /** Where to write the new JAR file. */
  private final Path pathToOutputFile;

  /** A collection of directories/ZIP/JAR files to include in the generated JAR file. */
  private final ImmutableSortedSet<Path> entriesToJar;

  /** If specified, the Main-Class to list in the manifest of the generated JAR file. */
  @Nullable private final String mainClass;

  /** If specified, the Manifest file to use for the generated JAR file. */
  @Nullable private final Path manifestFile;

  /** Indicates that manifest merging should occur. Defaults to true. */
  private final boolean mergeManifests;

  /** Indicates that the manifest should contain hashes of the entries. Defaults to false. */
  private final boolean hashEntries;

  /** A set of regex. If a file matches one of the regex it will not be included in the Jar. */
  private final RemoveClassesPatternsMatcher blacklist;

  public JarDirectoryStep(
      ProjectFilesystem filesystem,
      Path pathToOutputFile,
      ImmutableSortedSet<Path> entriesToJar,
      @Nullable String mainClass,
      @Nullable Path manifestFile) {
    this(
        filesystem,
        pathToOutputFile,
        entriesToJar,
        mainClass,
        manifestFile,
        true,
        RemoveClassesPatternsMatcher.EMPTY);
  }

  public JarDirectoryStep(
      ProjectFilesystem filesystem,
      Path pathToOutputFile,
      ImmutableSortedSet<Path> entriesToJar,
      @Nullable String mainClass,
      @Nullable Path manifestFile,
      boolean mergeManifests,
      RemoveClassesPatternsMatcher blacklist) {
    this(
        filesystem,
        pathToOutputFile,
        entriesToJar,
        mainClass,
        manifestFile,
        mergeManifests,
        false,
        blacklist);
  }
  /**
   * Creates a JAR from the specified entries (most often, classpath entries).
   *
   *
If an entry is a directory, then its files are traversed and added to the generated JAR.
   *
   *
If an entry is a file, then it is assumed to be a ZIP/JAR file, and its entries will be read
   * and copied to the generated JAR.
   *
   * @param pathToOutputFile The directory that contains this path must exist before this command is
   *     executed.
   * @param entriesToJar Paths to directories/ZIP/JAR files.
   * @param mainClass If specified, the value for the Main-Class attribute in the manifest of the
   *     generated JAR.
   * @param manifestFile If specified, the path to the manifest file to use with this JAR.
   */
  public JarDirectoryStep(
      ProjectFilesystem filesystem,
      Path pathToOutputFile,
      ImmutableSortedSet<Path> entriesToJar,
      @Nullable String mainClass,
      @Nullable Path manifestFile,
      boolean mergeManifests,
      boolean hashEntries,
      RemoveClassesPatternsMatcher blacklist) {
    this.filesystem = filesystem;
    this.pathToOutputFile = pathToOutputFile;
    this.entriesToJar = entriesToJar;
    this.mainClass = mainClass;
    this.manifestFile = manifestFile;
    this.mergeManifests = mergeManifests;
    this.hashEntries = hashEntries;
    this.blacklist = blacklist;
  }

  private String getJarArgs() {
    String result = "cf";
    if (manifestFile != null) {
      result += "m";
    }
    return result;
  }

  @Override
  public String getShortName() {
    return "jar";
  }

  @Override
  public String getDescription(ExecutionContext context) {
    return String.format(
        "jar %s %s %s %s",
        getJarArgs(),
        pathToOutputFile,
        manifestFile != null ? manifestFile : "",
        Joiner.on(' ').join(entriesToJar));
  }

  @Override
  public StepExecutionResult execute(ExecutionContext context)
      throws IOException, InterruptedException {

    JavacEventSinkToBuckEventBusBridge eventSink =
        new JavacEventSinkToBuckEventBusBridge(context.getBuckEventBus());
    return StepExecutionResult.of(
        new JarBuilder()
            .setObserver(new LoggingJarBuilderObserver(eventSink))
            .setEntriesToJar(entriesToJar.stream().map(filesystem::resolve))
            .setMainClass(Optional.ofNullable(mainClass).orElse(null))
            .setManifestFile(manifestFile != null ? filesystem.resolve(manifestFile) : null)
            .setShouldMergeManifests(mergeManifests)
            .setShouldHashEntries(hashEntries)
            .setRemoveEntryPredicate(blacklist::shouldRemoveClass)
            .createJarFile(filesystem.resolve(pathToOutputFile)));
  }
}


text:
<ion-view title="Trip Detail">
	<ion-content class="has-subheader" style="background-color: #eeeeee;">

Distance

{{getFormattedDistance(trip.data.properties.distance)}} km

Time

{{getFormattedTimeRange(trip.data.properties.start_ts,
           trip.data.properties.end_ts)}}

     <leaflet geojson="trip" id="$index" defaults="defaults"></leaflet>

start

km

mode

{{getFormattedTime(section.properties.start_ts)}}

{{getFormattedTimeRange(section.properties.end_ts, section.properties.start_ts)}}

{{getFormattedDistance(section.properties.distance)}}

	</ion-content>
</ion-view>


text:
'''

All VM operations for test.

@author: Youyk
'''

import apibinding.inventory as inventory
import apibinding.api_actions as api_actions
import zstackwoodpecker.test_util as test_util
import account_operations
import config_operations

import os
import inspect

def create_vm(vm_create_option):
    create_vm = api_actions.CreateVmInstanceAction()
    name = vm_create_option.get_name()
    if not name:
        create_vm.name = 'test_vm_default_name'
    else:
        create_vm.name = name

    create_vm.imageUuid = vm_create_option.get_image_uuid()
    create_vm.zoneUuid = vm_create_option.get_zone_uuid()
    create_vm.clusterUuid = vm_create_option.get_cluster_uuid()
    create_vm.hostUuid = vm_create_option.get_host_uuid()
    create_vm.instanceOfferingUuid = vm_create_option.get_instance_offering_uuid()
    create_vm.l3NetworkUuids = vm_create_option.get_l3_uuids()
    create_vm.defaultL3NetworkUuid = vm_create_option.get_default_l3_uuid()
    #If there are more than 1 network uuid, the 1st one will be the default l3.
    if len(create_vm.l3NetworkUuids) > 1 and not create_vm.defaultL3NetworkUuid:
        create_vm.defaultL3NetworkUuid = create_vm.l3NetworkUuids[0]

    vm_type = vm_create_option.get_vm_type()
    if not vm_type:
        create_vm.type = 'UserVm'
    else:
        create_vm.type = vm_type

    create_vm.systemTags = vm_create_option.get_system_tags()
    create_vm.userTags = vm_create_option.get_user_tags()
    timeout = vm_create_option.get_timeout()
    if not timeout:
        create_vm.timeout = 600000
    else:
        create_vm.timeout = timeout

    create_vm.dataDiskOfferingUuids = vm_create_option.get_data_disk_uuids()
    create_vm.rootDiskOfferingUuid = vm_create_option.get_root_disk_uuid()

    test_util.action_logger('Create VM: %s with [image:] %s and [l3_network:] %s' % (create_vm.name, create_vm.imageUuid, create_vm.l3NetworkUuids))
    evt = account_operations.execute_action_with_session(create_vm, vm_create_option.get_session_uuid())
    test_util.test_logger('[vm:] %s is created.' % evt.inventory.uuid)
    return evt.inventory

#The root volume will not be deleted immediately. It will only be reclaimed by system maintenance checking.
def destroy_vm(vm_uuid, session_uuid=None):
    action = api_actions.DestroyVmInstanceAction()
    action.uuid = vm_uuid
    action.timeout = 120000
    test_util.action_logger('Destroy VM [uuid:] %s' % vm_uuid)
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt.inventory

def stop_vm(vm_uuid, session_uuid=None):
    action = api_actions.StopVmInstanceAction()
    action.uuid = vm_uuid
    action.timeout = 120000
    test_util.action_logger('Stop VM [uuid:] %s' % vm_uuid)
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt.inventory

def start_vm(vm_uuid, session_uuid=None, timeout=120000):
    action = api_actions.StartVmInstanceAction()
    action.uuid = vm_uuid
    action.timeout = timeout
    test_util.action_logger('Start VM [uuid:] %s' % vm_uuid)
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt.inventory

def reboot_vm(vm_uuid, session_uuid=None):
    action = api_actions.RebootVmInstanceAction()
    action.uuid = vm_uuid
    action.timeout = 120000
    test_util.action_logger('Reboot VM [uuid:] %s' % vm_uuid)
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt.inventory

def migrate_vm(vm_uuid, host_uuid, timeout = 240000, session_uuid = None):
    action = api_actions.MigrateVmAction()
    action.vmInstanceUuid = vm_uuid
    action.hostUuid = host_uuid
    if not timeout:
        timeout = 240000
    action.timeout = timeout
    test_util.action_logger('Migrate VM [uuid:] %s to Host [uuid:] %s, in timeout: %s' % (vm_uuid, host_uuid, timeout))
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt.inventory

def reconnect_vr(vr_uuid, session_uuid=None):
    action = api_actions.ReconnectVirtualRouterAction()
    action.vmInstanceUuid = vr_uuid
    action.timeout = 300000
    test_util.action_logger('Reconnect VR VM [uuid:] %s' % vr_uuid)
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt.inventory

def change_instance_offering(vm_uuid, offering_uuid, session_uuid=None):
    action = api_actions.ChangeInstanceOfferingAction()
    action.vmInstanceUuid = vm_uuid
    action.instanceOfferingUuid = offering_uuid
    test_util.action_logger('Change VM [uuid:] %s Instance Offering to %s '\
            % (vm_uuid, offering_uuid))
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt

def create_instance_offering(instance_offering_option, session_uuid = None):
    action = api_actions.CreateInstanceOfferingAction()
    action.cpuNum = instance_offering_option.get_cpuNum()
    action.cpuSpeed = instance_offering_option.get_cpuSpeed()
    action.memorySize = instance_offering_option.get_memorySize()
    action.allocatorStrategy = instance_offering_option.get_allocatorStrategy()
    action.type = instance_offering_option.get_type()
    action.name = instance_offering_option.get_name()
    action.description = instance_offering_option.get_description()

    test_util.action_logger('create instance offering: name: %s cpuNum: %s, cpuSpeed: %s, memorySize: %s, allocatorStrategy: %s, type: %s '\
            % (action.name, action.cpuNum, action.cpuSpeed, action.memorySize, action.allocatorStrategy, action.type))
    evt = account_operations.execute_action_with_session(action, session_uuid)
    test_util.test_logger('Instance Offering: %s is created' % evt.inventory.uuid)
    return evt.inventory

def delete_instance_offering(instance_offering_uuid, session_uuid = None):
    action = api_actions.DeleteInstanceOfferingAction()
    action.uuid = instance_offering_uuid
    test_util.action_logger('Delete Instance Offering [uuid:] %s' \
            % instance_offering_uuid)
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt

def expunge_vm(vm_uuid, session_uuid = None):
    action = api_actions.ExpungeVmInstanceAction()
    action.uuid = vm_uuid
    action.timeout = 10000
    test_util.action_logger('Expunge VM [uuid:] %s ' % vm_uuid)
    evt = account_operations.execute_action_with_session(action, session_uuid)
    return evt.inventory


text:
using System;
using TNRD.Automatron.Editor.Core;
using UnityEditor;
using UnityEngine;

namespace TNRD.Automatron.Editor.Windows {

    public class InputBox : ExtendedPopup {

        private Action<EDialogResult, string> callback;

        private EDialogResult result;
        private GUIStyle style;

        private string message = "";
        private string value = "";

        public InputBox( string message ) {
            this.message = message;
        }

        public InputBox( string message, Action<EDialogResult, string> callback ) {
            this.message = message;
            this.callback = callback;
        }

        public InputBox( string title, string message ) {
            WindowContent = new GUIContent( title );
            this.message = message;
        }

        public InputBox( string title, string message, Action<EDialogResult, string> callback ) {
            WindowContent = new GUIContent( title );
            this.message = message;
            this.callback = callback;
        }

        protected override void OnInitializeGUI() {
            style = new GUIStyle( GUI.skin.label );
            style.alignment = TextAnchor.UpperLeft;
            style.wordWrap = true;
        }

        protected override void OnGUI() {
            if ( string.IsNullOrEmpty( message ) ) {
                var rect = new Rect( 20, Size.y / 2 - 8, Size.x - 35, 16 );
                value = EditorGUI.TextField( rect, value );
            } else {
                var recta = new Rect( 20, Size.y / 2 - 20, Size.x - 35, 16 );
                EditorGUI.LabelField( recta, message, style );
                var rect = new Rect( 20, Size.y / 2 - 4, Size.x - 35, 16 );
                value = EditorGUI.TextField( rect, value );
            }

            if ( GUI.Button( new Rect( Size.x - 175, Size.y - 35, 75, 20 ), "OK" ) ) {
                result = EDialogResult.OK;
                Close();
            }
            if ( GUI.Button( new Rect( Size.x - 90, Size.y - 35, 75, 20 ), "Cancel" ) ) {
                result = EDialogResult.Cancel;
                Close();
            }

            if ( Input.KeyReleased( KeyCode.KeypadEnter ) || Input.KeyReleased( KeyCode.Return ) ) {
                result = EDialogResult.OK;
                Close();
            }

            if ( Input.KeyReleased( KeyCode.Escape ) ) {
                result = EDialogResult.Cancel;
                Close();
            }
        }

        public override void Close() {
            if ( callback != null ) {
                callback( result, value );
            }

            base.Close();
        }
    }
}
#endif


text:
using System.Runtime.CompilerServices;

namespace System.Html.Media.Graphics.SVG {
	[Imported]
	public enum SVGFEBlendMode {
		Darken = 4,
		Lighten = 5,
		Multiply = 2,
		Normal = 1,
		Screen = 3,
		Unknown = 0
	}
}


text:
<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Solution;

/**
 * Interface for reference solution representations.
 */
interface SolutionInterface
{
    /**
     * Get the entry point. This is the PHP file that php would execute in order to run the
     * program. This should be the absolute path.
     *
     * @return string
     */
    public function getEntryPoint(): string;

    /**
     * Get all the files which are contained with the solution.
     *
     * @return array<SolutionFile>
     */
    public function getFiles(): array;

    /**
     * Get the absolute path to the directory containing the solution.
     *
     * @return string
     */
    public function getBaseDirectory(): string;

    /**
     * Whether or not the solution has a `composer.json` & `composer.lock` file.
     *
     * @return bool
     */
    public function hasComposerFile(): bool;
}


text:
"""Run Performance Test Bisect Tool

This script is used by a trybot to run the src/tools/bisect-perf-regression.py
script with the parameters specified in run-bisect-perf-regression.cfg. It will
check out a copy of the depot in a subdirectory 'bisect' of the working
directory provided, and run the bisect-perf-regression.py script there.

"""

import imp
import optparse
import os
import platform
import subprocess
import sys
import traceback

from auto_bisect import bisect_utils

bisect = imp.load_source('bisect-perf-regression',
    os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),
        'bisect-perf-regression.py'))

CROS_BOARD_ENV = 'BISECT_CROS_BOARD'
CROS_IP_ENV = 'BISECT_CROS_IP'

class Goma(object):

  def __init__(self, path_to_goma):
    self._abs_path_to_goma = None
    self._abs_path_to_goma_file = None
    if path_to_goma:
      self._abs_path_to_goma = os.path.abspath(path_to_goma)
      self._abs_path_to_goma_file = self._GetExecutablePath(
          self._abs_path_to_goma)

  def __enter__(self):
    if self._HasGOMAPath():
      self._SetupAndStart()
    return self

  def __exit__(self, *_):
    if self._HasGOMAPath():
      self._Stop()

  def _HasGOMAPath(self):
    return bool(self._abs_path_to_goma)

  def _GetExecutablePath(self, path_to_goma):
    if os.name == 'nt':
      return os.path.join(path_to_goma, 'goma_ctl.bat')
    else:
      return os.path.join(path_to_goma, 'goma_ctl.sh')

  def _SetupEnvVars(self):
    if os.name == 'nt':
      os.environ['CC'] = (os.path.join(self._abs_path_to_goma, 'gomacc.exe') +
          ' cl.exe')
      os.environ['CXX'] = (os.path.join(self._abs_path_to_goma, 'gomacc.exe') +
          ' cl.exe')
    else:
      os.environ['PATH'] = os.pathsep.join([self._abs_path_to_goma,
          os.environ['PATH']])

  def _SetupAndStart(self):
    """Sets up GOMA and launches it.

    Args:
      path_to_goma: Path to goma directory.

    Returns:
      True if successful."""
    self._SetupEnvVars()

    # Sometimes goma is lingering around if something went bad on a previous
    # run. Stop it before starting a new process. Can ignore the return code
    # since it will return an error if it wasn't running.
    self._Stop()

    if subprocess.call([self._abs_path_to_goma_file, 'start']):
      raise RuntimeError('GOMA failed to start.')

  def _Stop(self):
    subprocess.call([self._abs_path_to_goma_file, 'stop'])

def _LoadConfigFile(path_to_file):
  """Attempts to load the specified config file as a module
  and grab the global config dict.

  Args:
    path_to_file: Path to the file.

  Returns:
    The config dict which should be formatted as follows:
    {'command': string, 'good_revision': string, 'bad_revision': string
     'metric': string, etc...}.
    Returns None on failure.
  """
  try:
    local_vars = {}
    execfile(path_to_file, local_vars)

    return local_vars['config']
  except:
    print
    traceback.print_exc()
    print
    return {}

def _ValidateConfigFile(config_contents, valid_parameters):
  """Validates the config file contents, checking whether all values are
  non-empty.

  Args:
    config_contents: Contents of the config file passed from _LoadConfigFile.
    valid_parameters: A list of parameters to check for.

  Returns:
    True if valid.
  """
  try:
    [config_contents[current_parameter]
        for current_parameter in valid_parameters]
    config_has_values = [v and type(v) is str
        for v in config_contents.values() if v]
    return config_has_values
  except KeyError:
    return False

def _ValidatePerfConfigFile(config_contents):
  """Validates that the perf config file contents. This is used when we're
  doing a perf try job, rather than a bisect. The file is called
  run-perf-test.cfg by default.

  The parameters checked are the required parameters; any additional optional
  parameters won't be checked and validation will still pass.

  Args:
    config_contents: Contents of the config file passed from _LoadConfigFile.

  Returns:
    True if valid.
  """
  valid_parameters = ['command', 'metric', 'repeat_count', 'truncate_percent',
      'max_time_minutes']
  return _ValidateConfigFile(config_contents, valid_parameters)

def _ValidateBisectConfigFile(config_contents):
  """Validates that the bisect config file contents. The parameters checked are
  the required parameters; any additional optional parameters won't be checked
  and validation will still pass.

  Args:
    config_contents: Contents of the config file passed from _LoadConfigFile.

  Returns:
    True if valid.
  """
  valid_params = ['command', 'good_revision', 'bad_revision', 'metric',
      'repeat_count', 'truncate_percent', 'max_time_minutes']
  return _ValidateConfigFile(config_contents, valid_params)

def _OutputFailedResults(text_to_print):
  bisect_utils.OutputAnnotationStepStart('Results - Failed')
  print
  print text_to_print
  print
  bisect_utils.OutputAnnotationStepClosed()

def _CreateBisectOptionsFromConfig(config):
  opts_dict = {}
  opts_dict['command'] = config['command']
  opts_dict['metric'] = config['metric']

  if config['repeat_count']:
    opts_dict['repeat_test_count'] = int(config['repeat_count'])

  if config['truncate_percent']:
    opts_dict['truncate_percent'] = int(config['truncate_percent'])

  if config['max_time_minutes']:
    opts_dict['max_time_minutes'] = int(config['max_time_minutes'])

  if config.has_key('use_goma'):
    opts_dict['use_goma'] = config['use_goma']
  if config.has_key('goma_dir'):
    opts_dict['goma_dir'] = config['goma_dir']

  opts_dict['build_preference'] = 'ninja'
  opts_dict['output_buildbot_annotations'] = True

  if '--browser=cros' in config['command']:
    opts_dict['target_platform'] = 'cros'

    if os.environ[CROS_BOARD_ENV] and os.environ[CROS_IP_ENV]:
      opts_dict['cros_board'] = os.environ[CROS_BOARD_ENV]
      opts_dict['cros_remote_ip'] = os.environ[CROS_IP_ENV]
    else:
      raise RuntimeError('Cros build selected, but BISECT_CROS_IP or'
          'BISECT_CROS_BOARD undefined.')
  elif 'android' in config['command']:
    if 'android-chrome' in config['command']:
      opts_dict['target_platform'] = 'android-chrome'
    else:
      opts_dict['target_platform'] = 'android'

  return bisect.BisectOptions.FromDict(opts_dict)

def _RunPerformanceTest(config, path_to_file):
  # Bisect script expects to be run from src
  os.chdir(os.path.join(path_to_file, '..'))

  bisect_utils.OutputAnnotationStepStart('Building With Patch')

  opts = _CreateBisectOptionsFromConfig(config)
  b = bisect.BisectPerformanceMetrics(None, opts)

  if bisect_utils.RunGClient(['runhooks']):
    raise RuntimeError('Failed to run gclient runhooks')

  if not b.BuildCurrentRevision('chromium'):
    raise RuntimeError('Patched version failed to build.')

  bisect_utils.OutputAnnotationStepClosed()
  bisect_utils.OutputAnnotationStepStart('Running With Patch')

  results_with_patch = b.RunPerformanceTestAndParseResults(
      opts.command, opts.metric, reset_on_first_run=True, results_label='Patch')

  if results_with_patch[1]:
    raise RuntimeError('Patched version failed to run performance test.')

  bisect_utils.OutputAnnotationStepClosed()

  bisect_utils.OutputAnnotationStepStart('Reverting Patch')
  if bisect_utils.RunGClient(['revert']):
    raise RuntimeError('Failed to run gclient runhooks')
  bisect_utils.OutputAnnotationStepClosed()

  bisect_utils.OutputAnnotationStepStart('Building Without Patch')

  if bisect_utils.RunGClient(['runhooks']):
    raise RuntimeError('Failed to run gclient runhooks')

  if not b.BuildCurrentRevision('chromium'):
    raise RuntimeError('Unpatched version failed to build.')

  bisect_utils.OutputAnnotationStepClosed()
  bisect_utils.OutputAnnotationStepStart('Running Without Patch')

  results_without_patch = b.RunPerformanceTestAndParseResults(
      opts.command, opts.metric, upload_on_last_run=True, results_label='ToT')

  if results_without_patch[1]:
    raise RuntimeError('Unpatched version failed to run performance test.')

  # Find the link to the cloud stored results file.
  output = results_without_patch[2]
  cloud_file_link = [t for t in output.splitlines()
      if 'storage.googleapis.com/chromium-telemetry/html-results/' in t]
  if cloud_file_link:
    # What we're getting here is basically "View online at http://..." so parse
    # out just the url portion.
    cloud_file_link = cloud_file_link[0]
    cloud_file_link = [t for t in cloud_file_link.split(' ')
        if 'storage.googleapis.com/chromium-telemetry/html-results/' in t]
    assert cloud_file_link, "Couldn't parse url from output."
    cloud_file_link = cloud_file_link[0]
  else:
    cloud_file_link = ''

  # Calculate the % difference in the means of the 2 runs.
  percent_diff_in_means = (results_with_patch[0]['mean'] /
      max(0.0001, results_without_patch[0]['mean'])) * 100.0 - 100.0
  std_err = bisect.CalculatePooledStandardError(
      [results_with_patch[0]['values'], results_without_patch[0]['values']])

  bisect_utils.OutputAnnotationStepClosed()
  bisect_utils.OutputAnnotationStepStart('Results - %.02f +- %0.02f delta' %
      (percent_diff_in_means, std_err))
  print ' %s %s %s' % (''.center(10, ' '), 'Mean'.center(20, ' '),
      'Std. Error'.center(20, ' '))
  print ' %s %s %s' % ('Patch'.center(10, ' '),
      ('%.02f' % results_with_patch[0]['mean']).center(20, ' '),
      ('%.02f' % results_with_patch[0]['std_err']).center(20, ' '))
  print ' %s %s %s' % ('No Patch'.center(10, ' '),
      ('%.02f' % results_without_patch[0]['mean']).center(20, ' '),
      ('%.02f' % results_without_patch[0]['std_err']).center(20, ' '))
  if cloud_file_link:
    bisect_utils.OutputAnnotationStepLink('HTML Results', cloud_file_link)
  bisect_utils.OutputAnnotationStepClosed()

def _SetupAndRunPerformanceTest(config, path_to_file, path_to_goma):
  """Attempts to build and run the current revision with and without the
  current patch, with the parameters passed in.

  Args:
    config: The config read from run-perf-test.cfg.
    path_to_file: Path to the bisect-perf-regression.py script.
    path_to_goma: Path to goma directory.

  Returns:
    0 on success, otherwise 1.
  """
  try:
    with Goma(path_to_goma) as goma:
      config['use_goma'] = bool(path_to_goma)
      config['goma_dir'] = os.path.abspath(path_to_goma)
      _RunPerformanceTest(config, path_to_file)
    return 0
  except RuntimeError, e:
    bisect_utils.OutputAnnotationStepClosed()
    _OutputFailedResults('Error: %s' % e.message)
    return 1

def _RunBisectionScript(config, working_directory, path_to_file, path_to_goma,
    path_to_extra_src, dry_run):
  """Attempts to execute src/tools/bisect-perf-regression.py with the parameters
  passed in.

  Args:
    config: A dict containing the parameters to pass to the script.
    working_directory: A working directory to provide to the
      bisect-perf-regression.py script, where it will store it's own copy of
      the depot.
    path_to_file: Path to the bisect-perf-regression.py script.
    path_to_goma: Path to goma directory.
    path_to_extra_src: Path to extra source file.
    dry_run: Do a dry run, skipping sync, build, and performance testing steps.

  Returns:
    0 on success, otherwise 1.
  """
  bisect_utils.OutputAnnotationStepStart('Config')
  print
  for k, v in config.iteritems():
    print '  %s : %s' % (k, v)
  print
  bisect_utils.OutputAnnotationStepClosed()

  cmd = ['python', os.path.join(path_to_file, 'bisect-perf-regression.py'),
         '-c', config['command'],
         '-g', config['good_revision'],
         '-b', config['bad_revision'],
         '-m', config['metric'],
         '--working_directory', working_directory,
         '--output_buildbot_annotations']

  if config['repeat_count']:
    cmd.extend(['-r', config['repeat_count']])

  if config['truncate_percent']:
    cmd.extend(['-t', config['truncate_percent']])

  if config['max_time_minutes']:
    cmd.extend(['--max_time_minutes', config['max_time_minutes']])

  if config.has_key('bisect_mode'):
    cmd.extend(['--bisect_mode', config['bisect_mode']])

  cmd.extend(['--build_preference', 'ninja'])

  if '--browser=cros' in config['command']:
    cmd.extend(['--target_platform', 'cros'])

    if os.environ[CROS_BOARD_ENV] and os.environ[CROS_IP_ENV]:
      cmd.extend(['--cros_board', os.environ[CROS_BOARD_ENV]])
      cmd.extend(['--cros_remote_ip', os.environ[CROS_IP_ENV]])
    else:
      print 'Error: Cros build selected, but BISECT_CROS_IP or'\
            'BISECT_CROS_BOARD undefined.'
      print
      return 1

  if 'android' in config['command']:
    if 'android-chrome' in config['command']:
      cmd.extend(['--target_platform', 'android-chrome'])
    else:
      cmd.extend(['--target_platform', 'android'])

  if path_to_goma:
    # crbug.com/330900. For Windows XP platforms, GOMA service is not supported.
    # Moreover we don't compile chrome when gs_bucket flag is set instead
    # use builds archives, therefore ignore GOMA service for Windows XP.
    if config.get('gs_bucket') and platform.release() == 'XP':
      print ('Goma doesn\'t have a win32 binary, therefore it is not supported '
             'on Windows XP platform. Please refer to crbug.com/330900.')
      path_to_goma = None
    cmd.append('--use_goma')

  if path_to_extra_src:
    cmd.extend(['--extra_src', path_to_extra_src])

  # These flags are used to download build archives from cloud storage if
  # available, otherwise will post a try_job_http request to build it on
  # tryserver.
  if config.get('gs_bucket'):
    if config.get('builder_host') and config.get('builder_port'):
      cmd.extend(['--gs_bucket', config['gs_bucket'],
                  '--builder_host', config['builder_host'],
                  '--builder_port', config['builder_port']
                 ])
    else:
      print ('Error: Specified gs_bucket, but missing builder_host or '
             'builder_port information in config.')
      return 1

  if dry_run:
    cmd.extend(['--debug_ignore_build', '--debug_ignore_sync',
        '--debug_ignore_perf_test'])
  cmd = [str(c) for c in cmd]

  with Goma(path_to_goma) as goma:
    return_code = subprocess.call(cmd)

  if return_code:
    print 'Error: bisect-perf-regression.py returned with error %d' %\
        return_code
    print

  return return_code

def main():

  usage = ('%prog [options] [-- chromium-options]\n'
           'Used by a trybot to run the bisection script using the parameters'
           ' provided in the run-bisect-perf-regression.cfg file.')

  parser = optparse.OptionParser(usage=usage)
  parser.add_option('-w', '--working_directory',
                    type='str',
                    help='A working directory to supply to the bisection '
                    'script, which will use it as the location to checkout '
                    'a copy of the chromium depot.')
  parser.add_option('-p', '--path_to_goma',
                    type='str',
                    help='Path to goma directory. If this is supplied, goma '
                    'builds will be enabled.')
  parser.add_option('--path_to_config',
                    type='str',
                    help='Path to the config file to use. If this is supplied, '
                    'the bisect script will use this to override the default '
                    'config file path. The script will attempt to load it '
                    'as a bisect config first, then a perf config.')
  parser.add_option('--extra_src',
                    type='str',
                    help='Path to extra source file. If this is supplied, '
                    'bisect script will use this to override default behavior.')
  parser.add_option('--dry_run',
                    action="store_true",
                    help='The script will perform the full bisect, but '
                    'without syncing, building, or running the performance '
                    'tests.')
  (opts, args) = parser.parse_args()

  path_to_current_directory = os.path.abspath(os.path.dirname(sys.argv[0]))

  # If they've specified their own config file, use that instead.
  if opts.path_to_config:
    path_to_bisect_cfg = opts.path_to_config
  else:
    path_to_bisect_cfg = os.path.join(path_to_current_directory,
        'run-bisect-perf-regression.cfg')

  config = _LoadConfigFile(path_to_bisect_cfg)

  # Check if the config is valid.
  config_is_valid = _ValidateBisectConfigFile(config)

  if config and config_is_valid:
    if not opts.working_directory:
      print 'Error: missing required parameter: --working_directory'
      print
      parser.print_help()
      return 1

    return _RunBisectionScript(config, opts.working_directory,
        path_to_current_directory, opts.path_to_goma, opts.extra_src,
        opts.dry_run)
  else:
    perf_cfg_files = ['run-perf-test.cfg', os.path.join('..', 'third_party',
        'WebKit', 'Tools', 'run-perf-test.cfg')]

    for current_perf_cfg_file in perf_cfg_files:
      if opts.path_to_config:
        path_to_perf_cfg = opts.path_to_config
      else:
        path_to_perf_cfg = os.path.join(
            os.path.abspath(os.path.dirname(sys.argv[0])),
            current_perf_cfg_file)

      config = _LoadConfigFile(path_to_perf_cfg)
      config_is_valid = _ValidatePerfConfigFile(config)

      if config and config_is_valid:
        return _SetupAndRunPerformanceTest(config, path_to_current_directory,
            opts.path_to_goma)

    print 'Error: Could not load config file. Double check your changes to '\
          'run-bisect-perf-regression.cfg/run-perf-test.cfg for syntax errors.'
    print
    return 1

if __name__ == '__main__':
  sys.exit(main())


text:
<?php

namespace Shufti\RecogniserBundle\Exception;

class RecogniserPrerequisiteException extends \UnexpectedValueException {}


text:
// Copyright 2015 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.chrome.test.util;

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import junit.framework.Assert;

import org.chromium.base.ThreadUtils;
import org.chromium.chrome.browser.omnibox.AutocompleteController;
import org.chromium.chrome.browser.omnibox.AutocompleteController.OnSuggestionsReceivedListener;
import org.chromium.chrome.browser.omnibox.LocationBarLayout;
import org.chromium.chrome.browser.omnibox.OmniboxSuggestion;
import org.chromium.chrome.browser.omnibox.UrlBar;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.content.browser.test.util.TouchCommon;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Utility methods and classes for testing the Omnibox.
 */
public class OmniboxTestUtils {
    private OmniboxTestUtils() {}

    /**
     * Builder for the data structure that describes a set of omnibox results for a given
     * query.
     */
    public static class TestSuggestionResultsBuilder {
        private final List<SuggestionsResultBuilder> mSuggestionBuilders =
                new ArrayList<SuggestionsResultBuilder>();
        private String mTextShownFor;

        public TestSuggestionResultsBuilder addSuggestions(SuggestionsResultBuilder suggestions) {
            mSuggestionBuilders.add(suggestions);
            return this;
        }

        public TestSuggestionResultsBuilder setTextShownFor(String text) {
            mTextShownFor = text;
            return this;
        }

        private List<SuggestionsResult> buildSuggestionsList() {
            ArrayList<SuggestionsResult> suggestions = new ArrayList<SuggestionsResult>();
            for (int i = 0; i < mSuggestionBuilders.size(); i++) {
                suggestions.add(mSuggestionBuilders.get(i).build());
            }
            return suggestions;
        }
    }

    /**
     * Builder for {@link SuggestionsResult}.
     */
    public static class SuggestionsResultBuilder {
        private final List<OmniboxSuggestion> mSuggestions = new ArrayList<OmniboxSuggestion>();
        private String mAutocompleteText;

        public SuggestionsResultBuilder addGeneratedSuggestion(
                int type, String text, String url) {
            mSuggestions.add(new OmniboxSuggestion(
                    type, false, 0, 0, text, null, null, null, "", url, url, false, false));
            return this;
        }

        public SuggestionsResultBuilder addSuggestion(OmniboxSuggestion suggestion) {
            mSuggestions.add(suggestion);
            return this;
        }

        public SuggestionsResultBuilder setAutocompleteText(String autocompleteText) {
            mAutocompleteText = autocompleteText;
            return this;
        }

        private SuggestionsResult build() {
            return new SuggestionsResult(mSuggestions, mAutocompleteText);
        }
    }

    /**
     * Data structure that contains the test data to be sent to
     * {@link OnSuggestionsReceivedListener#onSuggestionsReceived}.
     */
    public static class SuggestionsResult {
        private final List<OmniboxSuggestion> mSuggestions;
        private final String mAutocompleteText;

        public SuggestionsResult(List<OmniboxSuggestion> suggestions, String autocompleteText) {
            mSuggestions = suggestions;
            mAutocompleteText = autocompleteText;
        }
    }

    /**
     * Builds the necessary suggestion input for a TestAutocompleteController.
     */
    public static Map<String, List<SuggestionsResult>> buildSuggestionMap(
            TestSuggestionResultsBuilder... builders) {
        Map<String, List<SuggestionsResult>> suggestionMap =
                new HashMap<String, List<SuggestionsResult>>();
        for (TestSuggestionResultsBuilder builder : builders) {
            suggestionMap.put(builder.mTextShownFor, builder.buildSuggestionsList());
        }
        return suggestionMap;
    }

    /**
     * AutocompleteController instance that allows for easy testing.
     */
    public static class TestAutocompleteController extends AutocompleteController {
        private final View mView;
        private final Map<String, List<SuggestionsResult>> mSuggestions;
        private Runnable mSuggestionsDispatcher;
        private int mZeroSuggestCalledCount;

        public TestAutocompleteController(
                View view,
                OnSuggestionsReceivedListener listener,
                Map<String, List<SuggestionsResult>> suggestions) {
            super(listener);
            mView = view;
            mSuggestions = suggestions;
        }

        @Override
        public void start(
                Profile profile, String url ,
                final String text, boolean preventInlineAutocomplete) {
            mSuggestionsDispatcher = new Runnable() {
                @Override
                public void run() {
                    List<SuggestionsResult> suggestions =
                            mSuggestions.get(text.toLowerCase(Locale.US));
                    if (suggestions == null) return;

                    for (int i = 0; i < suggestions.size(); i++) {
                        onSuggestionsReceived(
                                suggestions.get(i).mSuggestions,
                                suggestions.get(i).mAutocompleteText,
                                0);
                    }
                }
            };
            mView.post(mSuggestionsDispatcher);
        }

        @Override
        public void startZeroSuggest(Profile profile, String omniboxText, String url,
                boolean isQueryInOmnibox, boolean focusedFromFakebox) {
            mZeroSuggestCalledCount++;
        }

        public int numZeroSuggestRequests() {
            return mZeroSuggestCalledCount;
        }

        @Override
        public void stop(boolean clear) {
            if (mSuggestionsDispatcher != null) mView.removeCallbacks(mSuggestionsDispatcher);
            mSuggestionsDispatcher = null;
        }

        @Override
        protected long nativeInit(Profile profile) {
            return 1;
        }

        @Override
        public void setProfile(Profile profile) {}
    }

    /**
     * AutocompleteController instance that will trigger no suggestions.
     */
    public static class StubAutocompleteController extends AutocompleteController {
        public StubAutocompleteController() {
            super(new OnSuggestionsReceivedListener() {
                @Override
                public void onSuggestionsReceived(List<OmniboxSuggestion> suggestions,
                        String inlineAutocompleteText) {
                    Assert.fail("No autocomplete suggestions should be received");
                }
            });
        }

        @Override
        public void start(
                Profile profile, String url ,
                final String text, boolean preventInlineAutocomplete) {}

        @Override
        public void startZeroSuggest(Profile profile, String omniboxText, String url,
                boolean isQueryInOmnibox, boolean focusedFromFakebox) {
        }

        @Override
        public void stop(boolean clear) {}

        @Override
        protected long nativeInit(Profile profile) {
            return 1;
        }

        @Override
        public void setProfile(Profile profile) {}
    }

    /**
     * Checks and verifies that the URL bar can request and release focus X times without issue.
     * @param urlBar The view to focus.
     * @param times The number of times focus should be requested and released.
     * @throws InterruptedException
     */
    public static void checkUrlBarRefocus(UrlBar urlBar, int times)
            throws InterruptedException {
        for (int i = 0; i < times; i++) {
            toggleUrlBarFocus(urlBar, true);
            Assert.assertTrue(waitForFocusAndKeyboardActive(urlBar, true));
            toggleUrlBarFocus(urlBar, false);
            Assert.assertTrue(waitForFocusAndKeyboardActive(urlBar, false));
        }
    }

    /**
     * Determines whether the UrlBar currently has focus.
     * @param urlBar The view to check focus on.
     * @return Whether the UrlBar has focus.
     */
    public static boolean doesUrlBarHaveFocus(final UrlBar urlBar) {
        return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return urlBar.hasFocus();
            }
        });
    }

    private static boolean isKeyboardActiveForView(final View view) {
        return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                InputMethodManager imm =
                        (InputMethodManager) view.getContext().getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                return imm.isActive(view);
            }
        });
    }

    /**
     * Toggles the focus state for the passed in UrlBar.
     * @param urlBar The UrlBar whose focus is being changed.
     * @param gainFocus Whether focus should be requested or cleared.
     */
    public static void toggleUrlBarFocus(final UrlBar urlBar, boolean gainFocus) {
        if (gainFocus) {
            TouchCommon.singleClickView(urlBar);
        } else {
            ThreadUtils.runOnUiThreadBlocking(new Runnable() {
                @Override
                public void run() {
                    urlBar.clearFocus();
                }
            });
        }
    }

    /**
     * Waits for the UrlBar to have the expected focus state.
     *
     * @param urlBar The UrlBar whose focus is being inspected.
     * @param active Whether the UrlBar is expected to have focus or not.
     * @return Whether the UrlBar had the requested focus state.
     */
    public static boolean waitForFocusAndKeyboardActive(final UrlBar urlBar, final boolean active)
            throws InterruptedException {
        return CriteriaHelper.pollForCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return (doesUrlBarHaveFocus(urlBar) == active)
                        && (isKeyboardActiveForView(urlBar) == active);
            }
        });
    }

    /**
     * Waits for a non-empty list of omnibox suggestions is shown.
     *
     * @param locationBar The LocationBar who owns the suggestions.
     * @return Whether the suggestions were shown.
     */
    public static boolean waitForOmniboxSuggestions(final LocationBarLayout locationBar)
            throws InterruptedException {
        return CriteriaHelper.pollForUIThreadCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                LocationBarLayout.OmniboxSuggestionsList suggestionsList =
                        locationBar.getSuggestionList();
                return suggestionsList != null
                        && suggestionsList.isShown()
                        && suggestionsList.getCount() >= 1;
            }
        });
    }

    /**
     * Waits for a suggestion list to be shown with a specified number of entries.
     * @param locationBar The LocationBar who owns the suggestions.
     * @param expectedCount The number of suggestions expected to be shown.
     * @return Whether the suggestions were shown.
     */
    public static boolean waitForOmniboxSuggestions(
            final LocationBarLayout locationBar, final int expectedCount)
            throws InterruptedException {
        return CriteriaHelper.pollForUIThreadCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                LocationBarLayout.OmniboxSuggestionsList suggestionsList =
                        locationBar.getSuggestionList();
                return suggestionsList != null
                        && suggestionsList.isShown()
                        && suggestionsList.getCount() == expectedCount;
            }
        });
    }
}


text:
<?php
/**
 * The template for displaying all single posts and attachments
 *
 * @package WordPress
 * @subpackage mmoser
 * @since mmoser
 */

get_header();
if(pll_current_language()=="en"){
  $global_location_text = "Global Locations";
}else{
  $global_location_text = "全球分布";
}
?>

<a href="<?php echo get_permalink() ?>" class="active"><?php echo $global_location_text; ?>

 ← back

	        <?php
			// Start the loop.
			while ( have_posts() ) : the_post();
				/*
				 * Include the post format-specific template for the content. If you want to
				 * use this in a child theme, then include a file called called content-___.php
				 * (where ___ is the post format) and that will be used instead.
				 */
				the_content();
				//get_template_part( 'content', get_post_format() );

			// End the loop.
			endwhile;
			?>

<?php get_footer(); ?>


text:
using UnityEngine;
using System.Collections;

public class UIStateManager : MonoBehaviour
{
    Canvas UICanvas;

	// Use this for initialization
	void Awake () {
        UICanvas = GetComponentInChildren<Canvas>();
	}

	// Update is called once per frame
	void Update ()
    {
	    switch (GameStateManager.GameState)
        {
            case StateEnum.Menu:
                UICanvas.enabled = true;
                break;
            case StateEnum.Pause:
                UICanvas.enabled = true;
                break;
            case StateEnum.Play:
                UICanvas.enabled = false;
                break;
            case StateEnum.GameOver:
                UICanvas.enabled = true;
                break;
            case StateEnum.GameWon:
                UICanvas.enabled = true;
                break;
        }
	}

    void StartGame ()
    {
        if (GameStateManager.GameState != StateEnum.Play && GameStateManager.GameState != StateEnum.GameOver)
        {
            if (!GameStateManager.isGameInProgress)
            {
                GameStateManager.isGameInProgress = true;
            }
            GameStateManager.GameState = StateEnum.Play;
        }
        else if (GameStateManager.GameState == StateEnum.GameOver || GameStateManager.GameState == StateEnum.GameWon)
        {
            Application.LoadLevel(Application.loadedLevel);
        }
    }

    void QuitGame ()
    {
        Application.Quit();
    }
}


text:
package uk.bl.wa.blindex;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrResourceLoader;
import org.apache.solr.hadoop.Solate;
import org.apache.solr.hadoop.SolrInputDocumentWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Andrew Jackson <Andrew.Jackson@bl.uk>
 *
 */
public class EmbeddedIndexerJob {
	private static final Logger LOG = LoggerFactory.getLogger(EmbeddedIndexerJob.class);

	protected static String solrHomeZipName = "solr_home.zip";

	/**
	 *
	 * This mapper parses the input table, downloads the relevant XML, parses
	 * the content into Solr documents, computes the target SolrCloud slice and
	 * passes them down to the reducer.
	 *
	 * @author Andrew Jackson <Andrew.Jackson@bl.uk>
	 *
	 */
	public static class Map extends MapReduceBase implements
			Mapper<LongWritable, Text, IntWritable, SolrInputDocumentWritable> {

		private Solate sp;
		private String domidUrlPrefix;
		private JISC2DocumentFactory docFactory;

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop
		 * .mapred.JobConf)
		 */
		@Override
		public void configure(JobConf job) {
			super.configure(job);
			//
			String zkHost = job.get("solr.zookeepers");
			String collection = job.get("solr.collection");
			//
			int numShards = 4;
			sp = new Solate(zkHost, collection, numShards);
			//
			domidUrlPrefix = job.get("dls.prefix");
			docFactory = new JISC2DocumentFactory(domidUrlPrefix, "");
		}

		public void map(LongWritable key, Text value,
				OutputCollector<IntWritable, SolrInputDocumentWritable> output,
				Reporter reporter)
				throws IOException {

			// Pull in the xml and make the Solr documents:
			List<SolrNewspaperDocument> docs = docFactory.create(value
					.toString());

			// Group them by shard number:
			for (SolrInputDocument doc : docs) {
				String doc_id = (String) doc.getFieldValue("id");
				output.collect(new IntWritable(sp.getPartition(doc_id, doc)),
						new SolrInputDocumentWritable(doc));
			}

		}

	}

	/**
	 *
	 * This reducer collects the documents for each slice together and commits
	 * them to an embedded instance of the Solr server stored on HDFS
	 *
	 * @author Andrew Jackson <Andrew.Jackson@bl.uk>
	 *
	 */
	public static class Reduce extends MapReduceBase implements
			Reducer<IntWritable, SolrInputDocumentWritable, Text, IntWritable> {

		private FileSystem fs;
		private Path solrHomeDir = null;
		private Path outputDir;
		private String shardPrefix = "shard";

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop
		 * .mapred.JobConf)
		 */
		@Override
		public void configure(JobConf job) {
			LOG.info("Calling configure()...");
			super.configure(job);
			try {
				// Filesystem:
				fs = FileSystem.get(job);
				// Input:
				solrHomeDir = findSolrConfig(job, solrHomeZipName);
				LOG.info("Found solrHomeDir " + solrHomeDir);
			} catch (IOException e) {
				e.printStackTrace();
				LOG.error("FAILED in reducer configuration: " + e);
			}
			// Output:
			outputDir = new Path("/user/admin/jisc2/solr/");
		}

		public void reduce(IntWritable key,
				Iterator<SolrInputDocumentWritable> values,
				OutputCollector<Text, IntWritable> output, Reporter reporter)
				throws IOException {
			int slice = key.get();
			int countTotal = 0;
			int countFailures = 0;

			Path outputShardDir = new Path(outputDir, this.shardPrefix + slice);

			LOG.info("Running reducer for " + slice + " > " + outputShardDir);

			//
			EmbeddedSolrServer solrServer = createEmbeddedSolrServer(
					solrHomeDir, fs, outputDir,
							outputShardDir);

			while (values.hasNext()) {
				SolrInputDocument doc = values.next().getSolrInputDocument();
				countTotal++;
				try {
					solrServer.add(doc);
					output.collect(new Text("" + key), new IntWritable(1));
				} catch (Exception e) {
					LOG.error("ERROR " + e + " when adding document "
							+ doc.getFieldValue("id"));
					countFailures++;
				}
			}

			try {
				solrServer.commit();
				solrServer.shutdown();
			} catch (SolrServerException e) {
				LOG.error("ERROR on commit: " + e);
			}
			output.collect(new Text("TOTAL " + key),
					new IntWritable(countTotal));
			output.collect(new Text("FAILURES " + key), new IntWritable(
					countFailures));
		}

	}

	public static Path findSolrConfig(JobConf conf, String zipName)
			throws IOException {
	    Path solrHome = null;
		Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);
	    if (localArchives.length == 0) {
			LOG.error("No local cache archives.");
			throw new IOException(String.format("No local cache archives."));
	    }
	    for (Path unpackedDir : localArchives) {
			LOG.info("Looking at: " + unpackedDir + " for " + zipName);
			if (unpackedDir.getName().equals(zipName)) {
				LOG.info("Using this unpacked directory as solr home: {}",
						unpackedDir);
				solrHome = unpackedDir;
				break;
			}
	    }
	    return solrHome;
	  }

	/**
	 * c.f. SolrRecordWriter, SolrOutputFormat
	 *
	 * Cloudera Search defaults to: /solr/jisc2/core_node1 ...but note no
	 * replicas, which is why the shard-to-core mapping looks easy.
	 *
	 * Take /user/admin/jisc2-xmls/000000_0 Read line-by-line Split on 0x01.
	 *
	 *
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		JobConf conf = new JobConf(EmbeddedIndexerJob.Map.class);
		conf.setJobName("JISC2_Indexer");
		conf.setMapOutputKeyClass(IntWritable.class);
		conf.setMapOutputValueClass(SolrInputDocumentWritable.class);
		conf.setMapperClass(Map.class);
		conf.setNumMapTasks(4);
		conf.setReducerClass(Reduce.class);
		conf.setNumReduceTasks(4);
		conf.setInputFormat(TextInputFormat.class);
		conf.setOutputFormat(TextOutputFormat.class);
		// Get input and output folder from CLARGS:
		FileInputFormat.setInputPaths(conf, new Path(args[1]));
		FileOutputFormat.setOutputPath(conf, new Path(args[2]));

		conf.setSpeculativeExecution(false);

		// File solrHomeZip = new
		// File("src/main/resources/jisc2/solr_home.zip");

		Path zipPath = new Path("/user/admin/jisc2-xmls/solr_home.zip");
		FileSystem fs = FileSystem.get(conf);
		// fs.copyFromLocalFile(new Path(solrHomeZip.toString()), zipPath);
		final URI baseZipUrl = fs.getUri().resolve(
				zipPath.toString() + '#' + solrHomeZipName);

		DistributedCache.addCacheArchive(baseZipUrl, conf);
		LOG.debug("Set Solr distributed cache: {}",
				Arrays.asList(DistributedCache.getCacheArchives(conf)));
		LOG.debug("Set zipPath: {}", zipPath);

		JobClient.runJob(conf);

	}

	public static EmbeddedSolrServer createEmbeddedSolrServer(Path solrHomeDir,
			FileSystem fs, Path outputDir, Path outputShardDir)
			throws IOException {

		if (solrHomeDir == null) {
			throw new IOException("Unable to find solr home setting");
		}
		LOG.info("Creating embedded Solr server with solrHomeDir: "
				+ solrHomeDir + ", fs: " + fs + ", outputShardDir: "
				+ outputShardDir);

		Properties props = new Properties();
		// FIXME note this is odd (no scheme) given Solr doesn't currently
		// support uris (just abs/relative path)
		Path solrDataDir = new Path(outputShardDir, "data");
		if (!fs.exists(solrDataDir) && !fs.mkdirs(solrDataDir)) {
			throw new IOException("Unable to create " + solrDataDir);
		}

		String dataDirStr = solrDataDir.toUri().toString();
		LOG.info("Attempting to set data dir to:" + dataDirStr);
		props.setProperty("solr.data.dir", dataDirStr);
		props.setProperty("solr.home", solrHomeDir.toString());
		props.setProperty("solr.solr.home", solrHomeDir.toString());
		props.setProperty("solr.hdfs.home", outputDir.toString());

		SolrResourceLoader loader = new SolrResourceLoader(
				solrHomeDir.toString(), null, props);

		LOG.info(String
				.format("Constructed instance information solr.home %s (%s), instance dir %s, conf dir %s, writing index to solr.data.dir %s, with permdir %s",
						solrHomeDir, solrHomeDir.toUri(),
						loader.getInstanceDir(), loader.getConfigDir(),
						dataDirStr, outputShardDir));

		CoreContainer container = new CoreContainer(loader);
		container.load();
		LOG.error("Setting up core1 descriptor...");
		CoreDescriptor descr = new CoreDescriptor(container, "core1", new Path(
				solrHomeDir, "jisc2").toString());

		// descr.setDataDir(dataDirStr);
		// descr.setCoreProperties(props);
		LOG.error("Creating core1... " + descr.getConfigName());
		SolrCore core = container.create(descr);
		LOG.error("Registering core1...");
		container.register(core, false);

		System.setProperty("solr.hdfs.nrtcachingdirectory", "false");
		System.setProperty("solr.hdfs.blockcache.enabled", "false");
		System.setProperty("solr.autoCommit.maxTime", "-1");
		System.setProperty("solr.autoSoftCommit.maxTime", "-1");
		EmbeddedSolrServer solr = new EmbeddedSolrServer(container, "core1");
		return solr;
	}
}