text:
package com.github.nyrkovalex.deploy.me.parsing;

import com.github.nyrkovalex.deploy.me.descriptor.Application;
import com.github.nyrkovalex.deploy.me.descriptor.DeploymentDescriptor;
import com.github.nyrkovalex.deploy.me.descriptor.Fileset;
import com.github.nyrkovalex.deploy.me.descriptor.Named;
import com.github.nyrkovalex.deploy.me.descriptor.Script;
import com.github.nyrkovalex.deploy.me.descriptor.Server;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.toSet;

public class Parser {

    private final DeploymentDescriptorParser deploymentDescriptorParser;

    private Parser() {
        ScriptParser scriptParser = new ScriptParser();
        ScriptSetParser scriptSetParser = new ScriptSetParser(scriptParser);
        FilesetParser filesetParser = new FilesetParser(scriptSetParser);
        ServerParser serverParser = new ServerParser();
        ServerSetParser serverSetParser = new ServerSetParser(serverParser);
        FilesetSetParser filesetSetParser = new FilesetSetParser(filesetParser);
        ApplicationParser applicationParser = new ApplicationParser(serverSetParser, filesetSetParser);
        ApplicationSetParser applicationSetParser = new ApplicationSetParser(applicationParser);
        this.deploymentDescriptorParser = new DeploymentDescriptorParser(applicationSetParser);
    }

    private DeploymentDescriptor parse(String source) {
        return deploymentDescriptorParser.parse(new JsonParser().parse(source));
    }

    public static DeploymentDescriptor read(String source) {
        return new Parser().parse(source);
    }
}

class DeploymentDescriptorParser {

    private final ApplicationSetParser applicationParser;

    DeploymentDescriptorParser(ApplicationSetParser applicationParser) {
        this.applicationParser = applicationParser;
    }

    DeploymentDescriptor parse(JsonElement element) {
        JsonObject jsonObject = element.getAsJsonObject();
        Set<Application> applications = applicationParser.parse(jsonObject);
        return new DeploymentDescriptor(applications);
    }
}

class ApplicationSetParser extends SetParser<Application> {

    public ApplicationSetParser(ApplicationParser applicationParser) {
        super(applicationParser);
    }
}

class ApplicationParser implements BasicParser<Application> {

    private final ServerSetParser serverSetParser;
    private final FilesetSetParser filesetSetParser;

    public ApplicationParser(ServerSetParser serverParser, FilesetSetParser filesetSetParser) {
        this.serverSetParser = serverParser;
        this.filesetSetParser = filesetSetParser;
    }

    @Override
    public Application parse(String name, JsonElement element) {
        JsonObject jsonObject = element.getAsJsonObject();
        Set<Fileset> filesets = filesetSetParser.parse(jsonObject.getAsJsonObject("filesets"));
        Set<Server> servers = serverSetParser.parse(jsonObject.getAsJsonObject("servers"), filesets);
        return new Application(name, servers);
    }

}

class ServerParser {

    Server parse(String name, Map<String, Fileset> filesetIndex, JsonElement element) {
        JsonObject jsonObject = element.getAsJsonObject();
        JsonArray filesetsArray = jsonObject.get("filesets").getAsJsonArray();
        Set<Fileset> filesets = FluentIterable.from(filesetsArray)
                .transform(JsonElement::getAsString)
                .transform(filesetIndex::get)
                .toSet();
        return new Server(
                name,
                jsonObject.get("user").getAsString(),
                jsonObject.get("address").getAsString(),
                filesets);
    }
}

class ServerSetParser {

    private final ServerParser serverParser;

    ServerSetParser(ServerParser serverParser) {
        this.serverParser = serverParser;
    }

    Set<Server> parse(JsonObject jsonObject, Iterable<Fileset> filesets) {
        Map<String, Fileset> filesetIndex = Maps.uniqueIndex(filesets, Named::name);
        return jsonObject.entrySet().stream()
                .map(entry -> serverParser.parse(entry.getKey(), filesetIndex, entry.getValue()))
                .collect(toSet());
    }
}

class FilesetSetParser extends SetParser<Fileset> {

    FilesetSetParser(FilesetParser filesetParser) {
        super(filesetParser);
    }
}

class FilesetParser implements BasicParser<Fileset> {

    private final ScriptSetParser scriptParser;

    FilesetParser(ScriptSetParser scriptParser) {
        this.scriptParser = scriptParser;
    }

    @Override
    public Fileset parse(String name, JsonElement element) {
        JsonObject jsonObject = element.getAsJsonObject();
        Set<Script> scripts = scriptParser.parse(jsonObject);
        return new Fileset(name, scripts);
    }
}

class ScriptSetParser extends SetParser<Script> {

    public ScriptSetParser(ScriptParser scriptParser) {
        super(scriptParser);
    }
}

class ScriptParser implements BasicParser<Script> {

    @Override
    public Script parse(String path, JsonElement locations) {
        Iterable<String> targets = locations.isJsonArray()
                ? FluentIterable.from(locations.getAsJsonArray())
                .transform(item -> item.getAsString())
                .toSet()
                : ImmutableSet.of(locations.getAsString());
        return new Script(path, targets);
    }
}

abstract class SetParser<T> {

    private final BasicParser<T> basicParser;

    public SetParser(BasicParser<T> basicParser) {
        this.basicParser = basicParser;
    }

    public Set<T> parse(JsonObject jsonObject) {
        return jsonObject.entrySet().stream()
                .map(entry -> basicParser.parse(entry.getKey(), entry.getValue()))
                .collect(toSet());
    }
}

interface BasicParser<T> {

    T parse(String name, JsonElement content);
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | **string** | Company name must be between 2 and 484 characters | [optional]
**inChargePersonName** | **string** | In Charge Person name must be between 2 and 1084 characters and can contain only letters, digits and dashes | [optional]
**mainAddress** | **string** | Company main address must be in the form House Number, Street Direction, Street Name, Street Suffix, City, State, Zip, Country | [optional]
**mainImageURL** | **string** | Company main image URL must have valid URL form | [optional]
**logoURL** | **string** | Company logo URL must have valid URL form | [optional]
**contactPhone** | **string** | Company contact phone can contain only numbers and symbols plus sign and dash | [optional]
**companyType** | **string** | Company type | [optional]
**description** | **string** | Company description must be between 2 and 1284 characters | [optional]
**geoPosition** | [**\Swagger\Client\Model\Geometry**](Geometry.md) |  | [optional]
**userDefinedObject** | **object** | a free form user defined object that includes a key - value array. Place your custom properties in array, the key corresponds to property name its length must be not longer that 40 chars and value for each custom key is limited to 2048 chars. If for a key the value is empty then the key-property name will be deleted. | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

redpajama_set_name: RedPajamaGithub


text:
/**
 * Helper class which runs our native library, which is loaded from inside the Jar.
 * @author Thomas Buck
 * @version 1.0
 */
import java.io.*;
import java.nio.channels.*;
import java.nio.*;
import java.util.StringTokenizer;

public class HelperUtility {

    // Load libraries, copy from Jar if needed
    // Inspired by:
    // http://stackoverflow.com/questions/1611357/how-to-make-a-jar-file-that-include-dll-files
    static {
        loadFromJar();
    }

    /**
     * When packaged into JAR extracts DLLs, places these into
     */
    private static void loadFromJar() {
        // we need to put DLL to temp dir
        String os = System.getProperty("os.name").toLowerCase();
        String path = "CC_";
        if (os.indexOf("windows") > -1) {
            loadLib(path, "Serial.dll");
        } else if (os.indexOf("mac") > -1) {
            loadLib(path, "libSerial.jnilib");
        } else { // Hopefully unix/linux...
            loadLib(path, "libSerial.so");
        }
    }

    /**
     * Puts library to temp dir and loads to memory
     * @param path Put in front of file name
     * @param Complete name of file to load (w/ lib & .dll)
     */
    private static void loadLib(String path, String name) {
        try {
            // have to use a stream
            InputStream in = HelperUtility.class.getResourceAsStream(name);
            File fileOut = new File(System.getProperty("java.io.tmpdir") + "/" + path + name);
            OutputStream out = new FileOutputStream(fileOut);
            ReadableByteChannel inChannel = Channels.newChannel(in);
            WritableByteChannel outChannel = Channels.newChannel(out);
            fastChannelCopy(inChannel, outChannel);
            inChannel.close();
            outChannel.close();
            path = fileOut.getPath();
            try {
                System.load(path);
            } catch (UnsatisfiedLinkError e) {
                System.out.println("ERROR: Library does not exist!");
                return;
            } catch (SecurityException e) {
                System.out.println("ERROR: Not allowed to load Library!");
                return;
            } catch (NullPointerException e) {
                System.out.println("ERROR: Library name is null!");
                return;
            } catch (Exception e) {
                System.out.println("ERROR: " + e.toString());
                return;
            }
            // System.out.println("Loaded Serial Library at \"" + path + "\"");
            return;
        } catch (Exception e) {
            System.out.println("ERROR: Failed to load Serial Library:");
            e.printStackTrace();
            return;
        }
    }

    /**
     * Get the names of all available serial ports.
     *
     * @return Array of port names. First entry is "No serial ports!" if no
     *         others
     */
    // Get ports as single String from getPortsOS() and put them in an array
    public static String[] getPorts() {
        String portLines = getPortsOS();
        if (portLines == null) {
            String[] ports = { "No serial ports!" };
            return ports;
        } else {
            StringTokenizer sT = new StringTokenizer(portLines, "\n");
            int size = sT.countTokens();
            String[] ports = new String[size];
            for (int i = 0; i < size; i++) {
                ports[i] = sT.nextToken();
            }
            return ports;
        }
    }

    /**
     * Get all the existing serial port names
     *
     * @return List of port names. \n between entries
     */
    private static String getPortsOS() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.indexOf("windows") > -1) {
                return getThePorts("COM");
            } else if (os.indexOf("mac") > -1) {
                return getThePorts("tty.");
            } else {
                return getThePorts("rfcomm");
            }
        } catch (UnsatisfiedLinkError e) {
            System.out.println("ERROR: Library not loaded! (getPorts)");
            return "Serial Library Error!\n";
        }
    }

    private static native String getThePorts(String search);

    /**
     * Open Connection to a port
     *
     * @return TRUE if successful
     * @param name
     *            Port to open
     */
    public static boolean openPort(String name) {
        try {
            return openPortNative(name);
        } catch (UnsatisfiedLinkError e) {
            System.out.println("ERROR: Library not loaded! (openPort)");
            return false;
        }
    }

    private static native boolean openPortNative(String name);

    /**
     * Close Connection to port
     */
    public static void closePort() {
        try {
            closePortNative();
        } catch (UnsatisfiedLinkError e) {
            System.out.println("ERROR: Library not loaded! (closePort)");
        }
    }

    private static native void closePortNative();

    /**
     * Read data from Cube
     *
     * @param length Amount of data to read
     * @return Data read, empty on error
     */
    public static short[] readData(int length) {
        try {
            return readDataNative(length);
        } catch (UnsatisfiedLinkError e) {
            System.out.println("ERROR: Library not loaded! (readData)");
            return null;
        }
    }

    private static native short[] readDataNative(int length);

    /**
     * Write data to Cube
     *
     * @param data
     *            Data to write
     * @param length
     *            Length of data
     *
     * @return TRUE on success, FALSE on error
     */
    public static boolean writeData(short[] data, int length) {
        try {
            return writeDataNative(data, length);
        } catch (UnsatisfiedLinkError e) {
            System.out.println("ERROR: Library not loaded! (writeData)");
            return false;
        }
    }

    private static native boolean writeDataNative(short[] data, int length);

    // http://thomaswabner.wordpress.com/2007/10/09/fast-stream-copy-using-javanio-channels/
    private static void fastChannelCopy(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            dest.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear()
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }
}


text:
"use strict";

var UI = require("lazuli-ui/index.js");

module.exports = UI.ListQuery.clone({
    id: "ExportHistory",
    sortable: true,
    open_ended_recordset: true,             // for performance reasons
    show_row_control: false,
    key_condition: null,                 // Condition selecting the appropriate transactions, x.sql.Condition, use methods only
    extra_cond_sql: null,                 // Extra query condition SQL to filter the list, string
    extra_condition: null,                  // Extra query condition produced if extra_cond_sql is supplied, use methods only
});

module.exports.define("setup", function () {
    x.sections.ListBase.setup.call(this);        // deliberately DON'T call ListQuery.setup()

    if (!this.key) {
        this.key = this.deduceKey();
    }

    this.setupEntity("ac_export");
    this.generated_title = "Message History";
    this.query.addCondition({
        column: "A.subtype",
        operator: "=",
        value: this.subtype,
    });
    if (this.action) {
        this.query.addCondition({
            column: "A.action",
            operator: "=",
            value: this.action,
        });
    }
    this.key_condition = this.query.addCondition({
        full_condition: "LOCATE('ref_entity\":\"vr_rqmt_splr', A.base_record)"
                       + " AND LOCATE('val\":\"" + this.key + "', A.base_record)",
    });

    if (typeof this.extra_cond_sql === "string") {
        this.extra_condition = this.query.addCondition({ full_condition: this.extra_cond_sql, });
    }
});


text:
using namespace gpopt;
using namespace gpmd;

const WCHAR CScalarBooleanTest::m_rgwszBoolTest[EbtSentinel][30] =
{
	GPOS_WSZ_LIT("Is True"),
	GPOS_WSZ_LIT("Is Not True"),
	GPOS_WSZ_LIT("Is False"),
	GPOS_WSZ_LIT("Is Not False"),
	GPOS_WSZ_LIT("Is Unknown"),
	GPOS_WSZ_LIT("Is Not Unknown"),
};

// mapping operator type and child value to the corresponding result value for Boolean expression evaluation,
// in each entry, we have three values:
// (1) operator type: IS_TRUE / IS_NOT_TRUE / IS_FALSE / IS_NOT_FALSE / IS_UNKNOWN / IS_NOT_UNKNOWN
// (2) child value: EberTrue / EberFalse / EberNull / EberUnknown
// (3) expected result:  EberTrue / EberFalse / EberNull / EberUnknown

const BYTE CScalarBooleanTest::m_rgBoolEvalMap [][3] =
{
	{EbtIsTrue, EberTrue, EberTrue},	// IS_TRUE(True) = True
	{EbtIsTrue, EberFalse, EberFalse},	// IS_TRUE(False) = False
	{EbtIsTrue, EberNull, EberFalse},	// IS_TRUE(Null) = False
	{EbtIsTrue, EberUnknown, EberUnknown},	// IS_TRUE(Unknown) = Unknown

	{EbtIsNotTrue, EberTrue, EberFalse},	// IS_NOT_TRUE(True) = False
	{EbtIsNotTrue, EberFalse, EberTrue},	// IS_NOT_TRUE(False) = True
	{EbtIsNotTrue, EberNull, EberTrue},		// IS_NOT_TRUE(Null) = True
	{EbtIsNotTrue, EberUnknown, EberUnknown},	// IS_NOT_TRUE(Unknown) = Unknown

	{EbtIsFalse, EberTrue, EberFalse},	// IS_FALSE(True) = False
	{EbtIsFalse, EberFalse, EberTrue},	// IS_FALSE(False) = True
	{EbtIsFalse, EberNull, EberFalse},	// IS_FALSE(Null) = False
	{EbtIsFalse, EberUnknown, EberUnknown},	// IS_FALSE(Unknown) = Unknown

	{EbtIsNotFalse, EberTrue, EberTrue},	// IS_NOT_FALSE(True) = True
	{EbtIsNotFalse, EberFalse, EberFalse},	// IS_NOT_FALSE(False) = False
	{EbtIsNotFalse, EberNull, EberTrue},	// IS_NOT_FALSE(Null) = True
	{EbtIsNotFalse, EberUnknown, EberUnknown},	// IS_NOT_FALSE(Unknown) = Unknown

	{EbtIsUnknown, EberTrue, EberFalse},		// IS_UNKNOWN(True) = False
	{EbtIsUnknown, EberFalse, EberFalse},	// IS_UNKNOWN(False) = False
	{EbtIsUnknown, EberNull, EberTrue},		// IS_UNKNOWN(Null) = True  ---> Note that UNKNOWN in BooleanTest means NULL
	{EbtIsUnknown, EberUnknown, EberUnknown},	// IS_UNKNOWN(Unknown) = Unknown

	{EbtIsNotUnknown, EberTrue, EberTrue},		// IS_NOT_UNKNOWN(True) = True
	{EbtIsNotUnknown, EberFalse, EberTrue},		// IS_NOT_UNKNOWN(False) = True
	{EbtIsNotUnknown, EberNull, EberFalse},		// IS_NOT_UNKNOWN(Null) = False ---> Note that NOT_UNKNOWN in BooleanTest means NOT-NULL
	{EbtIsNotUnknown, EberUnknown, EberUnknown},	// IS_NOT_UNKNOWN(Unknown) = Unknown
};

//---------------------------------------------------------------------------
//	@function:
//		CScalarBooleanTest::FMatch
//
//	@doc:
//		Match function on operator level
//
//---------------------------------------------------------------------------
BOOL
CScalarBooleanTest::FMatch
	(
	COperator *pop
	)
	const
{
	if (pop->Eopid() == Eopid())
	{
		return m_ebt == CScalarBooleanTest::PopConvert(pop)->Ebt();
	}

	return false;
}

//---------------------------------------------------------------------------
//	@function:
//		CScalarBooleanTest::PmdidType
//
//	@doc:
//		Expression type
//
//---------------------------------------------------------------------------
IMDId *
CScalarBooleanTest::PmdidType() const
{
	CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda();

	return pmda->PtMDType<IMDTypeBool>()->Pmdid();
}

//---------------------------------------------------------------------------
//	@function:
//		CScalarBooleanTest::Eber
//
//	@doc:
//		Perform boolean expression evaluation
//
//---------------------------------------------------------------------------
CScalar::EBoolEvalResult
CScalarBooleanTest::Eber
	(
	DrgPul *pdrgpulChildren
	)
	const
{
	GPOS_ASSERT(NULL != pdrgpulChildren);
	GPOS_ASSERT(1 == pdrgpulChildren->UlLength());

	EBoolEvalResult eber = (EBoolEvalResult) *((*pdrgpulChildren)[0]);
	for (ULONG ul = 0; ul < GPOS_ARRAY_SIZE(m_rgBoolEvalMap); ul++)
	{
		if (m_ebt == m_rgBoolEvalMap[ul][0] &&
			eber == m_rgBoolEvalMap[ul][1])
		{
			return (CScalar::EBoolEvalResult) m_rgBoolEvalMap[ul][2];
		}
	}

	return EberUnknown;
}

//---------------------------------------------------------------------------
//	@function:
//		CScalarBooleanTest::OsPrint
//
//	@doc:
//		debug print
//
//---------------------------------------------------------------------------
IOstream &
CScalarBooleanTest::OsPrint
	(
	IOstream &os
	)
	const
{
	os << SzId() << " (";
	os << m_rgwszBoolTest[m_ebt];
	os << ")";

	return os;
}

// EOF


text:
require 'rails_helper'

describe "admin/pipelines/new.html.erb" do
  include GoUtil
  include FormUI
  include ReflectiveUtil
  include MockRegistryModule

  before(:each) do
    allow(view).to receive(:pipeline_create_path).and_return("create_path")

    @pipeline = PipelineConfigMother.createPipelineConfig("", "defaultStage", ["defaultJob"].to_java(java.lang.String))
    @material_config = com.thoughtworks.go.helper.MaterialConfigsMother.svn("svn://foo", "loser", "secret", true, "dest")
    @material_config.setName(CaseInsensitiveString.new("Svn Material Name"))
    @pipeline.materialConfigs().clear()
    @pipeline.addMaterialConfig(@material_config)
    @pipeline_group = BasicPipelineConfigs.new
    @pipeline_group.add(@pipeline)

    assign(:pipeline, @pipeline)
    assign(:pipeline_group, @pipeline_group)
    assign(:template_list, Array.new)
    assign(:all_pipelines, java.util.ArrayList.new)
    tvms = java.util.ArrayList.new
    tvms.add(com.thoughtworks.go.presentation.TaskViewModel.new(com.thoughtworks.go.config.AntTask.new, "template"))
    assign(:task_view_models, tvms)

    @cruise_config = BasicCruiseConfig.new
    repository1 = PackageRepositoryMother.create("repo1", "repo1-name", "pluginid", "version", Configuration.new([ConfigurationPropertyMother.create("k1", false, "v1")].to_java(ConfigurationProperty)))
    repository2 = PackageRepositoryMother.create("repo2", "repo2-name", "pluginid", "version", Configuration.new([ConfigurationPropertyMother.create("k1", false, "v1")].to_java(ConfigurationProperty)))
    pkg1 = PackageDefinitionMother.create("pkg1", "package1-name", Configuration.new([ConfigurationPropertyMother.create("k2", false, "v2")].to_java(ConfigurationProperty)), repository1)
    @pkg2 = PackageDefinitionMother.create("pkg2", "package2-name", Configuration.new([ConfigurationPropertyMother.create("k2", false, "v2")].to_java(ConfigurationProperty)), repository1)
    repository1.setPackages(Packages.new([pkg1, @pkg2].to_java(PackageDefinition)))
    repos = PackageRepositories.new
    repos.add(repository1)
    repos.add(repository2)
    @cruise_config.setPackageRepositories(repos)
    assign(:cruise_config, @cruise_config)
    assign(:original_cruise_config, @cruise_config)
    allow(view).to receive(:is_user_a_group_admin?).and_return(false)
    set(@cruise_config, "md5", "abc")
    allow(view).to receive(:render_pluggable_form_template).and_return("template")
  end

  describe "Materials" do

    it "should have material section " do
      render

      Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-materials').tap do |tab|
        expect(tab).to have_selector("h2.section_title", :text => "Step 2: Materials")
        expect(tab).to have_selector("label", :text => "Material Type*")
        tab.find("select[name='pipeline_group[pipeline][materials][materialType]']") do |select|
          expect(select).to have_selector("option[value='SvnMaterial']", :text => "Subversion")
          expect(select).to have_selector("option[value='GitMaterial']", :text => "Git")
          expect(select).to have_selector("option[value='HgMaterial']", :text => "Mercurial")
          expect(select).to have_selector("option[value='P4Material']", :text => "Perforce")
          expect(select).to have_selector("option[value='DependencyMaterial']", :text => "Pipeline")
        end
        expect(tab).to have_selector("button.cancel_button", :text => "Cancel")
        expect(tab).to have_selector("button#next_to_materials", :text => "Next")
      end
    end

    describe "Svn material" do

      it "should render all svn material attributes" do
        in_params(:pipeline_name => "pipeline_name")

        render

        Capybara.string(response.body).find('div#tab-content-of-materials #material_forms .SvnMaterial').tap do |form|
          expect(form).to have_selector("label", :text => "URL*")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::URL}]']")

          expect(form).to have_selector("label", :text => "Username")
          expect(form).to have_selector("input.svn_username[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME}]']")

          expect(form).to have_selector("label", :text => "Password")
          expect(form).to have_selector("input.svn_password[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::PASSWORD}]']")

          expect(form).to have_selector("div.hidden input[type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::PASSWORD_CHANGED}]'][value='1'][checked='checked']")

          expect(form).to have_selector("label", :text => "Poll for new changes")
          expect(form).to have_selector("input[type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::AUTO_UPDATE}]'][checked='checked']")
          expect(form).to have_selector("textarea[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{ScmMaterialConfig::FILTER}]']")
        end
      end

      it "should display check connection button" do
        render

        expect(response.body).to have_selector("button#check_connection_svn", :text => "CHECK CONNECTION")
        expect(response.body).to have_selector("#vcsconnection-message_svn", :text => "", visible: false)
      end

      it "should display new svn material view with errors" do
        error = config_error(com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::URL, "Url is wrong")
        error.add(com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME, "Username is wrong")
        error.add(com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::PASSWORD, "Password is wrong")

        set(@material_config, "errors", error)

        render

        Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
          Capybara.string(response.body).find("div.steps_panes.sub_tab_container_content div#tab-content-of-materials #material_forms .SvnMaterial").tap do |svn|
            expect(svn).to have_selector("div.field_with_errors input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::URL}]'][value='svn://foo']")
            expect(svn).to have_selector("div.form_error", :text => "Url is wrong")

            expect(svn).to have_selector("div.field_with_errors input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME}]'][value='loser']")
            expect(svn).to have_selector("div.form_error", :text => "Username is wrong")

            expect(svn).to have_selector("div.field_with_errors input[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::PASSWORD}]'][value='secret']")
            expect(svn).to have_selector("div.form_error", :text => "Password is wrong")
          end
        end
      end
    end

    describe "Git Material" do
      it "should render all git material attributes" do
        in_params(:pipeline_name => "pipeline_name")

        render

        Capybara.string(response.body).find("div#tab-content-of-materials #material_forms .GitMaterial").tap do |form|
          expect(form).to have_selector("label", :text => "URL*")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::URL}]']")

          expect(form).to have_selector("label", :text => "Username")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME}]']")

          expect(form).to have_selector("label", :text => "Password")
          expect(form).to have_selector("input[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::PASSWORD}]']")

          expect(form).to have_selector("label", :text => "Branch")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::BRANCH}]']")

          expect(form).to have_selector("label", :text => "Poll for new changes")
          expect(form).to have_selector("input[type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::AUTO_UPDATE}]'][checked='checked']")

          expect(form).to have_selector("label", :text => "Shallow clone (recommended for large repositories)")
          expect(form).to have_selector("input[type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::SHALLOW_CLONE}]']")

          expect(form).to have_selector("textarea[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{ScmMaterialConfig::FILTER}]']")
        end
      end
    end

    describe "Hg Material" do
      it "should render all hg material attributes" do
        in_params(:pipeline_name => "pipeline_name")

        render

        Capybara.string(response.body).find("div#tab-content-of-materials #material_forms .HgMaterial").tap do |form|
          expect(form).to have_selector("label", :text => "URL*")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::URL}]']")

          expect(form).to have_selector("label", :text => "Username")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME}]']")

          expect(form).to have_selector("label", :text => "Password")
          expect(form).to have_selector("input[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::PASSWORD}]']")

          expect(form).to have_selector("label", :text => "Branch")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::BRANCH}]']")

          expect(form).to have_selector("label", :text => "Poll for new changes")
          expect(form).to have_selector("input[type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::AUTO_UPDATE}]'][checked='checked']")
          expect(form).to have_selector("textarea[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::TYPE}][#{ScmMaterialConfig::FILTER}]']")
        end
      end
    end

    describe "Tfs Material" do
      it "should render all tfs material attributes" do
        in_params(:pipeline_name => "pipeline_name")

        render

        Capybara.string(response.body).find("div#tab-content-of-materials #material_forms .TfsMaterial").tap do |form|
          expect(form).to have_selector("label", :text => "URL*")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::URL}]']")
          expect(form).to have_selector("input.tfs_username[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::USERNAME}]']")
          expect(form).to have_selector("input.tfs_password[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::PASSWORD}]']")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::PROJECT_PATH}]']")

          expect(form).to have_selector("label", :text => "Poll for new changes")
          expect(form).to have_selector("input[type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::AUTO_UPDATE}]'][checked='checked']")
          expect(form).to have_selector("textarea[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][#{ScmMaterialConfig::FILTER}]']")

          expect(form).not_to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][workspaceOwner]']")
          expect(form).not_to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][workspace]']")
        end
      end
    end

    describe "P4 Material" do
      it "should render all P4 material attributes" do
        in_params(:pipeline_name => "pipeline_name")

        render

        Capybara.string(response.body).find("div#tab-content-of-materials #material_forms .P4Material").tap do |form|
          expect(form).to have_selector("label", :text => "Server and Port*")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::SERVER_AND_PORT}]']")

          expect(form).to have_selector("label", :text => "Username")
          expect(form).to have_selector("input.p4_username[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::USERNAME}]']")

          expect(form).to have_selector("label", :text => "Password")
          expect(form).to have_selector("input.p4_password[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::PASSWORD}]']")

          expect(form).to have_selector("label", :text => "View*")
          expect(form).to have_selector("textarea[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::VIEW}]']")
          expect(form).to have_selector("textarea[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{ScmMaterialConfig::FILTER}]']")

          expect(form).to have_selector("label[for='material_useTickets']", :text => "Use tickets")
          expect(form).to have_selector("input[id='material_useTickets'][type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::USE_TICKETS}]']")

          expect(form).to have_selector("label", :text => "Poll for new changes")
          expect(form).to have_selector("input[type='checkbox'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.ScmMaterialConfig::AUTO_UPDATE}]'][checked='checked']")
        end
      end
    end

    describe "Dependency Material" do
      it "should render all Dependency material attributes" do
        in_params(:pipeline_name => "pipeline_name")

        render

        Capybara.string(response.body).find("div#tab-content-of-materials .DependencyMaterial").tap do |form|
          expect(form).to have_selector("label", :text => "Pipeline [Stage]*")
          expect(form).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig::PIPELINE_STAGE_NAME}]']")
        end
      end
    end

    describe "Package Material" do

      before(:each) do
        @material = PackageMaterialConfig.new
        @material_configs = MaterialConfigs.new([@material].to_java(com.thoughtworks.go.domain.materials.MaterialConfig))
        fields_for(:pipeline_group, @pipeline_group) do |gf|
          gf.fields_for(:pipeline, @pipeline) do |pf|
            pf.fields_for(:materials, @material_configs) do |mf|
              mf.fields_for(com.thoughtworks.go.config.materials.PackageMaterialConfig::TYPE, @material) do |f|
                @form = f
              end
            end
          end
        end
      end

      it "should render all material attributes" do
        in_params(:pipeline_name => "pipeline-name")

        render

        Capybara.string(response.body).find("div#tab-content-of-materials #material_forms .PackageMaterial").tap do |form|
          expect(form).to have_selector("input[type='hidden'][name='material_type'][value='#{com.thoughtworks.go.config.materials.PackageMaterialConfig::TYPE}']", visible: :hidden)
          expect(form).to have_selector("input[type='radio'][name='material[create_or_associate_pkg_def]'][value='associate'][checked='checked']")
          expect(form).to have_selector("input[type='radio'][name='material[create_or_associate_pkg_def]'][value='create']")
          form.find("select.required[name='material[package_definition[repositoryId]]']") do |select|
            expect(select).not_to have_selector("option")
          end
          form.find("select.required[name='material[#{PackageMaterialConfig::PACKAGE_ID}]']") do |select|
            expect(select).not_to have_selector("option")
          end
        end
      end

      it "should pre-select repo and package for the material" do
        @material.setPackageDefinition(@pkg2)
        in_params(:pipeline_name => "pipeline-name", :finger_print => "foo")

        render :partial => "admin/pipelines/materials/package_material_form.html", :locals => {:scope => {:material => @material, :form => @form}}

        expect(response.body).to have_selector("input[type='hidden'][name='material_type'][value='#{@material.getType()}']", visible: :hidden)
        expect(response.body).to have_selector("input[type='radio'][name='material[create_or_associate_pkg_def]'][value='create']")
        expect(response.body).to have_selector("input[type='radio'][name='material[create_or_associate_pkg_def]'][value='associate'][checked='checked']")

        Capybara.string(response.body).find("select.required[name='material[package_definition[repositoryId]]']").tap do |select|
          expect(select).not_to have_selector("option")
        end
        Capybara.string(response.body).find("select.required[name='material[#{PackageMaterialConfig::PACKAGE_ID}]']").tap do |select|
          expect(select).not_to have_selector("option")
        end
      end

      describe "render package definition" do
        before(:each) do
          @material.setPackageDefinition(@pkg2)
          @metadata = PackageConfigurations.new
          @metadata.addConfiguration(PackageConfiguration.new("key1").with(PackageConfiguration::SECURE, false).with(PackageConfiguration::DISPLAY_NAME, "Key 1"))
          @metadata.addConfiguration(PackageConfiguration.new("key2").with(PackageConfiguration::SECURE, false).with(PackageConfiguration::DISPLAY_NAME, "Key 2"))
          @metadata.addConfiguration(PackageConfiguration.new("key3_secure").with(PackageConfiguration::SECURE, true).with(PackageConfiguration::DISPLAY_NAME, "Key 3 Secure"))

          p1 = ConfigurationProperty.new(ConfigurationKey.new("key1"), ConfigurationValue.new("value1"), nil, nil)
          p2 = ConfigurationProperty.new(ConfigurationKey.new("key2"), ConfigurationValue.new("value2"), nil, nil)
          p3_secure = ConfigurationProperty.new(ConfigurationKey.new("key3_secure"), nil, EncryptedConfigurationValue.new("secure"), nil)
          @package = PackageDefinition.new("go", "package-name", Configuration.new([p1, p2, p3_secure].to_java(ConfigurationProperty)))
          @package_view_model_new = PackageViewModel.new(@metadata, @package)
          assign(:package_configuration, @package_view_model_new)
        end

        it "should render show_package_definition with check connection if the form was opened for associating a existing package definition" do
          in_params(:pipeline_name => "pipeline-name", :finger_print => "foo", :material => {:create_or_associate_pkg_def => "associate"})

          stub_template "admin/package_definitions/show_package_definition_for_new_pipeline_wizard" => "show package definition for new pipeline wizard"

          render :partial => "admin/pipelines/materials/package_material_form.html", :locals => {:scope => {:material => @material, :form => @form}}

          assert_template partial: "admin/package_definitions/show_package_definition_for_new_pipeline_wizard", :locals => {:scope => {:package_configuration => @package_view_model_new}}
        end

        it "should render new package definition with check connection if the form was opened to create a new package definition" do
          in_params(:pipeline_name => "pipeline-name", :finger_print => "foo", :material => {:create_or_associate_pkg_def => "create"})

          stub_template "admin/package_definitions/form_for_new_pipeline_wizard" => "form for new pipeline wizard"

          render :partial => "admin/pipelines/materials/package_material_form.html", :locals => {:scope => {:material => @material, :form => @form}}

          assert_template partial: "admin/package_definitions/form_for_new_pipeline_wizard", :locals => {:scope => {:package_configuration => @package_view_model_new}}
        end

        it "should render check connection when a form is opened for creating a new package definition" do
          in_params(:pipeline_name => "pipeline-name", :finger_print => "foo", :material => {:create_or_associate_pkg_def => "create"})

          render :partial => "admin/pipelines/materials/package_material_form.html", :locals => {:scope => {:material => @material, :form => @form}}

          Capybara.string(response.body).find('.new_form_content').tap do |form|
            form.find(".field.no-label-element") do |field|
              expect(field).to have_selector("button.submit#check_package span", :text => "CHECK PACKAGE")
              expect(field).to have_selector("span#package_check_message")
            end
          end
        end

        it "should render check connection when a form is opened for associating an existing package definition" do
          in_params(:pipeline_name => "pipeline-name", :finger_print => "foo", :material => {:create_or_associate_pkg_def => "associate"})

          render :partial => "admin/pipelines/materials/package_material_form.html", :locals => {:scope => {:material => @material, :form => @form}}

          Capybara.string(response.body).find('.new_form_content').tap do |form|
            form.find(".field.no-label-element") do |field|
              expect(field).to have_selector("button.submit#check_package span", :text => "CHECK PACKAGE")
              expect(field).to have_selector("span#package_check_message")
            end
          end
        end

        it "should not render package configuration elements if there is no package configured" do
          assign(:package_configuration, nil)
          in_params(:pipeline_name => "pipeline-name", :finger_print => "foo", :material => {:create_or_associate_pkg_def => "associate"})

          render :partial => "admin/pipelines/materials/package_material_form.html", :locals => {:scope => {:material => @material, :form => @form}}

          expect(response.body).not_to have_selector("#check_package span")
          expect(response.body).not_to have_selector("span#package_check_message")
        end

        it "should render warning if no repositories exist" do
          @cruise_config.setPackageRepositories(PackageRepositories.new)

          render :partial => "admin/pipelines/materials/package_material_form.html", :locals => {:scope => {:material => @material, :form => @form}}

          Capybara.string(response.body).find('.new_form_content').tap do |div|
            expect(div).to have_selector("p.warnings", :text => "No repositories found. Please add a package repository first.")
            div.find("p.warnings") do |warnings|
              expect(warnings).to have_selector("a[href='#{package_repositories_new_path}']", :text => "add a package repository")
            end
          end
        end
      end
    end
  end
end


text:
{% define "title" %}Google I/O 2015{% end %}

{% define "mastheadBgClass" %}bg-photo{% end %}

{% define "masthead" %}

Watch the keynote

{% end %}

{% define "content" %}

  <social-poller url="api/v1/social" posts="{{socialPosts}}" interval="30000"></social-poller>

  <core-toolbar class="navbar__overlay navbar__overlay--video" aria-hidden="{{!fullscreenVideoActive}}" fit>
    <paper-icon-button icon="arrow-back" on-tap="{{closeVideoCard}}" aria-label="Close video" tabindex="{{fullscreenVideoActive ? 0 : -1}}"></paper-icon-button>
    Watch
  </core-toolbar>

  <paper-dialog class="video_overlay-dialog" transition="core-transition-center"
                backdrop?="{{!isIOS}}" layered="false"
                on-core-overlay-close-completed="{{closeMastheadVideo}}">
    <paper-icon-button icon="arrow-back" core-overlay-toggle aria-label="Close dialog"></paper-icon-button>
    <template if="{{mastheadVideoActive}}">

        <google-youtube videoid="7V-fIGMDsmE" fit width="100%" height="100%"
            autohide="1" controls="2" modestbranding="1" showinfo="0"
            iv_load_policy="3" rel="0" autoplay="1"></google-youtube>

    </template>
  </paper-dialog>

Google I/O is for developers - the creative coders who are building what's next.
            Each year, we explore the latest in tech, mobile & beyond.

<paper-progress indeterminate fit hidden?="{{!settingsIOReminder}}"></paper-progress>

            <core-icon icon="io:videocam"></core-icon> Watch the keynote

Featured sessions

            <paper-icon-button icon="io:keyboard-arrow-left" on-tap="{{shiftContentLeft}}"></paper-icon-button>
            <paper-icon-button icon="io:keyboard-arrow-right" on-tap="{{shiftContentRight}}"></paper-icon-button>

          <template repeat="{{session in scheduleData.sessions | featuredSessionsFilter}}">

                  <core-image src="{{session.photoUrl}}"
                              load?="{{!!session}}" sizing="cover" preload
                              placeholder="images/io15-color.png" fade fit></core-image>

{{session.title}}

{{session.speakers | speakerIdsToNameString}}

          </template>

We've wrapped up another amazing year of I/O. Check out the best moments from 2015 in photos.

            See photos from I/O 2015

See what everyone was talking about at #io15

            +googledevelopers<core-icon icon="io:post-gplus"></core-icon>

            @googledevs<core-icon icon="io:post-twitter"></core-icon>

        <social-poller url="api/v1/social" posts="{{socialPosts}}" interval="30000"></social-poller>

        <template if="{{socialPosts.length >= 3}}">

            <template repeat="{{socialPost in socialPosts | limit(3)}}">
              <social-post kind="{{socialPost.kind}}"
                           author="{{socialPost.author}}"
                           url="{{socialPost.url}}"
                           text="{{socialPost.text}}"
                           when="{{socialPost.when}}">
              </social-post>
            </template>

        </template>

  <template if="{{fullscreenVideoActive}}">

      <google-youtube videoid="7V-fIGMDsmE" height="100%" width="100%" fit
                      autohide="1" controls="2" modestbranding="1" showinfo="0"
                      iv_load_policy="3" rel="0" autoplay="1"></google-youtube>

  </template>

{% end %}


text:
from benchfunk import functions
from benchfunk.core import run_stack
from collections import OrderedDict
import itertools
import jug
import numpy as np

nreps = 5

@jug.TaskGenerator
def experiment(func, sn2, niter, seed):
    """Example experiment. Testing the uniform random sampling strategy."""

    # setup objective
    objective = func(sn2, rng=seed)
    bounds = objective.bounds

    ndim = len(bounds)
    xmin, xmax = bounds.T

    # uniform random sampling strategy
    rng = np.random.RandomState(seed)
    X = xmin + (xmax - xmin) * rng.rand(niter, ndim)
    y = np.full(niter, -np.inf)
    xbest = np.empty_like(X)

    for i in xrange(niter):
        y[i] = objective(X[i])
        xbest[i] = X[np.argmax(y)]

    return xbest

# prescribe functions and noise levels to test
funcs = [functions.Gramacy,
        functions.Branin]
sn2s = [0.01, 0.1]
niters = [20, 40, 80]

# list all experiments
experiments = itertools.product(funcs, sn2s, niters)

# build stack of experiments
stack = OrderedDict()
for func, sn2, niter in experiments:
    name = format(func(sn2))
    if name not in stack:
        stack[name] = OrderedDict()

    key = str(niter)    # name the particular run

    # the following keys must correspond to the kwargs of experiment()
    stack[name][key] = dict(func=func, sn2=sn2, niter=niter)

# run stack of tasks
results = run_stack(experiment, stack, nreps)


text:
project_pasteur_rest
.


text:
********
PIDADMIN
********

============
About
============

A persistent identifier (PID) is a long-lasting reference to a digital object—a single file or set of files. With this approach, references to the data are decoupled from its physical location, thus allowing a high degree of flexibility while ensuring that the information will always be accessible.  Catania Science Gateway is committed to this approach, allowing the usage of PIDs to specify the location of the input files of many of the integrated applications. Of course, the user can also employ it to identify the place where the output of a given execution has been stored.  pidAdmin is a very simple application devoted to manage these PIDs. It allows to create or delete PIDs corresponding to the different existing applications, greatly simplifying their management and making it accesible to any user of Catania Science Gateway.

============
Installation
============
Following instructions are meant for science gateway maintainers while generic users can skip this section.
To install the portlet it is enough to install the war file into the application server and then configure the preference settings into the portlet preferences pane.

Preferences are splitted in three separate parts: Generic, Infrastructures and the application execution setting.
The generic part contains the **Log level** which contains one of following values, sorted by decreasing level: info, debug, warning and error.

The **Application Identifier** refers to theId field value of the GridEngine 'UsersTracking'database table: GridInteractions.

The infrastructure part consists of different settings related to the destination of users job execution. The fields belonging to this category are:

 **Enable infrastructure**: A true/false flag which enables or disable the current infrastructure;

 **Infrastructure Name**: The infrastructure name for these settings;

 **Infrastructure Acronym**: A short name representing the infrastructure;

 **BDII host**: The Infrastructure information system endpoint (URL). Infrastructure preferences have been thought initially for the elite Grid based infrastructures;

 **WMS host**: It is possible to specify which is the brokering service endpoint (URL);

 **Robot Proxy values**: This is a collection of several values which configures the robot proxy settings (Host, Port, proxyID, VO, Role, proxy renewal);

 **Job requirements**: This field contains the necessary statements to specify a job execution requirement, such as a particular software, a particular number of CPUs/RAM, etc.

.. image:: images/settings.jpg

Actually, depending on the infrastructure, some of the fields above have an overloaded meaning. Please contact the support for further information or watch existing production portlet settings.

============
Usage
============

pidAdmin allows to manage PIDs. Using its very simple interface user can create, list and delete them. As PIDs can be related to different portlets, they can be chosen in the menu.

.. image:: images/input.png
   :align: center

============
References
============

.. _1: http://agenda.ct.infn.it/event/1110/

* CHAIN-REDS Conference: *"Open Science at the Global Scale: Sharing e-Infrastructures, Sharing Knowledge, Sharing Progress"* – March 31, 2015 – Brussels, Belgium [1_];

============
Contributors
============
Please feel free to contact us any time if you have any questions or comments.

.. _Sci-Track: http://rdgroups.ciemat.es/web/sci-track/

:Authors:
 `Manuel RODRIGUEZ-PASCUAL <mailto:manuel.rodriguez@ciemat.es>`_ - CIEMAT Sci-Track


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.monitor.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** An email receiver. */
@Fluent
public final class EmailReceiver {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(EmailReceiver.class);

    /*
     * The name of the email receiver. Names must be unique across all
     * receivers within an action group.
     */
    @JsonProperty(value = "name", required = true)
    private String name;

    /*
     * The email address of this receiver.
     */
    @JsonProperty(value = "emailAddress", required = true)
    private String emailAddress;

    /*
     * Indicates whether to use common alert schema.
     */
    @JsonProperty(value = "useCommonAlertSchema")
    private Boolean useCommonAlertSchema;

    /*
     * The receiver status of the e-mail.
     */
    @JsonProperty(value = "status", access = JsonProperty.Access.WRITE_ONLY)
    private ReceiverStatus status;

    /**
     * Get the name property: The name of the email receiver. Names must be unique across all receivers within an action
     * group.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: The name of the email receiver. Names must be unique across all receivers within an action
     * group.
     *
     * @param name the name value to set.
     * @return the EmailReceiver object itself.
     */
    public EmailReceiver withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the emailAddress property: The email address of this receiver.
     *
     * @return the emailAddress value.
     */
    public String emailAddress() {
        return this.emailAddress;
    }

    /**
     * Set the emailAddress property: The email address of this receiver.
     *
     * @param emailAddress the emailAddress value to set.
     * @return the EmailReceiver object itself.
     */
    public EmailReceiver withEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
        return this;
    }

    /**
     * Get the useCommonAlertSchema property: Indicates whether to use common alert schema.
     *
     * @return the useCommonAlertSchema value.
     */
    public Boolean useCommonAlertSchema() {
        return this.useCommonAlertSchema;
    }

    /**
     * Set the useCommonAlertSchema property: Indicates whether to use common alert schema.
     *
     * @param useCommonAlertSchema the useCommonAlertSchema value to set.
     * @return the EmailReceiver object itself.
     */
    public EmailReceiver withUseCommonAlertSchema(Boolean useCommonAlertSchema) {
        this.useCommonAlertSchema = useCommonAlertSchema;
        return this;
    }

    /**
     * Get the status property: The receiver status of the e-mail.
     *
     * @return the status value.
     */
    public ReceiverStatus status() {
        return this.status;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (name() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property name in model EmailReceiver"));
        }
        if (emailAddress() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property emailAddress in model EmailReceiver"));
        }
    }
}


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

namespace Attributes {
    // Can be applied to any target.
    public class BlahAttribute : Attribute {
        public BlahAttribute() { }
    }

    // Can be applied to any enums only.
    // There are 2 named parameters, Inherited (def. true) and AllowMultiple (def. false).
    [AttributeUsage(AttributeTargets.Enum, Inherited = false)]
    public class BlahAttribute2 : Attribute {
        public BlahAttribute2() { }
    }

    // This shows how to create an attribute with some mandatory parameters
    // (passed to the constructor) and some optional ones (properties).
    // Note that a Type can be used as a parameter (clients must use typeof() operator).
    public class BlahAttribute3 : Attribute {
        private int m_X;
        private string m_Y;

        public BlahAttribute3(int x) {
            m_X = x;
        }

        public int X {
            get { return m_X; }
            set { m_X = value; }
        }

        public string Y {
            get { return m_Y; }
            set { m_Y = value; }
        }
    }
}


text:
#include <aws/cloudhsmv2/model/ModifyClusterRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::CloudHSMV2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ModifyClusterRequest::ModifyClusterRequest() :
    m_backupRetentionPolicyHasBeenSet(false),
    m_clusterIdHasBeenSet(false)
{
}

Aws::String ModifyClusterRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_backupRetentionPolicyHasBeenSet)
  {
   payload.WithObject("BackupRetentionPolicy", m_backupRetentionPolicy.Jsonize());

  }

  if(m_clusterIdHasBeenSet)
  {
   payload.WithString("ClusterId", m_clusterId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection ModifyClusterRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "BaldrApiService.ModifyCluster"));
  return headers;

}


text:
'use strict';

KylinApp
    .controller('JobCtrl', function ($scope, $q, $routeParams, $interval, $modal, ProjectService, MessageService, JobService,SweetAlert,loadingRequest,UserService,jobConfig,JobList,$window, MessageBox) {

        $scope.jobList = JobList;
        JobList.removeAll();
        $scope.jobConfig = jobConfig;
        $scope.cubeName = JobList.jobFilter.cubeName;
        //$scope.projects = [];
        $scope.action = {};
        $scope.timeFilter = jobConfig.timeFilter[JobList.jobFilter.timeFilterId];
        $scope.searchMode = jobConfig.searchMode[JobList.jobFilter.searchModeId];
        if ($routeParams.jobTimeFilter) {
            $scope.timeFilter = jobConfig.timeFilter[$routeParams.jobTimeFilter];
        }

        $scope.status = [];
        for(var i in JobList.jobFilter.statusIds){
            for(var j in jobConfig.allStatus){
                if(JobList.jobFilter.statusIds[i] == jobConfig.allStatus[j].value){
                    $scope.status.push(jobConfig.allStatus[j]);
                    break;
                }
            }
        }
        $scope.toggleSelection = function toggleSelection(current) {
            var idx = $scope.status.indexOf(current);
            if (idx > -1) {
              $scope.status.splice(idx, 1);
            }else {
              $scope.status.push(current);
            }
        };

        $scope.tabs=[
          {
            "title":"Jobs",
            "active":true
          },
          {
            "title": "Slow Queries",
            "active": false
          }
        ]

        // projectName from page ctrl
        $scope.state = {loading: false, refreshing: false, filterAttr: 'last_modified', filterReverse: true, reverseColumn: 'last_modified', projectName:$scope.projectModel.selectedProject};

        $scope.list = function (offset, limit) {
            var defer = $q.defer();
            if(!$scope.projectModel.projects.length){
                defer.resolve([]);
              return  defer.promise;
            }
            offset = (!!offset) ? offset : 0;

            var statusIds = [];
            angular.forEach($scope.status, function (statusObj, index) {
                statusIds.push(statusObj.value);
            });

            $scope.cubeName=$scope.cubeName == ""?null:$scope.cubeName;
            JobList.jobFilter.cubeName = $scope.cubeName;
            JobList.jobFilter.timeFilterId = $scope.timeFilter.value;
            JobList.jobFilter.searchModeId = _.indexOf(jobConfig.searchMode, $scope.searchMode);
            JobList.jobFilter.statusIds = statusIds;

            var jobRequest = {
                cubeName: $scope.cubeName,
                projectName: $scope.state.projectName,
                status: statusIds,
                offset: offset,
                limit: limit,
                timeFilter: $scope.timeFilter.value,
                jobSearchMode: $scope.searchMode.value
            };
            $scope.state.loading = true;

            return JobList.list(jobRequest).then(function(resp){
                $scope.state.loading = false;
                if (angular.isDefined($scope.state.selectedJob)) {
                    $scope.state.selectedJob = JobList.jobs[ $scope.state.selectedJob.uuid];
                }
                defer.resolve(resp);
                return defer.promise;
            },function(resp){
              $scope.state.loading = false;
              defer.resolve([]);
              SweetAlert.swal('Oops...', resp, 'error');
              return defer.promise;
            });
        }

        $scope.reload = function () {
            // trigger reload action in pagination directive
            $scope.action.reload = !$scope.action.reload;
        };

        $scope.$watch('projectModel.selectedProject', function (newValue, oldValue) {
            if(newValue!=oldValue||newValue==null){
                JobList.removeAll();
                $scope.state.projectName = newValue;
                $scope.reload();
            }

        });
        $scope.resume = function (job) {
            SweetAlert.swal({
                title: '',
                text: 'Are you sure to resume the job?',
                type: '',
                showCancelButton: true,
                confirmButtonColor: '#DD6B55',
                confirmButtonText: "Yes",
                closeOnConfirm: true
            }, function(isConfirm) {
              if(isConfirm) {
                loadingRequest.show();
                JobService.resume({jobId: job.uuid}, {}, function (job) {
                  loadingRequest.hide();
                  JobList.jobs[job.uuid] = job;
                  if (angular.isDefined($scope.state.selectedJob)) {
                    $scope.state.selectedJob = JobList.jobs[$scope.state.selectedJob.uuid];
                  }
                  MessageBox.successNotify('Job has been resumed successfully!');
                }, function (e) {
                  loadingRequest.hide();
                  if (e.data && e.data.exception) {
                    var message = e.data.exception;
                    var msg = !!(message) ? message : 'Failed to take action.';
                    SweetAlert.swal('Oops...', msg, 'error');
                  } else {
                    SweetAlert.swal('Oops...', "Failed to take action.", 'error');
                  }
                });
              }
            });
        }

        $scope.cancel = function (job) {
            SweetAlert.swal({
                title: '',
                text: 'Are you sure to discard the job?',
                type: '',
                showCancelButton: true,
                confirmButtonColor: '#DD6B55',
                confirmButtonText: "Yes",
                closeOnConfirm: true
            }, function(isConfirm) {
              if(isConfirm) {
                loadingRequest.show();
                JobService.cancel({jobId: job.uuid}, {}, function (job) {
                    loadingRequest.hide();
                    $scope.safeApply(function() {
                        JobList.jobs[job.uuid] = job;
                        if (angular.isDefined($scope.state.selectedJob)) {
                            $scope.state.selectedJob = JobList.jobs[ $scope.state.selectedJob.uuid];
                        }

                    });
                    MessageBox.successNotify('Job has been discarded successfully!');
                },function(e){
                    loadingRequest.hide();
                    if(e.data&& e.data.exception){
                        var message =e.data.exception;
                        var msg = !!(message) ? message : 'Failed to take action.';
                        SweetAlert.swal('Oops...', msg, 'error');
                    }else{
                        SweetAlert.swal('Oops...', "Failed to take action.", 'error');
                    }
                });
              }
            });
        }

      $scope.pause = function (job) {
        SweetAlert.swal({
          title: '',
          text: 'Are you sure to pause the job?',
          type: '',
          showCancelButton: true,
          confirmButtonColor: '#DD6B55',
          confirmButtonText: "Yes",
          closeOnConfirm: true
        }, function(isConfirm) {
          if(isConfirm) {
            loadingRequest.show();
            JobService.pause({jobId: job.uuid}, {}, function (job) {
              loadingRequest.hide();
              $scope.safeApply(function() {
                JobList.jobs[job.uuid] = job;
                if (angular.isDefined($scope.state.selectedJob)) {
                  $scope.state.selectedJob = JobList.jobs[ $scope.state.selectedJob.uuid];
                }

              });
              MessageBox.successNotify('Job has been paused successfully!');
            },function(e){
              loadingRequest.hide();
              if(e.data&& e.data.exception){
                var message =e.data.exception;
                var msg = !!(message) ? message : 'Failed to take action.';
                SweetAlert.swal('Oops...', msg, 'error');
              }else{
                SweetAlert.swal('Oops...', "Failed to take action.", 'error');
              }
            });
          }
        });
      }

     $scope.drop = function (job) {
        SweetAlert.swal({
          title: '',
          text: 'Are you sure to drop the job?',
          type: '',
          showCancelButton: true,
          confirmButtonColor: '#DD6B55',
          confirmButtonText: "Yes",
          closeOnConfirm: true
        }, function(isConfirm) {
          if(isConfirm) {
            loadingRequest.show();
            JobService.drop({jobId: job.uuid}, {}, function (job) {
              loadingRequest.hide();
              MessageBox.successNotify('Job has been dropped successfully!');
              $scope.jobList.jobs[job.uuid].dropped = true;
            },function(e){
              loadingRequest.hide();
              if(e.data&& e.data.exception){
                var message =e.data.exception;
                var msg = !!(message) ? message : 'Failed to take action.';
                SweetAlert.swal('Oops...', msg, 'error');
              }else{
                SweetAlert.swal('Oops...', "Failed to take action.", 'error');
              }
            });
          }
        });
      }

      $scope.diagnosisJob =function(job) {
        if (!job){
          SweetAlert.swal('', "No job selected.", 'info');
          return;
        }
        var downloadUrl = Config.service.url + 'diag/job/'+job.uuid+'/download';
        $window.open(downloadUrl);
      }

        $scope.openModal = function () {
            if (angular.isDefined($scope.state.selectedStep)) {
                if ($scope.state.stepAttrToShow == "output") {
                    $scope.state.selectedStep.loadingOp = true;
                    internalOpenModal();
                    var stepId = $scope.state.selectedStep.sequence_id;
                    JobService.stepOutput({jobId: $scope.state.selectedJob.uuid, propValue: $scope.state.selectedStep.id}, function (result) {
                        if (angular.isDefined(JobList.jobs[result['jobId']])) {
                            var tjob = JobList.jobs[result['jobId']];
                            tjob.steps[stepId].cmd_output = result['cmd_output'];
                            tjob.steps[stepId].loadingOp = false;
                        }
                    },function(e){
                      SweetAlert.swal('Oops...',"Failed to load job info, please check system log for details.", 'error');
                    });
                } else {
                    internalOpenModal();
                }
            }
        }

        function internalOpenModal() {
            $modal.open({
                templateUrl: 'jobStepDetail.html',
                controller: jobStepDetail,
                resolve: {
                    step: function () {
                        return $scope.state.selectedStep;
                    },
                    attr: function () {
                        return $scope.state.stepAttrToShow;
                    }
                }
            });
        }
    }
);

var jobStepDetail = function ($scope, $modalInstance, step, attr) {
    $scope.step = step;
    $scope.stepAttrToShow = attr;
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    }
};


text:
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(ParticleSystem))]

public class BNG_TargetAction : MonoBehaviour
{

    public int hp;
    public GameObject TurretObject;
    public Sprite killSprite;
    private BNG_TurretAction taScript;

    private ParticleSystem particles;
    private SpriteRenderer sr;

    //each target has this script that will collect damage and report status, as well as change sprite to dead sprite.
    //turret action can access this script by finding it, it will call the on hit function and kill functions

	// Use this for initialization
	void Start () {

        //get the script on the turret so we can do what we want with it
        taScript = TurretObject.GetComponent<BNG_TurretAction>();

        particles = new ParticleSystem();
        sr = GetComponent<SpriteRenderer>();
	}

	// Update is called once per frame
	void Update () {

        if (hp == 0)
        {
            sr.sprite = killSprite;
            return;
        }

	}

    void doHit()
    {
        hp--;

        taScript.hittingTarget(transform.gameObject);

        //you could do blood splatter or hit effects here.

        if (hp == 0)
        {
            doKill();
        }

    }

    void doWait()
    {
        //this is happening when the object is deactivated, an intermediary split second

    }

    void doKill()
    {
        //print("kill");
        hp = 0;

        //do some kill effects, particles or whatever.

        //you can set the layer to ignore raycast like this and the zapper will not hit it.
        transform.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");

        //you have 2 seconds before it blows!
        Destroy(transform.gameObject, 2f);

    }
}


text:
.. _nsx-rn:

VMware NSX integration
----------------------

VMware NSX is supported as an
:ref:`experimental feature<experimental-features-term>`  in Fuel 6.1.

Resolved NSX issues
+++++++++++++++++++

Known NSX issues
++++++++++++++++

The VMware NSX integration into Mirantis OpenStack 6.0 is supported,
but it has some known limitations:


text:
import {GridTestHelpers} from '../../../unitTesting/grid/base';
import {PaginationComponent, IPaginationOptions} from './pagination';

describe('Pagination component', () => {
  let h: GridTestHelpers;
  let getComponent = (codeBased: IPaginationOptions, domBased: string) => {
    let gridOptions = h.getGridOptions({ pagination: codeBased }, domBased + `<columns><column field="Name"></column></columns>`);
    return new PaginationComponent(<any>h.dataSource, <any>h.aureliaUtils, <any>h.gridInternals, gridOptions);
  }

  beforeEach(() => {
    h = new GridTestHelpers();
    h.beforeEach();
  });

  describe('should be able to create options', () => {

    it('from DOM based settings', () => {
      let pagination = getComponent({}, `<pagination size="10" all.bind="[5,10,15]" range="50"></pagination>`);

      let options = pagination.createOptions();

      expect(options.size).toEqual(10);
      expect(options.all).toEqual([5,10,15]);
      expect(options.range).toEqual(50);
    });

    it('from code based settings', () => {
      let pagination = getComponent({size: 100, all:[100,200,300], range: 50},
      `<pagination size="10" all.bind="[5,10,15]"></pagination>`);

      let options = pagination.createOptions();

      expect(options.size).toEqual(100);
      expect(options.all).toEqual([100,200,300]);
      expect(options.range).toEqual(50);
    });

    it('when configuration is not available', () => {
      let pagination = getComponent(false, ``);

      let options = pagination.createOptions();

      expect(options).toBeFalsy();
    });

    it('with default settings', () => {
      let pagination = getComponent(true, ``);

      let options = pagination.createOptions();

      expect(options).toEqual(pagination.defaultOptions);
    });

  });

  describe('changePage method should', () => {

    it('update view modela and refresh the grid', () => {
      let pagination = getComponent({}, ``);

      pagination.changePage(25);

      expect(pagination.selected).toEqual(25);
      expect(h.gridInternals.refresh.calledOnce).toBe(true);
    });

    it('do nothing if page has not changed', () => {
      let pagination = getComponent({}, ``);

      pagination.changePage(1);

      expect(pagination.selected).toEqual(1);
      expect(h.gridInternals.refresh.calledOnce).toBe(false);
    })

  });

  it('selectFirst method should select first page', () => {
    let pagination = getComponent({}, ``);
    pagination.selected = 2;

    pagination.selectFirst();

    expect(pagination.selected).toEqual(1);
    expect(h.gridInternals.refresh.calledOnce).toBe(true);
  });

  it('selectLast method should select last page', () => {
    let pagination = getComponent({}, ``);
    pagination.lastPage = 5;

    pagination.selectLast();

    expect(pagination.selected).toEqual(5);
    expect(h.gridInternals.refresh.calledOnce).toBe(true);
  });

  describe('selectPrev method should select previous page', () => {
    it('', () => {
      let pagination = getComponent({}, ``);
      pagination.selected = 5;

      pagination.selectPrev();

      expect(pagination.selected).toEqual(4);
      expect(h.gridInternals.refresh.calledOnce).toBe(true);
    });
    it('but only if not first selected', () => {
      let pagination = getComponent({}, ``);
      pagination.selected = 1;

      pagination.selectPrev();

      expect(pagination.selected).toEqual(1);
      expect(h.gridInternals.refresh.calledOnce).toBe(false);
    });
  });

  describe('selectNext method should select next page', () => {
    it('', () => {
      let pagination = getComponent({}, ``);
      pagination.lastPage = 10;
      pagination.selected = 5;

      pagination.selectNext();

      expect(pagination.selected).toEqual(6);
      expect(h.gridInternals.refresh.calledOnce).toBe(true);
    });
    it('but only if not last selected', () => {
      let pagination = getComponent({}, ``);
      pagination.lastPage = 5;
      pagination.selected = 5;

      pagination.selectNext();

      expect(pagination.selected).toEqual(5);
      expect(h.gridInternals.refresh.calledOnce).toBe(false);
    });
  });

  describe('should listen on size change', () => {

    it('and react if changed', () => {
      let pagination = getComponent({size: 100, all:[100,200,300]}, ``);
      pagination.tryEnable();
      pagination.selected = 2;

      h.aureliaUtils.observe.emit(pagination.options, 'size', 25, pagination.options.size);

      expect(pagination.selected).toEqual(1);
      expect(h.gridInternals.refresh.calledOnce).toBe(true);
    });

    it('and do not react if not changed', () => {
      let pagination = getComponent({size: 100, all:[100,200,300]}, ``);
      pagination.tryEnable();
      pagination.selected = 2;

      h.aureliaUtils.observe.emit(pagination.options, 'size', pagination.options.size, pagination.options.size);

      expect(pagination.selected).toEqual(2);
      expect(h.gridInternals.refresh.calledOnce).toBe(false);
    });

  });

  it('should attach appropriate data on data source read', () => {
    let pagination = getComponent({size: 10}, ``);
    pagination.tryEnable();
    pagination.selected = 2;
    let params = <any>{};

    h.dataSource.subscribe.emit('DataRead', params);

    expect(params.page).toEqual(2);
    expect(params.pageSize).toBe(10);
  });

  it('should unregister correctly', () => {
    let pagination = getComponent({}, ``);
    pagination.tryEnable();

    pagination.stop();

    expect(h.dataSource.subscribe.subscribers.length).toBe(0);
    expect(h.aureliaUtils.observe.observers.length).toBe(0);
  });

  describe('should update buttons on data received', () => {

    type resultType = {
      selected: number, items: number[], total: number, buttons: any, lastPage: number
    };
    let test = (options: IPaginationOptions, result: resultType) => {
      let pagination = getComponent(options, ``);
      pagination.tryEnable();
      pagination.selected = result.selected;

      h.dataSource.subscribe.emit('DataReceived', {result: {
        total: result.total
      }});

      expect(pagination.selected).toEqual(result.selected);
      expect(pagination.items).toEqual(result.items);
      expect(pagination.buttons).toEqual(result.buttons);
      expect(pagination.lastPage).toEqual(result.lastPage);
    }

    it('with selected first page', () => {
      test({size: 10, range: 3}, {
        selected: 1,
        items: [1,2,3,4],
        total: 31,
        lastPage: 4,
        buttons: {
          prev: false,
          next: true,
          leftSideOutOfRange: false,
          rightSideOutOfRange: false
        }
      });
      test({size: 10, range: 3}, {
        selected: 1,
        items: [1,2,3,4],
        total: 41,
        lastPage: 5,
        buttons: {
          prev: false,
          next: true,
          leftSideOutOfRange: false,
          rightSideOutOfRange: true
        }
      });
    });

    it('with selected last page', () => {
      test({size: 10, range: 3}, {
        selected: 4,
        items: [1,2,3,4],
        total: 31,
        lastPage: 4,
        buttons: {
          prev: true,
          next: false,
          leftSideOutOfRange: false,
          rightSideOutOfRange: false
        }
      });
      test({size: 10, range: 3}, {
        selected: 5,
        items: [2,3,4,5],
        total: 41,
        lastPage: 5,
        buttons: {
          prev: true,
          next: false,
          leftSideOutOfRange: true,
          rightSideOutOfRange: false
        }
      });
    });

    it('with selected page at the middle', () => {
      test({size: 10, range: 3}, {
        selected: 4,
        items: [1,2,3,4,5,6,7],
        total: 61,
        lastPage: 7,
        buttons: {
          prev: true,
          next: true,
          leftSideOutOfRange: false,
          rightSideOutOfRange: false
        }
      });
      test({size: 10, range: 2}, {
        selected: 4,
        items: [2,3,4,5,6],
        total: 61,
        lastPage: 7,
        buttons: {
          prev: true,
          next: true,
          leftSideOutOfRange: true,
          rightSideOutOfRange: true
        }
      });
    });

  });
});


text:
id: bad87fee1348bd9aedf08736
title: Style the HTML Body Element
challengeType: 0
isHidden: false
videoUrl: 'https://scrimba.com/c/cB77PHW'
forumTopicId: 18313
---

## Description

Now let's start fresh and talk about CSS inheritance.
Every HTML page has a body element.

## Instructions

We can prove that the body element exists here by giving it a background-color of black.
We can do this by adding the following to our style element:

```css
body {
  background-color: black;
}
```

## Tests

```yml
tests:
  - text: Your <code>body</code> element should have the <code>background-color</code> of black.
    testString: assert($("body").css("background-color") === "rgb(0, 0, 0)");
  - text: Your CSS rule should be properly formatted with both opening and closing curly brackets.
    testString: assert(code.match(/<style>\s*body\s*\{\s*background.*\s*:\s*.*;\s*\}\s*<\/style>/i));
  - text: Your CSS rule should end with a semi-colon.
    testString: assert(code.match(/<style>\s*body\s*\{\s*background.*\s*:\s*.*;\s*\}\s*<\/style>/i));

```

## Challenge Seed

```html
<style>

</style>
```

## Solution

```html
<style>
body {
  background-color: black;
}
</style>
```


text:
<ion-header>
  <ion-toolbar>
    <ion-title>
      Ajouter ingrédient
    </ion-title>
    <ion-buttons start>
      <button ion-button (click)="dismiss()">
        Cancel
        <ion-icon name="md-close" showWhen="android,windows"></ion-icon>
      </button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content>

  <ion-searchbar (ionInput)="getItems($event)" (ionCancel)="onCancel($event)" [showCancelButton]="true"></ion-searchbar>
  <ion-list *ngIf="showList" class="results">
    <ion-item *ngFor="let ingredient of getIngredientsFiltered()">
      <button ion-item (click)="addIngredient(ingredient)">
        {{ingredient.title}}
      </button>
    </ion-item>
  </ion-list>

  <page-admin-meals-ingredient-list [ingredients]="ingredientsSelected"></page-admin-meals-ingredient-list>

</ion-content>


text:
using System.Runtime.Serialization;
using System.Xml;
using Machine.Specifications;
using Machine.Specifications.Annotations;

namespace DCSExt.Xml.Tests {
    #region [ TestCaseContext ]
    public abstract class DeserializingContext<TResult> {
        protected static XmlObjectSerializer mDeserializer;
        protected static XmlTextReader mXmlTextReader;
        protected static TResult mResult;

        [UsedImplicitly]
        Establish context = () => {
            mDeserializer = new DataContractSerializerExt(typeof(TResult));
        };

        [UsedImplicitly]
        Because of = () => mResult = (TResult)mDeserializer.ReadObject(mXmlTextReader);
    }
    #endregion
}


text:
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System.Collections.Generic;
using System.IO;
using MSBuild = Microsoft.Build.Evaluation;

namespace Microsoft.VisualStudioTools.TestUtilities.SharedProject {
    /// <summary>
    /// Generates a source code file.  The extension will be the code extension for
    /// the project type being generated and content will be the default content.
    ///
    /// The item is added to the project if not excluded.
    /// </summary>
    public sealed class CompileItem : ProjectContentGenerator {
        public readonly string Name, Content, LinkFile;
        public readonly bool IsExcluded;
        public readonly bool IsMissing;

        /// <summary>
        /// Creates a new compile item.  The item will be generated with the
        /// projects code file extension and sample code.  If the item is excluded
        /// then the file will be written out but not added to the project.
        /// If the item is missing then the file will not be written to disk.
        ///
        /// If content is not provided or is null then the default sample code
        /// from the project type will be used.
        /// </summary>
        public CompileItem(string name, string content = null, bool isExcluded = false, bool isMissing = false, string link = null) {
            Name = name;
            IsExcluded = isExcluded;
            IsMissing = isMissing;
            Content = content;
            LinkFile = link;
        }

        public override void Generate(ProjectType projectType, MSBuild.Project project) {
            var filename = Path.Combine(project.DirectoryPath, Name + projectType.CodeExtension);
            if (!IsMissing) {
                File.WriteAllText(filename, Content ?? projectType.SampleCode);
            }

            if (!IsExcluded) {
                List<KeyValuePair<string, string>> metadata = new List<KeyValuePair<string, string>>();
                if (LinkFile != null) {
                    metadata.Add(new KeyValuePair<string, string>("Link", LinkFile + projectType.CodeExtension));
                }

                project.AddItem(
                    "Compile",
                    Name + projectType.CodeExtension,
                    metadata
                );
            }
        }

        public CompileItem Link(string link) {
            return new CompileItem(
                Name,
                Content,
                IsExcluded,
                IsMissing,
                link
            );
        }
    }

}


text:
/* $NetBSD: softintr.c,v 1.2 2002/03/17 06:28:57 simonb Exp $ */

/*
 * Copyright 2000, 2001
 * Broadcom Corporation. All rights reserved.
 *
 * This software is furnished under license and may be used and copied only
 * in accordance with the following terms and conditions.  Subject to these
 * conditions, you may download, copy, install, use, modify and distribute
 * modified or unmodified copies of this software in source and/or binary
 * form. No title or ownership is transferred hereby.
 *
 * 1) Any source code used, modified or distributed must reproduce and
 *    retain this copyright notice and list of conditions as they appear in
 *    the source file.
 *
 * 2) No right is granted to use any trade name, trademark, or logo of
 *    Broadcom Corporation. Neither the "Broadcom Corporation" name nor any
 *    trademark or logo of Broadcom Corporation may be used to endorse or
 *    promote products derived from this software without the prior written
 *    permission of Broadcom Corporation.
 *
 * 3) THIS SOFTWARE IS PROVIDED "AS-IS" AND ANY EXPRESS OR IMPLIED
 *    WARRANTIES, INCLUDING BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OF
 *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 *    NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL BROADCOM BE LIABLE
 *    FOR ANY DAMAGES WHATSOEVER, AND IN PARTICULAR, BROADCOM SHALL NOT BE
 *    LIABLE FOR DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 *    BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 *    OR OTHERWISE), EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>

__KERNEL_RCSID(0, "$NetBSD: softintr.c,v 1.2 2002/03/17 06:28:57 simonb Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>

/* XXX for uvmexp */
#include <uvm/uvm_extern.h>

#include <machine/intr.h>
#include <machine/systemsw.h>

#include <net/netisr.h>

struct sh {
	struct sh *next;
	void	(*fun)(void *);
	void	*arg;
};

static struct sh *sh_list_head = NULL;
static struct sh **sh_list_tail = &sh_list_head;

static void dosoftnet(void *unused);
static void dosoftclock(void *unused);

void *
softintr_establish(int level, void (*fun)(void *), void *arg)
{
	struct sh *new, *sh;

	new = malloc(sizeof *sh, M_DEVBUF, M_WAITOK);
	new->next = NULL;
	new->fun = fun;
	new->arg = arg;

	return new;
}

void
softintr_disestablish(void *cookie)
{
	struct sh *sh, **prevnext;
	int s;

	s = splhigh();
	for (prevnext = &sh_list_head, sh = *prevnext;
	    sh != NULL;
	    prevnext = &sh->next, sh = *prevnext) {
		if (sh == cookie) {
			*prevnext = sh->next;
			if (*prevnext == NULL)
				sh_list_tail = prevnext;
			break;
		}
	}
	splx(s);
	free(sh, M_DEVBUF);
}

void
softintr_schedule(void *cookie)
{
	struct sh *sh = cookie;
	int s;

	s = splhigh();
	if (sh->next == NULL) {
		*sh_list_tail = sh;
		sh_list_tail = &sh->next;
		cpu_setsoftintr();
	}
	splx(s);
}

void
dosoftints(void)
{
	struct sh *sh;
	void (*fun)(void *), *arg;
	int s;

	while (1) {
		s = splhigh();

		sh = sh_list_head;
		if (sh == NULL)
			break;

		uvmexp.softs++;

		if ((sh_list_head = sh->next) == NULL)
			sh_list_tail = &sh_list_head;
		sh->next = NULL;
		fun = sh->fun;
		arg = sh->arg;

		splx(s);

		(*fun)(arg);
	}
	splx(s);
}

void
setsoftclock()
{
	static struct sh sh_softclock = { NULL, dosoftclock, NULL, };

	softintr_schedule(&sh_softclock);
}

static void
dosoftclock(void *unused)
{

	intrcnt[SOFTCLOCK_INTR]++;
	softclock(NULL);
}

void
setsoftnet()
{
	static struct sh sh_softnet = { NULL, dosoftnet, NULL, };

	softintr_schedule(&sh_softnet);
}

/* XXX BEGIN */
#include "opt_inet.h"
#include <sys/mbuf.h>
#ifdef INET
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/ip_var.h>
#include "arp.h"
#if NARP > 0
#include <netinet/if_inarp.h>
#endif
#endif
#ifdef INET6
# ifndef INET
#  include <netinet/in.h>
# endif
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#endif
/* XXX END */

static void
dosoftnet(void *unused)
{
	int n, s;

	intrcnt[SOFTNET_INTR]++;

	/* XXX could just use netintr! */

	s = splhigh();
	n = netisr;
	netisr = 0;
	splx(s);

#define DONETISR(bit, fn)						\
	do {								\
		if (n & (1 << (bit)))					\
			fn();						\
	} while (0)

#include <net/netisr_dispatch.h>

#undef DONETISR
}


text:
let util = require('../../util.js')

const TYPE = 'super'

exports.type = TYPE

/**
 * Detects usage of ES6 super function.
 */
exports.func = (node, parent) => {
  if (node.type === 'Super') {
    return util.createFeature(node, TYPE)
  }
}


text:
package io.cytodev.freqcalc.objects;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * io.cytodev.freqcalc.objects "FrequencyCalculator"
 * 2016/06/15 @ 17:18
 *
 * @author Roel Walraven <mail@cytodev.io>
 */
public class Translator {
    public String language;
    public String name;
    public String url;

    private Translator(JSONObject object) {
        try {
            this.language = object.getString("language");
            this.name     = object.getString("name");
            this.url      = object.getString("url");
        } catch(JSONException e) {
            e.printStackTrace();
        }
    }

    public static ArrayList<Translator> fromJson(JSONArray jsonObjects) {
        ArrayList<Translator> translators = new ArrayList<>();

        for(int i = 0; i < jsonObjects.length(); i++) {
            try {
                translators.add(new Translator(jsonObjects.getJSONObject(i)));
            } catch(JSONException e) {
                e.printStackTrace();
            }
        }

        return translators;
    }
}


text:
export declare const coreColors: Array<keyof CoreColors>;
export interface TextColor {
    /**
     * Used for: Text
     * @default charcoal800
     */
    text: string;
}
export interface CoreColors extends TextColor {
    /**
     * Default page background
     * Used for: application background
     * @default white
     */
    background: string;
    /**
     * Used as page background
     * In some themes pageBackground and background have a subtle difference
     * wherein the pageBackground is closer to `ui1` but blends are calculated
     * from a more "absolute" background color (white or black)
     */
    pageBackground: string;
    /**
     * Key color is applied strategically across the UI
     * Used for: default action buttons, toggle switches, interactive component accents
     * @default purple400
     */
    key: string;
}
export declare const intentColors: Array<keyof IntentColors>;
export interface IntentColors {
    /**
     * Link text color
     * Used for: Breadcrumb, external link
     * @default blue600
     */
    link: string;
    /**
     * Critical intent color
     * Used for: Delete button, error and validation messages
     * @default red500
     */
    critical: string;
    /**
     * Warn intent color
     * Used for: Warning banner
     * @default yellow500
     */
    warn: string;
    /**
     * Positive intent color
     * Used for: Positive banner
     * @default green500
     */
    positive: string;
    /**
     * Inform intent color
     * Used for: Info banner
     * @default blue500
     */
    inform: string;
    /**
     * Indicates a calculated value
     * @default #319220
     */
    calculation: string;
    /**
     * Indicates dimensionality
     * @default #31689E
     */
    dimension: string;
    /**
     * Indicates measure
     * @default #C2772E
     */
    measure: string;
}
export interface SpecifiableTextColors {
    /**
     * Used by Heading
     * @note This is generally identical to colors.text5
     * @default charcoal800
     */
    title: string;
    /**
     * Used by Paragraph, Ul/Ol
     * @note This is generally identical to colors.text5
     * @default charcoal800
     */
    body: string;
}
export declare type IllustrationColors = {
    /**
     * Used in Illustration background circles
     * If not specified, the background will have a neutral color and simplified style
     */
    illustration1?: string;
    /**
     * Used in Illustration background circles
     * If not specified, the background will have a neutral color and simplified style
     */
    illustration2?: string;
    /**
     * Used in Illustration background circles
     * If not specified, the background will have a neutral color and simplified style
     */
    illustration3?: string;
    /**
     * Used in Illustration background circles
     * If not specified, the background will have a neutral color and simplified style
     */
    illustration4?: string;
    /**
     * Used in Illustration background circles
     * If not specified, the background will have a neutral color and simplified style
     */
    illustration5?: string;
};
export declare const specifiableTextColors: string[];
export declare type SpecifiableColors = CoreColors & IntentColors & IllustrationColors & Partial<SpecifiableTextColors>;
export declare const specifiableColors: Array<keyof SpecifiableColors>;