text:
package org.apache.abdera.model;

import java.util.Comparator;
import java.util.List;

import org.apache.abdera.i18n.iri.IRISyntaxException;

/**
 *

 * Represents an Atom Feed Element
 *

 *

 * Per RFC4287:
 *

 *
 *

 * The "atom:feed" element is the document (i.e., top-level) element of
 * an Atom Feed Document, acting as a container for metadata and data
 * associated with the feed.  Its element children consist of metadata
 * elements followed by zero or more atom:entry child elements.
 *
 * atomFeed =
 *   element atom:feed {
 *       atomCommonAttributes,
 *       (atomAuthor*
 *        & atomCategory*
 *        & atomContributor*
 *        & atomGenerator?
 *        & atomIcon?
 *        & atomId
 *        & atomLink*
 *        & atomLogo?
 *        & atomRights?
 *        & atomSubtitle?
 *        & atomTitle
 *        & atomUpdated
 *        & extensionElement*),
 *       atomEntry*
 *   }
 *
 * This specification assigns no significance to the order of atom:entry
 * elements within the feed.
 *
 * The following child elements are defined by this specification (note
 * that the presence of some of these elements is required):
 *
 * o  atom:feed elements MUST contain one or more atom:author elements,
 *    unless all of the atom:feed element's child atom:entry elements
 *    contain at least one atom:author element.
 * o  atom:feed elements MAY contain any number of atom:category
 *    elements.
 * o  atom:feed elements MAY contain any number of atom:contributor
 *    elements.
 * o  atom:feed elements MUST NOT contain more than one atom:generator
 *    element.
 * o  atom:feed elements MUST NOT contain more than one atom:icon
 *    element.
 * o  atom:feed elements MUST NOT contain more than one atom:logo
 *    element.
 * o  atom:feed elements MUST contain exactly one atom:id element.
 * o  atom:feed elements SHOULD contain one atom:link element with a rel
 *    attribute value of "self".  This is the preferred URI for
 *    retrieving Atom Feed Documents representing this Atom feed.
 * o  atom:feed elements MUST NOT contain more than one atom:link
 *    element with a rel attribute value of "alternate" that has the
 *    same combination of type and hreflang attribute values.
 * o  atom:feed elements MAY contain additional atom:link elements
 *    beyond those described above.
 * o  atom:feed elements MUST NOT contain more than one atom:rights
 *    element.
 * o  atom:feed elements MUST NOT contain more than one atom:subtitle
 *    element.
 * o  atom:feed elements MUST contain exactly one atom:title element.
 * o  atom:feed elements MUST contain exactly one atom:updated element.
 *
 * If multiple atom:entry elements with the same atom:id value appear in
 * an Atom Feed Document, they represent the same entry.  Their
 * atom:updated timestamps SHOULD be different.  If an Atom Feed
 * Document contains multiple entries with the same atom:id, Atom
 * Processors MAY choose to display all of them or some subset of them.
 * One typical behavior would be to display only the entry with the
 * latest atom:updated timestamp.
 *

 */
public interface Feed extends Source {

    /**
     * Returns the complete set of entries contained in this feed
     *
     * @return A listing of atom:entry elements
     */
    List<Entry> getEntries();

    /**
     * Adds a new Entry to the end of the Feeds collection of entries
     *
     * @param entry Add an entry
     */
    Feed addEntry(Entry entry);

    /**
     * Adds a new Entry to the end of the Feeds collection of entries
     *
     * @return A newly created atom:entry
     */
    Entry addEntry();

    /**
     * Adds a new Entry to the start of the Feeds collection of entries
     *
     * @param entry An atom:entry to insert
     */
    Feed insertEntry(Entry entry);

    /**
     * Adds a new Entry to the start of the Feeds collection of entries
     *
     * @return A newly created atom:entry
     */
    Entry insertEntry();

    /**
     * Creates a Source element from this Feed
     *
     * @return Returns a copy of this atom:feed as a atom:source element
     */
    Source getAsSource();

    /**
     * Sorts entries by the atom:updated property
     *
     * @param new_first If true, entries with newer atom:updated values will come first
     */
    Feed sortEntriesByUpdated(boolean new_first);

    /**
     * Sorts entries by the app:edited property. if app:edited is null, use app:updated
     */
    Feed sortEntriesByEdited(boolean new_first);

    /**
     * Sorts entries using the given comparator
     *
     * @param comparator Sort the entries using the comparator
     */
    Feed sortEntries(Comparator<Entry> comparator);

    /**
     * Retrieves the first entry in the feed with the given atom:id value
     *
     * @param id The id to retrieve
     * @return The matching atom:entry
     * @throws IRISyntaxException if the id is malformed
     */
    Entry getEntry(String id);

}


text:
package org.mrgeo.resources.wcs;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mrgeo.core.MrGeoConstants;
import org.mrgeo.junit.IntegrationTest;
import org.mrgeo.test.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.Response;

@SuppressWarnings("all") // Test code, not included in production
public class WcsGetCoverageTest extends WcsGeneratorTestAbstract
{
private static final Logger log = LoggerFactory.getLogger(WcsGetCoverageTest.class);

@BeforeClass
public static void setUpForJUnit()
{
  try
  {
    baselineInput = TestUtils.composeInputDir(WcsGetCoverageTest.class);
    WcsGeneratorTestAbstract.setUpForJUnit();
  }
  catch (final Exception e)
  {
    e.printStackTrace();
  }
}

@AfterClass
public static void teardown()
{
  log.debug("done");
}

@Test
@Category(IntegrationTest.class)
public void testGetMapFullLayerPath() throws Exception
{
  String contentType = "image/geotiff";

  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER",
          "/mrgeo/test-files/org.mrgeo.resources.wcs/WcsGeneratorTestAbstract/IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, contentType, "png");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapGeoTifLargerThanTileSize() throws Exception
{
  String contentType = "image/geotiff";

  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", "1024")
      .queryParam("HEIGHT", "1024")
      .request().get();

  processImageResponse(response, contentType, "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapGeoTifMultipleSourceTiles() throws Exception
{
  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", "image/geotif")
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_MULTIPLE_SOURCE_TILES)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, "image/geotiff", "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapGeoTifNonExistingZoomLevelBelowWithPyramids() throws Exception
{
  String contentType = "image/geotiff";
  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      // pyramid only goes up to zoom level = 10; pass in zoom level = 11
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_PAST_HIGHEST_RES_ZOOM_LEVEL)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, contentType, "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapGeoTifRectangularTileSize() throws Exception
{
  String contentType = "image/geotiff";
  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", "700")
      .queryParam("HEIGHT", "300")
      .request().get();

  processImageResponse(response, contentType, "tif", true);
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapGeoTifSingleSourceTile() throws Exception
{
  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", "image/geotif")
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, "image/geotiff", "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapInvalidFormat() throws Exception
{
  String contentType = "image/abc";

  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      .queryParam("BOUNDINGBOX", "160.312500,-11.250000,161.718750,-9.843750")
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processXMLResponse(response, "testGetMapInvalidFormat.xml", Response.Status.BAD_REQUEST);
}

@Test
@Category(IntegrationTest.class)
public void testGetMapLowerCaseParams() throws Exception
{
  String contentType = "image/tiff";
  Response response = target("wcs")
      .queryParam("service", "WCS")
      .queryParam("version", "1.1.0")
      .queryParam("request", "getcoverage")
      .queryParam("identifier", "IslandsElevation-v2")
      .queryParam("format", contentType)
      .queryParam("boundingbox", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("width", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("height", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, contentType, "png");
  response.close();
}

  /*
   * WmsGenerator doesn't support more than one layer per request.
   */

@Test
@Category(IntegrationTest.class)
public void testGetMapMultipleRequestLayers() throws Exception
{
  String contentType = "image/tiff";
  Response response = target("wcs")
      .queryParam("service", "WCS")
      .queryParam("version", "1.1.0")
      .queryParam("request", "getcoverage")
      .queryParam("identifier", "IslandsElevation-v2,IslandsElevation-v3")
      .queryParam("format", contentType)
      .queryParam("boundingbopx", "160.312500,-11.250000,161.718750,-9.843750")
      .queryParam("width", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("height", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processXMLResponse(response, "testGetMapMultipleRequestLayers.xml", Response.Status.BAD_REQUEST);
}

  /*
   * JPG doesn't support transparency, so a black image is returned for out of bounds requests.
   */

@Test
@Category(IntegrationTest.class)
public void testGetMapOutOfBoundsTif() throws Exception
{
  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", "image/tif")
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_OUT_OF_BOUNDS)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, "image/tiff", "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapTifLargerThanTileSize() throws Exception
{
  String contentType = "image/tiff";

  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", "1024")
      .queryParam("HEIGHT", "1024")
      .request().get();

  processImageResponse(response, contentType, "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapTifMultipleSourceTiles() throws Exception
{
  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", "image/tif")
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_MULTIPLE_SOURCE_TILES)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, "image/tiff", "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapTifNonExistingZoomLevelBelowWithPyramids() throws Exception
{
  String contentType = "image/tiff";

  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      // pyramid only goes up to zoom level = 10; pass in zoom level = 11
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_PAST_HIGHEST_RES_ZOOM_LEVEL)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, contentType, "tif");
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapTifRectangularTileSize() throws Exception
{
  String contentType = "image/tiff";

  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", "700")
      .queryParam("HEIGHT", "300")
      .request().get();

  processImageResponse(response, contentType, "tif", true);
  response.close();
}

@Test
@Category(IntegrationTest.class)
public void testGetMapTifSingleSourceTile() throws Exception
{
  Response response = target("wcs")
      .queryParam("SERVICE", "WCS")
      .queryParam("VERSION", "1.1.0")
      .queryParam("REQUEST", "getcoverage")
      .queryParam("IDENTIFIER", "IslandsElevation-v2")
      .queryParam("FORMAT", "image/tif")
      .queryParam("BOUNDINGBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("HEIGHT", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, "image/tiff", "tif");
  response.close();
}

}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class HiveAdminTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, HiveAdmin
  end
end


text:
package com.happydroids.droidtowers.gui;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.Iterator;
import java.util.List;

import static com.happydroids.droidtowers.gui.FontManager.Default;

public class NewsTickerPanel extends Table {
  private final Label label;
  private List<String> stories;
  private Iterator<String> storiesIterator;

  public NewsTickerPanel() {
    stories = Lists.newArrayList();
    storiesIterator = Iterables.cycle(stories).iterator();

    label = Default.makeLabel("");

    defaults();
    add(Default.makeLabel("NEWS: ", Color.LIGHT_GRAY)).bottom();
    add(label).expandX();

    addStory("Some droids are stuck in the elevator!");
    addStory("Timmy fell into the well!");
    addStory("Bleh!");

    label.setText(storiesIterator.next());

    label.getColor().a = 0f;

    label.addAction(Actions.forever(Actions.sequence(
                                                            Actions.fadeIn(0.35f),
                                                            Actions.delay(5f),
                                                            Actions.fadeOut(0.35f),
                                                            Actions.run(new Runnable() {
                                                              @Override
                                                              public void run() {
                                                                label.setText(storiesIterator.next());
                                                              }
                                                            })
    )));
  }

  private void addStory(String storyText) {
    stories.add(storyText);
    storiesIterator = Iterables.cycle(stories).iterator();
  }

  @Override
  public void act(float delta) {
    super.act(delta);
  }
}


text:
package nl.xillio.xill.plugins.xml.constructs;

import com.google.inject.Inject;
import nl.xillio.xill.api.components.MetaExpression;
import nl.xillio.xill.api.construct.Argument;
import nl.xillio.xill.api.construct.Construct;
import nl.xillio.xill.api.construct.ConstructContext;
import nl.xillio.xill.api.construct.ConstructProcessor;
import nl.xillio.xill.api.data.XmlNode;
import nl.xillio.xill.plugins.xml.services.NodeService;

/**
 * Replaces existing node with new XML node
 *
 * @author Zbynek Hochmann
 */
public class ReplaceNodeConstruct extends Construct {
    @Inject
    private NodeService nodeService;

    @Override
    public ConstructProcessor prepareProcess(ConstructContext context) {
        return new ConstructProcessor(
                (node, xml) -> process(node, xml, nodeService),
                new Argument("node", ATOMIC),
                new Argument("xml", ATOMIC)
        );
    }

    static MetaExpression process(MetaExpression orgNodeVar, MetaExpression replXmlStrVar, NodeService service) {
        XmlNode orgXmlNode = assertMeta(orgNodeVar, "node", XmlNode.class, "XML node");
        String replXmlStr = replXmlStrVar.getStringValue();

        XmlNode newNode = service.replaceNode(orgXmlNode, replXmlStr);

        MetaExpression result = fromValue(newNode.toString());
        result.storeMeta(newNode);
        return result;
    }

}


text:
<?php

namespace Eloquent\Composer\Configuration\Exception;

use Exception;
use PHPUnit\Framework\TestCase;

class InvalidJsonExceptionTest extends TestCase
{
    public function exceptionData()
    {
        return [
            [
                "Invalid JSON in Composer configuration at '/foo/bar': The maximum stack depth has been exceeded.",
                JSON_ERROR_DEPTH,
            ],
            [
                "Invalid JSON in Composer configuration at '/foo/bar': Invalid or malformed JSON.",
                JSON_ERROR_STATE_MISMATCH,
            ],
            [
                "Invalid JSON in Composer configuration at '/foo/bar': Control character error, possibly incorrectly encoded.",
                JSON_ERROR_CTRL_CHAR,
            ],
            [
                "Invalid JSON in Composer configuration at '/foo/bar': Syntax error.",
                JSON_ERROR_SYNTAX,
            ],
            [
                "Invalid JSON in Composer configuration at '/foo/bar': Malformed UTF-8 characters, possibly incorrectly encoded.",
                JSON_ERROR_UTF8,
            ],
            [
                "Invalid JSON in Composer configuration at '/foo/bar': Unknown error.",
                'baz',
            ],
        ];
    }

    /**
     * @dataProvider exceptionData
     */
    public function testConstructor($expectedMessage, $jsonErrorCode)
    {
        $path = '/foo/bar';
        $previous = new Exception();
        $exception = new InvalidJsonException($path, $jsonErrorCode, $previous);

        $this->assertSame($path, $exception->path());
        $this->assertSame($jsonErrorCode, $exception->jsonErrorCode());
        $this->assertSame($expectedMessage, $exception->getMessage());
        $this->assertSame(0, $exception->getCode());
        $this->assertSame($previous, $exception->getPrevious());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenopsidium macrocarpa Å.E. Dahl

### Remarks
null


text:
import json
import os
from datetime import datetime
from pathlib import Path
from unittest.mock import patch

from eth_utils import to_canonical_address

from raiden.storage.migrations.v21_to_v22 import (
    SOURCE_VERSION,
    TARGET_VERSION,
    constraint_has_canonical_identifier_or_values_removed,
    upgrade_v21_to_v22,
    walk_dicts,
)
from raiden.storage.sqlite import SQLiteStorage
from raiden.tests.utils.mocks import MockRaidenService
from raiden.utils.upgrades import UpgradeManager, UpgradeRecord

def setup_storage(db_path):
    storage = SQLiteStorage(str(db_path))

    state_changes_file = Path(__file__).parent / f"data/v{SOURCE_VERSION}_statechanges.json"
    state_changes_data = json.loads(state_changes_file.read_text())
    for state_change_record in state_changes_data:
        storage.write_state_change(
            state_change=json.dumps(state_change_record[1]),
            log_time=datetime.utcnow().isoformat(timespec="milliseconds"),
        )

    events_file = Path(__file__).parent / f"data/v{SOURCE_VERSION}_events.json"
    events_data = json.loads(events_file.read_text())
    event_tuples = []
    for event in events_data:
        state_change_identifier = event[1]
        event_data = json.dumps(event[2])
        log_time = datetime.utcnow().isoformat(timespec="milliseconds")
        event_tuples.append((None, state_change_identifier, log_time, event_data))
    storage.write_events(event_tuples)

    chain_state_data = Path(__file__).parent / f"data/v{SOURCE_VERSION}_chainstate.json"
    chain_state = chain_state_data.read_text()
    snapshots = json.loads(chain_state)
    for identifier, statechange_id, data in zip(*[snapshots[i::3] for i in range(3)]):
        cursor = storage.conn.cursor()
        cursor.execute(
            """
            INSERT INTO state_snapshot(identifier, statechange_id, data)
            VALUES(?, ?, ?)
            """,
            (identifier, statechange_id, json.dumps(data)),
        )
    storage.conn.commit()
    storage.conn.close()
    storage = SQLiteStorage(str(db_path))
    return storage

def test_upgrade_v21_to_v22(tmp_path):
    address = to_canonical_address("0x87A749D9b9c0c91AC009AeeBd74313D1a736A24C")
    with patch("raiden.utils.upgrades.latest_db_file") as latest_db_file:
        old_db_filename = tmp_path / Path(f"v{SOURCE_VERSION}_log.db")
        latest_db_file.return_value = str(old_db_filename)
        storage = setup_storage(str(old_db_filename))
        with patch("raiden.storage.sqlite.RAIDEN_DB_VERSION", new=SOURCE_VERSION):
            storage.update_version()
        storage.conn.close()

        raiden_service_mock = MockRaidenService()
        raiden_service_mock.address = address

        db_path = tmp_path / Path(f"v{TARGET_VERSION}_log.db")
        manager = UpgradeManager(db_filename=str(db_path), raiden=raiden_service_mock)
        with patch(
            "raiden.utils.upgrades.UPGRADES_LIST",
            new=[UpgradeRecord(from_version=SOURCE_VERSION, function=upgrade_v21_to_v22)],
        ):
            manager.run()

        storage = SQLiteStorage(str(db_path))
        for batch in storage.batch_query_event_records(batch_size=500):
            for event in batch:
                walk_dicts(event, constraint_has_canonical_identifier_or_values_removed)
        for batch in storage.batch_query_state_changes(batch_size=500):
            for state_change in batch:
                walk_dicts(state_change, constraint_has_canonical_identifier_or_values_removed)
        for snapshot in storage.get_snapshots():
            walk_dicts(snapshot, constraint_has_canonical_identifier_or_values_removed)

        assert os.path.isfile(str(db_path))
        assert os.path.isfile(str(old_db_filename))
        os.unlink(str(db_path))
        os.unlink(str(old_db_filename))
        assert not os.path.exists(str(db_path))
        assert not os.path.exists(str(old_db_filename))


text:
"""Gather info for scaffolding."""
import json

from homeassistant.util import slugify

from .const import COMPONENT_DIR
from .model import Info
from .error import ExitApp

CHECK_EMPTY = ["Cannot be empty", lambda value: value]

def gather_info(arguments) -> Info:
    """Gather info."""
    existing = arguments.template != "integration"

    if arguments.develop:
        print("Running in developer mode. Automatically filling in info.")
        print()

    if existing:
        if arguments.develop:
            return _load_existing_integration("develop")

        if arguments.integration:
            return _load_existing_integration(arguments.integration)

        return gather_existing_integration()

    if arguments.develop:
        return Info(
            domain="develop",
            name="Develop Hub",
            codeowner="@developer",
            requirement="aiodevelop==1.2.3",
        )

    return gather_new_integration()

def gather_new_integration() -> Info:
    """Gather info about new integration from user."""
    return Info(
        **_gather_info(
            {
                "domain": {
                    "prompt": "What is the domain?",
                    "validators": [
                        CHECK_EMPTY,
                        [
                            "Domains cannot contain spaces or special characters.",
                            lambda value: value == slugify(value),
                        ],
                        [
                            "There already is an integration with this domain.",
                            lambda value: not (COMPONENT_DIR / value).exists(),
                        ],
                    ],
                },
                "name": {
                    "prompt": "What is the name of your integration?",
                    "validators": [CHECK_EMPTY],
                },
                "codeowner": {
                    "prompt": "What is your GitHub handle?",
                    "validators": [
                        CHECK_EMPTY,
                        [
                            'GitHub handles need to start with an "@"',
                            lambda value: value.startswith("@"),
                        ],
                    ],
                },
                "requirement": {
                    "prompt": "What PyPI package and version do you depend on? Leave blank for none.",
                    "validators": [
                        [
                            "Versions should be pinned using '=='.",
                            lambda value: not value or "==" in value,
                        ]
                    ],
                },
                "authentication": {
                    "prompt": "Does Home Assistant need the user to authenticate to control the device/service? (yes/no)",
                    "default": "yes",
                    "validators": [
                        [
                            "Type either 'yes' or 'no'",
                            lambda value: value in ("yes", "no"),
                        ]
                    ],
                    "convertor": lambda value: value == "yes",
                },
                "discoverable": {
                    "prompt": "Is the device/service discoverable on the local network? (yes/no)",
                    "default": "no",
                    "validators": [
                        [
                            "Type either 'yes' or 'no'",
                            lambda value: value in ("yes", "no"),
                        ]
                    ],
                    "convertor": lambda value: value == "yes",
                },
            }
        )
    )

def gather_existing_integration() -> Info:
    """Gather info about existing integration from user."""
    answers = _gather_info(
        {
            "domain": {
                "prompt": "What is the domain?",
                "validators": [
                    CHECK_EMPTY,
                    [
                        "Domains cannot contain spaces or special characters.",
                        lambda value: value == slugify(value),
                    ],
                    [
                        "This integration does not exist.",
                        lambda value: (COMPONENT_DIR / value).exists(),
                    ],
                ],
            }
        }
    )

    return _load_existing_integration(answers["domain"])

def _load_existing_integration(domain) -> Info:
    """Load an existing integration."""
    if not (COMPONENT_DIR / domain).exists():
        raise ExitApp("Integration does not exist", 1)

    manifest = json.loads((COMPONENT_DIR / domain / "manifest.json").read_text())

    return Info(domain=domain, name=manifest["name"])

def _gather_info(fields) -> dict:
    """Gather info from user."""
    answers = {}

    for key, info in fields.items():
        hint = None
        while key not in answers:
            if hint is not None:
                print()
                print(f"Error: {hint}")

            try:
                print()
                msg = info["prompt"]
                if "default" in info:
                    msg += f" [{info['default']}]"
                value = input(f"{msg}\n> ")
            except (KeyboardInterrupt, EOFError):
                raise ExitApp("Interrupted!", 1)

            value = value.strip()

            if value == "" and "default" in info:
                value = info["default"]

            hint = None

            for validator_hint, validator in info["validators"]:
                if not validator(value):
                    hint = validator_hint
                    break

            if hint is None:
                if "convertor" in info:
                    value = info["convertor"](value)
                answers[key] = value

    print()
    return answers


text:
namespace Chef
{
    using System;

    public class Chef
    {
        public void Cook()
        {
            Potato potato = this.GetPotato();
            Carrot carrot = this.GetCarrot();
            Bowl bowl = this.GetBowl();

            this.Peel(potato);
            this.Cut(potato);
            bowl.Add(carrot);

            this.Peel(carrot);
            this.Cut(carrot);
            bowl.Add(potato);
        }

        private Potato GetPotato()
        {
            return new Potato();
        }

        private Bowl GetBowl()
        {
            return new Bowl();
        }

        private Carrot GetCarrot()
        {
            return new Carrot();
        }

        private void Peel(Vegetable vegetable)
        {
            throw new NotImplementedException();
        }

        private void Cut(Vegetable potato)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package io.clickhandler.web.reactGwt.client.react;

import io.clickhandler.web.reactGwt.client.Func;
import io.clickhandler.web.reactGwt.client.Jso;
import io.clickhandler.web.reactGwt.client.Reflection;
import io.clickhandler.web.reactGwt.client.dom.DOM;

/**
 *
 * @param <P>
 */
public abstract class ExternalComponent<P> {
    public ExternalComponent() {
    }

    public native P createProps() /*-{
        return {};
    }-*/;

    protected void initProps(P props) {
    }

    protected abstract ReactClass<P> reactClass();

    protected P defaultProps() {
        final P props = createProps();
        try {
            initProps(props);
            Reflection.assign(props, reactClass().getDefaultProps());
            applyKey(props);
        } catch (Throwable e) {
            // Ignore.
        }
        return props;
    }

    protected void applyKey(P props) {
        Object key = Reflection.get(props, "key");
        if (key == null) {
            Reflection.set(props, "key", io.clickhandler.web.reactGwt.client.react.ChildCounter.get().newKey());
        }
    }

    public ReactElement $() {
        return io.clickhandler.web.reactGwt.client.react.React.createElement(reactClass(), defaultProps());
    }

    public ReactElement $(Object... children) {
        return io.clickhandler.web.reactGwt.client.react.React.createElement(reactClass(), defaultProps(), children);
    }

    public ReactElement $(Func.Run1<P> propsCallback) {
        P props = defaultProps();
        if (props == null) props = Jso.create();
        if (propsCallback != null) {
            propsCallback.run(props);
        }
        return io.clickhandler.web.reactGwt.client.react.React.createElement(reactClass(), props);
    }

    public ReactElement $(Func.Run1<P> propsCallback, Func.Run1<DOM.ChildList> childCallback) {
        P props = defaultProps();
        if (props == null) props = Jso.create();
        if (propsCallback != null) {
            propsCallback.run(props);
        }

        final DOM.ChildList childList = new DOM.ChildList();
        if (childCallback != null) {
            childCallback.run(childList);
        }

        return io.clickhandler.web.reactGwt.client.react.React.createElement(reactClass(), props, childList.toArray());
    }

    public ReactElement $(Func.Run1<P> propsCallback, Object... children) {
        P props = defaultProps();
        if (props == null) props = Jso.create();
        if (propsCallback != null) {
            propsCallback.run(props);
        }
        return io.clickhandler.web.reactGwt.client.react.React.createElement(reactClass(), props, children);
    }

    public ReactElement $$(Func.Run1<DOM.ChildList> childCallback) {
        P props = defaultProps();
        if (props == null) props = Jso.create();
        final DOM.ChildList childList = new DOM.ChildList();
        if (childCallback != null) {
            childCallback.run(childList);
        }
        return io.clickhandler.web.reactGwt.client.react.React.createElement(reactClass(), props, childList.toArray());
    }
}


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

<TITLE>
MenuWrapperFactory
</TITLE>

<META NAME="date" CONTENT="2013-08-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

android.support.v7.internal.view.menu

Class MenuWrapperFactory

java.lang.Object
  android.support.v7.internal.view.menu.MenuWrapperFactory

public final class MenuWrapperFactory
extends java.lang.Object

Method Summary

static MenuItem
createMenuItemWrapper(android.view.MenuItem frameworkMenuItem)

static Menu
createMenuWrapper(android.view.Menu frameworkMenu)

static android.support.v4.internal.view.SupportMenuItem
createSupportMenuItemWrapper(android.view.MenuItem frameworkMenuItem)

static android.support.v4.internal.view.SupportMenu
createSupportMenuWrapper(android.view.Menu frameworkMenu)

static android.support.v4.internal.view.SupportSubMenu
createSupportSubMenuWrapper(android.view.SubMenu frameworkSubMenu)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

createMenuWrapper

public static Menu createMenuWrapper(android.view.Menu frameworkMenu)

createMenuItemWrapper

public static MenuItem createMenuItemWrapper(android.view.MenuItem frameworkMenuItem)

createSupportMenuWrapper

public static android.support.v4.internal.view.SupportMenu createSupportMenuWrapper(android.view.Menu frameworkMenu)

createSupportSubMenuWrapper

public static android.support.v4.internal.view.SupportSubMenu createSupportSubMenuWrapper(android.view.SubMenu frameworkSubMenu)

createSupportMenuItemWrapper

public static android.support.v4.internal.view.SupportMenuItem createSupportMenuItemWrapper(android.view.MenuItem frameworkMenuItem)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
// ==UserScript==
// @name        HackerNews Paywall warning
// @namespace   voltagex
// @description Adds a warning for paywalls on HackerNews
// @include     https://news.ycombinator.com/
// @include     https://news.ycombinator.com/news*
// @include     https://news.ycombinator.com/newest*
// @include     https://news.ycombinator.com/submitted?*
// @version     0.02
// @grant       none
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// ==/UserScript==

var paywalls = [
'(economist.com)',
'(wsj.com)',
'(nytimes.com)'];

var paywallStyle = "span.sitebit.comhead.paywall::after { content: ' [paywall]' }";

/* https://css-tricks.com/snippets/javascript/inject-new-css-rules/#comment-248379
GM_addStyle() wasn't working for me*/
function injectStyles(rule) {
  // Works in IE6
  var div = $("<div />", {
    html: '<style>' + rule + '</style>'
  }).children().appendTo("body");
}

$('span.sitebit.comhead').each(
	function(i,obj) {
		var site = $.trim($(obj).text());

		if ($.inArray(site, paywalls) > -1)
		{
			$(obj).addClass('paywall');
		}
});

injectStyles(paywallStyle);


text:
package de.codescape.bitvunit.samples.compatibility;

import de.codescape.bitvunit.samples.AbstractBaseSpec;
import org.junit.Test;

import java.net.URL;

import static de.codescape.bitvunit.BitvUnit.allRules;
import static de.codescape.bitvunit.BitvUnit.compliantTo;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * This test demonstrates testing for accessibility with simple URLs.
 *
 * @author Stefan Glase
 * @since 0.7
 */
public class URLSampleSpec extends AbstractBaseSpec {

    @Test
    public void testingAccessibilityWithSimpleURL() throws Exception {
        // create a URL
        URL url = new URL(urlForPage("index.html"));

        // assert accessibility
        assertThat(url, is(compliantTo(allRules())));
    }

}


text:
require 'spec_helper.rb'

describe 'Reservation' do
  it "can read" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.taskrouter.v1.workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                           .workers("WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                           .reservations.list()
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations',
    ))).to eq(true)
  end

  it "receives read_full responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "meta": {
              "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0",
              "key": "reservations",
              "next_page_url": null,
              "page": 0,
              "page_size": 50,
              "previous_page_url": null,
              "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0"
          },
          "reservations": [
              {
                  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "date_created": "2014-05-14T10:50:02Z",
                  "date_updated": "2014-05-15T16:03:42Z",
                  "links": {
                      "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                      "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                      "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                  },
                  "reservation_status": "accepted",
                  "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "worker_name": "Doug",
                  "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
              }
          ]
      }
      ]
    ))

    actual = @client.taskrouter.v1.workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .workers("WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .reservations.list()

    expect(actual).to_not eq(nil)
  end

  it "receives read_empty responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "meta": {
              "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0",
              "key": "reservations",
              "next_page_url": null,
              "page": 0,
              "page_size": 50,
              "previous_page_url": null,
              "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0"
          },
          "reservations": []
      }
      ]
    ))

    actual = @client.taskrouter.v1.workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .workers("WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .reservations.list()

    expect(actual).to_not eq(nil)
  end

  it "can fetch" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.taskrouter.v1.workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                           .workers("WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                           .reservations("WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    ))).to eq(true)
  end

  it "receives fetch responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "2014-05-14T10:50:02Z",
          "date_updated": "2014-05-15T16:03:42Z",
          "links": {
              "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
              "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
              "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
          },
          "reservation_status": "accepted",
          "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "worker_name": "Doug",
          "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.taskrouter.v1.workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .workers("WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .reservations("WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()

    expect(actual).to_not eq(nil)
  end

  it "can update" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.taskrouter.v1.workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                           .workers("WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                           .reservations("WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update()
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    ))).to eq(true)
  end

  it "receives update responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "2014-05-14T10:50:02Z",
          "date_updated": "2014-05-15T16:03:42Z",
          "links": {
              "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
              "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
              "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
          },
          "reservation_status": "accepted",
          "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "worker_name": "Doug",
          "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.taskrouter.v1.workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .workers("WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                  .reservations("WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update()

    expect(actual).to_not eq(nil)
  end
end


text:
using System;
namespace ShareFile.Api.Client.Models
{
    public enum PinLockType
    {
        None = -1,
        UserSelected = 0,
        Numeric = 1,
        Alphanumeric = 2
    }
}


text:
import * as R     from 'ramda'
import * as React from 'react'

export const attitudes = [ 'neutral', 'positive', 'negative' ]
export const emphases  = [ 'primary', 'secondary' ]
export const examples  = (Component: React.StatelessComponent<any>) => (
  emphases.map((emphasis: string, j: number) =>
    attitudes.map((attitude: string, i: number) =>
      <Component key={`${i}-${j}`} {...{ attitude, emphasis }} />
    )
  )
)

export const propTypes = (props: Object) => R.merge(props, {
  attitude: React.PropTypes.oneOf(attitudes),
  emphasis: React.PropTypes.oneOf(emphases),
})

export const defaultProps = (props = {}) => R.merge(props, {
  emphasis: 'primary',
  attitude: 'neutral',
})

export const capitalize   = (s: string): string => s[0].toUpperCase() + s.slice(1)
export const uncapitalize = (s: string): string => s[0].toLowerCase() + s.slice(1)

export const camelToDash = (s: string): string =>
  s.replace(/\W+/g, '-').replace(/([a-z\d])([A-Z])/g, '$1-$2')

export const dashToCamel = (s: string): string =>
  capitalize(s.replace(/\W+(.)/g, (_, chr) => capitalize(chr)))

export const spaceToCamel = (s: string): string =>
  uncapitalize(s.replace(/\W+(.)/g, (_, chr) => capitalize(chr)))

/** Utility function to create a K:V from a list of strings */
export function strEnum<T extends string>(obj: Array<T>): {[K in T]: K} {
  return obj.reduce((soFar, key) => ({ ...soFar, key }), Object.create(null))
}


text:
class CategoryService
  attr_reader :category, :category_params, :sub_category_params

  def initialize(category, category_params, sub_category_params)
    @category = category
    @category_params = category_params
    @sub_category_params = sub_category_params
  end

  def update_category!
    Comfy::Cms::Category.transaction do
      category.update!(category_params)
      update_sub_categories
      update_page_order(:list_order_pages_en)
      update_page_order(:list_order_pages_cy)
    end
  end

  def update_sub_categories
    list_order(:list_order_sub_categories).each_with_index do |category_id, index|
      Comfy::Cms::Category.find(category_id).update!(ordinal: index + 1)
    end
  end

  private

  def update_page_order(locale)
    list_order(locale).each_with_index do |page_id, index|
      categorization(page_id).update!(ordinal: index + 1)
    end
  end

  def categorization(page_id)
    Comfy::Cms::Categorization.find_by(categorized_id: page_id, category_id: category.id)
  end

  def list_order(type)
    sub_category_params[type].to_s.split(',')
  end
end


text:
package cqrs

// InMemoryEventBus provides an inmemory implementation of the VersionedEventPublisher VersionedEventReceiver interfaces
type InMemoryEventBus struct {
	publishedEventsChannel chan VersionedEvent
	startReceiving         bool
}

// NewInMemoryEventBus constructor
func NewInMemoryEventBus() *InMemoryEventBus {
	publishedEventsChannel := make(chan VersionedEvent, 0)
	return &InMemoryEventBus{publishedEventsChannel, false}
}

// PublishEvents publishes events to the event bus
func (bus *InMemoryEventBus) PublishEvents(events []VersionedEvent) error {
	for _, event := range events {
		bus.publishedEventsChannel <- event
	}

	return nil
}

// ReceiveEvents starts a go routine that monitors incoming events and routes them to a receiver channel specified within the options
func (bus *InMemoryEventBus) ReceiveEvents(options VersionedEventReceiverOptions) error {

	go func() {
		for {
			select {
			case ch := <-options.Close:
				ch <- nil
			case versionedEvent := <-bus.publishedEventsChannel:
				if err := options.ReceiveEvent(versionedEvent); err != nil {

				}
			}
		}
	}()

	return nil
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('games', '0002_auto_20150421_1142'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='expansion',
            name='thumbnail',
        ),
        migrations.RemoveField(
            model_name='game',
            name='thumbnail',
        ),
        migrations.AddField(
            model_name='expansion',
            name='image',
            field=models.ImageField(null=True, upload_to=b'expansoes/image/%Y/%m/%d', blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='game',
            name='image',
            field=models.ImageField(null=True, upload_to=b'games/image/%Y/%m/%d', blank=True),
            preserve_default=True,
        ),
    ]


text:
{-# LANGUAGE BangPatterns #-}

module Network.Wai.Handler.Warp.Buffer (
    createWriteBuffer
  , allocateBuffer
  , freeBuffer
  , toBuilderBuffer
  , bufferIO
  ) where

import Data.IORef (IORef, readIORef)
import qualified Data.Streaming.ByteString.Builder.Buffer as B (Buffer (..))
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc (mallocBytes, free)
import Foreign.Ptr (plusPtr)
import Network.Socket.BufferPool

import Network.Wai.Handler.Warp.Imports
import Network.Wai.Handler.Warp.Types

----------------------------------------------------------------

-- | Allocate a buffer of the given size and wrap it in a 'WriteBuffer'
-- containing that size and a finalizer.
createWriteBuffer :: BufSize -> IO WriteBuffer
createWriteBuffer size = do
  bytes <- allocateBuffer size
  return
    WriteBuffer
      { bufBuffer = bytes,
        bufSize = size,
        bufFree = freeBuffer bytes
      }

----------------------------------------------------------------

-- | Allocating a buffer with malloc().
allocateBuffer :: Int -> IO Buffer
allocateBuffer = mallocBytes

-- | Releasing a buffer with free().
freeBuffer :: Buffer -> IO ()
freeBuffer = free

----------------------------------------------------------------
--
-- Utilities
--

toBuilderBuffer :: IORef WriteBuffer -> IO B.Buffer
toBuilderBuffer writeBufferRef = do
    writeBuffer <- readIORef writeBufferRef
    let ptr = bufBuffer writeBuffer
        size = bufSize writeBuffer
    fptr <- newForeignPtr_ ptr
    return $ B.Buffer fptr ptr ptr (ptr `plusPtr` size)

bufferIO :: Buffer -> Int -> (ByteString -> IO ()) -> IO ()
bufferIO ptr siz io = do
    fptr <- newForeignPtr_ ptr
    io $ PS fptr 0 siz


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

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="splitmenubuttons.css" />

Dynamic Drive

Web Design

Web Graphics

What's New

Revised

DD Forums

CSS Library

Image Optimizer

Gradient Image Maker

FavIcon Generator

Item 1a

Item 2a

Item Folder 3a

Sub Item 3.1a

Sub Item 3.2a

Sub Item 3.3a

Sub Item 3.4a

Item 4a

Item Folder 5a

Sub Item 5.1a

Item Folder 5.2a

Sub Item 5.2.1a

Sub Item 5.2.2a

Sub Item 5.2.3a

Sub Item 5.2.4a

Item 6a


text:
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;

namespace Amazon.S3.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Get Bucket Website Request Marshaller
    /// </summary>
    public class GetBucketWebsiteRequestMarshaller : IMarshaller<IRequest, GetBucketWebsiteRequest> ,IMarshaller<IRequest,Amazon.Runtime.AmazonWebServiceRequest>
	{
		public IRequest Marshall(Amazon.Runtime.AmazonWebServiceRequest input)
		{
			return this.Marshall((GetBucketWebsiteRequest)input);
		}

        public IRequest Marshall(GetBucketWebsiteRequest getBucketWebsiteRequest)
        {
            IRequest request = new DefaultRequest(getBucketWebsiteRequest, "AmazonS3");

            request.Suppress404Exceptions = true;
            request.HttpMethod = "GET";

            request.ResourcePath = string.Concat("/", S3Transforms.ToStringValue(getBucketWebsiteRequest.BucketName));
            request.AddSubResource("website");
            request.UseQueryString = true;

            return request;
        }
    }
}


text:
package org.springside.modules.charts.jruby;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;

import org.springside.modules.charts.deprecated.BaseChartTest;

public class TrendsChartTest extends BaseChartTest {
  private static final int WIDTH = 900;
  private static final int HEIGHT = 350;

  private TrendsChart chart;

  public void testTrendsChart() throws ParseException, IOException {
    chart = new TrendsChart(WIDTH, HEIGHT, "fr", true);
    chart.initSerie(0L, "Global", false);
    chart.initSerie(6L, "Efficiency", true);
    chart.initSerie(9L, "Maintanability", false);
    chart.initSerie(3L, "Portability", false);
    chart.initSerie(24L, "Reliability", true);
    chart.initSerie(60L, "Usability", false);

    chart.addMeasure(20.0, stringToDate("12-10-07 8h30"), 0L);
    chart.addMeasure(35.0, stringToDate("12-10-07 8h30"), 6L);
    chart.addMeasure(12.4, stringToDate("12-10-07 8h30"), 9L);
    chart.addMeasure(99.99, stringToDate("12-10-07 8h30"), 3L);
    chart.addMeasure(2.3, stringToDate("12-10-07 8h30"), 24L);
    chart.addMeasure(12.5, stringToDate("12-10-07 8h30"), 60L);

    chart.addMeasure(10.0, stringToDate("12-11-07 8h30"), 0L);
    chart.addMeasure(30.0, stringToDate("12-11-07 8h30"), 6L);
    chart.addMeasure(22.4, stringToDate("12-11-07 8h30"), 9L);
    chart.addMeasure(99.99, stringToDate("12-11-07 8h30"), 3L);
    chart.addMeasure(0.3, stringToDate("12-11-07 8h30"), 24L);
    chart.addMeasure(12.5, stringToDate("12-11-07 8h30"), 60L);

    chart.addMeasure(30.0, stringToDate("12-12-07 8h30"), 0L);
    chart.addMeasure(15.0, stringToDate("12-12-07 8h30"), 6L);
    chart.addMeasure(82.4, stringToDate("12-12-07 8h30"), 9L);
    chart.addMeasure(99.99, stringToDate("12-12-07 8h30"), 3L);
    chart.addMeasure(52.3, stringToDate("12-12-07 8h30"), 24L);
    chart.addMeasure(12.5, stringToDate("12-12-07 8h30"), 60L);

    chart.addLabel(stringToDate("12-11-07 12h35"), "Label A");
    chart.addLabel(stringToDate("11-11-07 12h35"), "Label B", true);

    BufferedImage img = chart.getChartImage();
    assertChartSizeGreaterThan(img, 1000);
    saveChart(img, "trends-chart.png");
  }

  public void testSingleSerieWithoutLegends() throws ParseException, IOException {
    chart = new TrendsChart(WIDTH, HEIGHT, "fr", false);
    chart.initSerie(0L, "single", false);

    chart.addMeasure(20.0, stringToDate("12-10-07 8h30"), 0L);
    chart.addMeasure(10.0, stringToDate("12-11-07 8h30"), 0L);
    chart.addMeasure(30.0, stringToDate("12-12-07 8h30"), 0L);

    BufferedImage img = chart.getChartImage();
    assertChartSizeGreaterThan(img, 1000);
    saveChart(img, "trends-single-without-legends.png");
  }
}


text:
"""
CloudFormation template transform macro: Explode
"""

import re
import sys

EXPLODE_RE = re.compile(r'(?i)!Explode (?P<explode_key>\w+)')

def walk_resource(resource, map_data):
    """Recursively process a resource."""
    if isinstance(resource, dict):
        new_resource = {}
        for key, value in resource.items():
            if isinstance(value, (dict, list)):
                new_resource[key] = walk_resource(value, map_data)
            elif isinstance(value, str):
                new_resource[key] = replace_explode_in_string(value, map_data)
            else:
                new_resource[key] = value
    elif isinstance(resource, list):
        new_resource = []
        for value in resource:
            if isinstance(value, (dict, list)):
                new_resource.append(walk_resource(value, map_data))
            elif isinstance(value, str):
                new_resource.append(replace_explode_in_string(value, map_data))
            else:
                new_resource.append(value)

    else:
        # if the resource is of type string
        new_resource = replace_explode_in_string(resource, map_data)
    return new_resource

def replace_explode_in_string(value, map_data):
    """Recursively process and replace Explode instances in a string."""
    match = EXPLODE_RE.search(value)
    while match:
        explode_key = match.group('explode_key')
        try:
            replace_value = map_data[explode_key]
        except KeyError:
            print("Missing item {} in mapping while processing {}: {}".format(
                explode_key,
                key,
                value))
        if isinstance(replace_value, int):
            value = replace_value
            # No further explosion is possible on an int
            match = None
        else:
            value = value.replace(match.group(0), replace_value)
            match = EXPLODE_RE.search(value)
    return value

def handle_section_transform(section, mappings):
    """Go through template and explode objects in the section."""
    new_section = {}
    for resource_name, resource in section.items():
        try:
            explode_map = resource['ExplodeMap']
            del resource['ExplodeMap']
        except KeyError:
            # This resource does not have an ExplodeMap, so copy it verbatim
            # and move on
            new_section[resource_name] = resource
            continue
        try:
            explode_map_data = mappings[explode_map]
        except KeyError:
            # This resource refers to a mapping entry which doesn't exist, so
            # fail
            print('Unable to find mapping for exploding object {}'.format(resource_name))
            raise
        resource_instances = explode_map_data.keys()
        for resource_instance in resource_instances:
            new_resource = walk_resource(resource, explode_map_data[resource_instance])
            if 'ResourceName' in explode_map_data[resource_instance]:
                new_resource_name = explode_map_data[resource_instance]['ResourceName']
            else:
                new_resource_name = resource_name + resource_instance
            new_section[new_resource_name] = new_resource
    return new_section

def handle_transform(fragment):
    """Go through template and explode objects in the fragment."""
    mappings = fragment['Mappings']
    if 'Conditions' in fragment:
        fragment['Conditions'] = handle_section_transform(fragment['Conditions'], mappings)
    fragment['Resources'] = handle_section_transform(fragment['Resources'], mappings)
    if 'Outputs' in fragment:
        fragment['Outputs'] = handle_section_transform(fragment['Outputs'], mappings)
    return fragment

def handler(event, _context):
    """Handle invocation in Lambda (when CloudFormation processes the Macro)"""
    fragment = event["fragment"]
    status = "success"

    try:
        fragment = handle_transform(fragment)
    except:
        status = "failure"

    return {
        "requestId": event["requestId"],
        "status": status,
        "fragment": fragment,
    }

if __name__ == "__main__":
    """
    If run from the command line, parse the file specified and output it
    This is quite naive; CF YAML tags like !GetAtt will break it (as will
    !Explode, but you can hide that in a string). Probably best to use JSON.
    Relatedly, always outputs JSON.
    """
    if len(sys.argv) == 2:
        import json
        filename = sys.argv[1]
        if filename.endswith(".yml") or filename.endswith(".yaml"):
            try:
                import yaml
            except ImportError:
                print("Please install PyYAML to test yaml templates")
                sys.exit(1)
            with open(filename, 'r') as file_handle:
                loaded_fragment = yaml.safe_load(file_handle)
        elif filename.endswith(".json"):
            with open(sys.argv[1], 'r') as file_handle:
                loaded_fragment = json.load(file_handle)
        else:
            print("Test file needs to end .yaml, .yml or .json")
            sys.exit(1)
        new_fragment = handle_transform(loaded_fragment)
        print(json.dumps(new_fragment))


text:
package main

import (
	"os"
	"regexp"
	"strconv"
	"strings"

	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/util"

	"github.com/urfave/cli"
	ini "gopkg.in/ini.v1"
)

// EnvironmentPrefix environment variables prefixed with this represent ini values to write
const EnvironmentPrefix = "GITEA"

func main() {
	app := cli.NewApp()
	app.Name = "environment-to-ini"
	app.Usage = "Use provided environment to update configuration ini"
	app.Description = `As a helper to allow docker users to update the gitea configuration
	through the environment, this command allows environment variables to
	be mapped to values in the ini.

	Environment variables of the form "GITEA__SECTION_NAME__KEY_NAME"
	will be mapped to the ini section "[section_name]" and the key
	"KEY_NAME" with the value as provided.

	Environment variables are usually restricted to a reduced character
	set "0-9A-Z_" - in order to allow the setting of sections with
	characters outside of that set, they should be escaped as following:
	"_0X2E_" for ".". The entire section and key names can be escaped as
	a UTF8 byte string if necessary. E.g. to configure:

		"""
		...
		[log.console]
		COLORIZE=false
		STDERR=true
		...
		"""

	You would set the environment variables: "GITEA__LOG_0x2E_CONSOLE__COLORIZE=false"
	and "GITEA__LOG_0x2E_CONSOLE__STDERR=false". Other examples can be found
	on the configuration cheat sheet.`
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "custom-path, C",
			Value: setting.CustomPath,
			Usage: "Custom path file path",
		},
		cli.StringFlag{
			Name:  "config, c",
			Value: setting.CustomConf,
			Usage: "Custom configuration file path",
		},
		cli.StringFlag{
			Name:  "work-path, w",
			Value: setting.AppWorkPath,
			Usage: "Set the gitea working path",
		},
		cli.StringFlag{
			Name:  "out, o",
			Value: "",
			Usage: "Destination file to write to",
		},
		cli.BoolFlag{
			Name:  "clear",
			Usage: "Clears the matched variables from the environment",
		},
		cli.StringFlag{
			Name:  "prefix, p",
			Value: EnvironmentPrefix,
			Usage: "Environment prefix to look for - will be suffixed by __ (2 underscores)",
		},
	}
	app.Action = runEnvironmentToIni
	setting.SetCustomPathAndConf("", "", "")

	err := app.Run(os.Args)
	if err != nil {
		log.Fatal("Failed to run app with %s: %v", os.Args, err)
	}
}

func runEnvironmentToIni(c *cli.Context) error {
	providedCustom := c.String("custom-path")
	providedConf := c.String("config")
	providedWorkPath := c.String("work-path")
	setting.SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath)

	cfg := ini.Empty()
	isFile, err := util.IsFile(setting.CustomConf)
	if err != nil {
		log.Fatal("Unable to check if %s is a file. Error: %v", setting.CustomConf, err)
	}
	if isFile {
		if err := cfg.Append(setting.CustomConf); err != nil {
			log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
		}
	} else {
		log.Warn("Custom config '%s' not found, ignore this if you're running first time", setting.CustomConf)
	}
	cfg.NameMapper = ini.SnackCase

	prefix := c.String("prefix") + "__"

	for _, kv := range os.Environ() {
		idx := strings.IndexByte(kv, '=')
		if idx < 0 {
			continue
		}
		eKey := kv[:idx]
		value := kv[idx+1:]
		if !strings.HasPrefix(eKey, prefix) {
			continue
		}
		eKey = eKey[len(prefix):]
		sectionName, keyName := DecodeSectionKey(eKey)
		if len(keyName) == 0 {
			continue
		}
		section, err := cfg.GetSection(sectionName)
		if err != nil {
			section, err = cfg.NewSection(sectionName)
			if err != nil {
				log.Error("Error creating section: %s : %v", sectionName, err)
				continue
			}
		}
		key := section.Key(keyName)
		if key == nil {
			key, err = section.NewKey(keyName, value)
			if err != nil {
				log.Error("Error creating key: %s in section: %s with value: %s : %v", keyName, sectionName, value, err)
				continue
			}
		}
		key.SetValue(value)
	}
	destination := c.String("out")
	if len(destination) == 0 {
		destination = setting.CustomConf
	}
	err = cfg.SaveTo(destination)
	if err != nil {
		return err
	}
	if c.Bool("clear") {
		for _, kv := range os.Environ() {
			idx := strings.IndexByte(kv, '=')
			if idx < 0 {
				continue
			}
			eKey := kv[:idx]
			if strings.HasPrefix(eKey, prefix) {
				_ = os.Unsetenv(eKey)
			}
		}
	}
	return nil
}

const escapeRegexpString = "_0[xX](([0-9a-fA-F][0-9a-fA-F])+)_"

var escapeRegex = regexp.MustCompile(escapeRegexpString)

// DecodeSectionKey will decode a portable string encoded Section__Key pair
// Portable strings are considered to be of the form [A-Z0-9_]*
// We will encode a disallowed value as the UTF8 byte string preceded by _0X and
// followed by _. E.g. _0X2C_ for a '-' and _0X2E_ for '.'
// Section and Key are separated by a plain '__'.
// The entire section can be encoded as a UTF8 byte string
func DecodeSectionKey(encoded string) (string, string) {
	section := ""
	key := ""

	inKey := false
	last := 0
	escapeStringIndices := escapeRegex.FindAllStringIndex(encoded, -1)
	for _, unescapeIdx := range escapeStringIndices {
		preceding := encoded[last:unescapeIdx[0]]
		if !inKey {
			if splitter := strings.Index(preceding, "__"); splitter > -1 {
				section += preceding[:splitter]
				inKey = true
				key += preceding[splitter+2:]
			} else {
				section += preceding
			}
		} else {
			key += preceding
		}
		toDecode := encoded[unescapeIdx[0]+3 : unescapeIdx[1]-1]
		decodedBytes := make([]byte, len(toDecode)/2)
		for i := 0; i < len(toDecode)/2; i++ {
			// Can ignore error here as we know these should be hexadecimal from the regexp
			byteInt, _ := strconv.ParseInt(toDecode[2*i:2*i+2], 16, 0)
			decodedBytes[i] = byte(byteInt)
		}
		if inKey {
			key += string(decodedBytes)
		} else {
			section += string(decodedBytes)
		}
		last = unescapeIdx[1]
	}
	remaining := encoded[last:]
	if !inKey {
		if splitter := strings.Index(remaining, "__"); splitter > -1 {
			section += remaining[:splitter]
			inKey = true
			key += remaining[splitter+2:]
		} else {
			section += remaining
		}
	} else {
		key += remaining
	}
	section = strings.ToLower(section)
	return section, key
}


text:
package generator

import (
	"bytes"
	"fmt"
	"testing"

	"github.com/go-openapi/spec"
	"github.com/go-openapi/swag"
	"github.com/stretchr/testify/assert"
)

func TestBodyParams(t *testing.T) {
	b, err := opBuilder("updateTask", "../fixtures/codegen/todolist.bodyparams.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}

	_, _, op, ok := b.Analyzed.OperationForName("updateTask")
	if assert.True(t, ok) && assert.NotNil(t, op) {
		resolver := &typeResolver{ModelsPackage: b.ModelsPackage, Doc: b.Doc}
		resolver.KnownDefs = make(map[string]struct{})
		for k := range b.Doc.Spec().Definitions {
			resolver.KnownDefs[k] = struct{}{}
		}
		for _, param := range op.Parameters {
			if param.Name == "body" {
				gp, err := b.MakeParameter("a", resolver, param)
				if assert.NoError(t, err) {
					assert.True(t, gp.IsBodyParam())
					if assert.NotNil(t, gp.Schema) {
						assert.True(t, gp.Schema.IsComplexObject)
						assert.False(t, gp.Schema.IsAnonymous)
						assert.Equal(t, "models.Task", gp.Schema.GoType)
					}
				}
			}
		}
	}

	b, err = opBuilder("createTask", "../fixtures/codegen/todolist.bodyparams.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}

	_, _, op, ok = b.Analyzed.OperationForName("createTask")
	if assert.True(t, ok) && assert.NotNil(t, op) {
		resolver := &typeResolver{ModelsPackage: b.ModelsPackage, Doc: b.Doc}
		resolver.KnownDefs = make(map[string]struct{})
		for k := range b.Doc.Spec().Definitions {
			resolver.KnownDefs[k] = struct{}{}
		}
		for _, param := range op.Parameters {
			if param.Name == "body" {
				gp, err := b.MakeParameter("a", resolver, param)
				if assert.NoError(t, err) {
					assert.True(t, gp.IsBodyParam())
					if assert.NotNil(t, gp.Schema) {
						assert.True(t, gp.Schema.IsComplexObject)
						assert.False(t, gp.Schema.IsAnonymous)
						assert.Equal(t, "CreateTaskBody", gp.Schema.GoType)

						gpe, ok := b.ExtraSchemas["CreateTaskBody"]
						assert.True(t, ok)
						assert.True(t, gpe.IsComplexObject)
						assert.False(t, gpe.IsAnonymous)
						assert.Equal(t, "CreateTaskBody", gpe.GoType)
					}
				}
			}
		}
	}
}

var arrayFormParams = []paramTestContext{
	{"siBool", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatBool", "swag.ConvertBool", nil}},
	{"siString", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"", "", nil}},
	{"siNested", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"", "", &paramItemsTestContext{"", "", &paramItemsTestContext{"", "", nil}}}},
	{"siInt", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatInt64", "swag.ConvertInt64", nil}},
	{"siInt32", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatInt32", "swag.ConvertInt32", nil}},
	{"siInt64", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatInt64", "swag.ConvertInt64", nil}},
	{"siFloat", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatFloat64", "swag.ConvertFloat64", nil}},
	{"siFloat32", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatFloat32", "swag.ConvertFloat32", nil}},
	{"siFloat64", "arrayFormParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatFloat64", "swag.ConvertFloat64", nil}},
}

func TestFormArrayParams(t *testing.T) {
	b, err := opBuilder("arrayFormParams", "../fixtures/codegen/todolist.arrayform.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}

	for _, v := range arrayFormParams {
		v.B = b
		if !v.assertParameter(t) {
			t.FailNow()
		}
	}
}

var arrayQueryParams = []paramTestContext{
	{"siBool", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatBool", "swag.ConvertBool", nil}},
	{"siString", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"", "", nil}},
	{"siNested", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"", "", &paramItemsTestContext{"", "", &paramItemsTestContext{"", "", nil}}}},
	{"siInt", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatInt64", "swag.ConvertInt64", nil}},
	{"siInt32", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatInt32", "swag.ConvertInt32", nil}},
	{"siInt64", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatInt64", "swag.ConvertInt64", nil}},
	{"siFloat", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatFloat64", "swag.ConvertFloat64", nil}},
	{"siFloat32", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatFloat32", "swag.ConvertFloat32", nil}},
	{"siFloat64", "arrayQueryParams", "", "", codeGenOpBuilder{}, &paramItemsTestContext{"swag.FormatFloat64", "swag.ConvertFloat64", nil}},
}

func TestQueryArrayParams(t *testing.T) {
	b, err := opBuilder("arrayQueryParams", "../fixtures/codegen/todolist.arrayquery.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}

	for _, v := range arrayQueryParams {
		v.B = b
		if !v.assertParameter(t) {
			t.FailNow()
		}
	}
}

var simplePathParams = []paramTestContext{
	{"siBool", "simplePathParams", "swag.FormatBool", "swag.ConvertBool", codeGenOpBuilder{}, nil},
	{"siString", "simplePathParams", "", "", codeGenOpBuilder{}, nil},
	{"siInt", "simplePathParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siInt32", "simplePathParams", "swag.FormatInt32", "swag.ConvertInt32", codeGenOpBuilder{}, nil},
	{"siInt64", "simplePathParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siFloat", "simplePathParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
	{"siFloat32", "simplePathParams", "swag.FormatFloat32", "swag.ConvertFloat32", codeGenOpBuilder{}, nil},
	{"siFloat64", "simplePathParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
}

func TestSimplePathParams(t *testing.T) {
	b, err := opBuilder("simplePathParams", "../fixtures/codegen/todolist.simplepath.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}
	for _, v := range simplePathParams {
		v.B = b
		if !v.assertParameter(t) {
			t.FailNow()
		}
	}
}

var simpleHeaderParams = []paramTestContext{
	{"id", "simpleHeaderParams", "swag.FormatInt32", "swag.ConvertInt32", codeGenOpBuilder{}, nil},
	{"siBool", "simpleHeaderParams", "swag.FormatBool", "swag.ConvertBool", codeGenOpBuilder{}, nil},
	{"siString", "simpleHeaderParams", "", "", codeGenOpBuilder{}, nil},
	{"siInt", "simpleHeaderParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siInt32", "simpleHeaderParams", "swag.FormatInt32", "swag.ConvertInt32", codeGenOpBuilder{}, nil},
	{"siInt64", "simpleHeaderParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siFloat", "simpleHeaderParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
	{"siFloat32", "simpleHeaderParams", "swag.FormatFloat32", "swag.ConvertFloat32", codeGenOpBuilder{}, nil},
	{"siFloat64", "simpleHeaderParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
}

func TestSimpleHeaderParams(t *testing.T) {
	b, err := opBuilder("simpleHeaderParams", "../fixtures/codegen/todolist.simpleheader.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}
	for _, v := range simpleHeaderParams {
		v.B = b
		if !v.assertParameter(t) {
			t.FailNow()
		}
	}
}

var simpleFormParams = []paramTestContext{
	{"id", "simpleFormParams", "swag.FormatInt32", "swag.ConvertInt32", codeGenOpBuilder{}, nil},
	{"siBool", "simpleFormParams", "swag.FormatBool", "swag.ConvertBool", codeGenOpBuilder{}, nil},
	{"siString", "simpleFormParams", "", "", codeGenOpBuilder{}, nil},
	{"siInt", "simpleFormParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siInt32", "simpleFormParams", "swag.FormatInt32", "swag.ConvertInt32", codeGenOpBuilder{}, nil},
	{"siInt64", "simpleFormParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siFloat", "simpleFormParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
	{"siFloat32", "simpleFormParams", "swag.FormatFloat32", "swag.ConvertFloat32", codeGenOpBuilder{}, nil},
	{"siFloat64", "simpleFormParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
}

func TestSimpleFormParams(t *testing.T) {
	b, err := opBuilder("simpleFormParams", "../fixtures/codegen/todolist.simpleform.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}
	for _, v := range simpleFormParams {
		v.B = b
		if !v.assertParameter(t) {
			t.FailNow()
		}
	}
}

var simpleQueryParams = []paramTestContext{
	{"id", "simpleQueryParams", "swag.FormatInt32", "swag.ConvertInt32", codeGenOpBuilder{}, nil},
	{"siBool", "simpleQueryParams", "swag.FormatBool", "swag.ConvertBool", codeGenOpBuilder{}, nil},
	{"siString", "simpleQueryParams", "", "", codeGenOpBuilder{}, nil},
	{"siInt", "simpleQueryParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siInt32", "simpleQueryParams", "swag.FormatInt32", "swag.ConvertInt32", codeGenOpBuilder{}, nil},
	{"siInt64", "simpleQueryParams", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"siFloat", "simpleQueryParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
	{"siFloat32", "simpleQueryParams", "swag.FormatFloat32", "swag.ConvertFloat32", codeGenOpBuilder{}, nil},
	{"siFloat64", "simpleQueryParams", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
}

func TestSimpleQueryParams(t *testing.T) {
	b, err := opBuilder("simpleQueryParams", "../fixtures/codegen/todolist.simplequery.yml")

	if !assert.NoError(t, err) {
		t.FailNow()
	}
	for _, v := range simpleQueryParams {
		v.B = b
		if !v.assertParameter(t) {
			t.FailNow()
		}
	}
}

type paramItemsTestContext struct {
	Formatter string
	Converter string
	Items     *paramItemsTestContext
}

type paramTestContext struct {
	Name      string
	OpID      string
	Formatter string
	Converter string
	B         codeGenOpBuilder
	Items     *paramItemsTestContext
}

func (ctx *paramTestContext) assertParameter(t testing.TB) bool {
	_, _, op, err := ctx.B.Analyzed.OperationForName(ctx.OpID)
	if assert.True(t, err) && assert.NotNil(t, op) {
		resolver := &typeResolver{ModelsPackage: ctx.B.ModelsPackage, Doc: ctx.B.Doc}
		resolver.KnownDefs = make(map[string]struct{})
		for k := range ctx.B.Doc.Spec().Definitions {
			resolver.KnownDefs[k] = struct{}{}
		}
		for _, param := range op.Parameters {
			if param.Name == ctx.Name {
				gp, err := ctx.B.MakeParameter("a", resolver, param)
				if assert.NoError(t, err) {
					return assert.True(t, ctx.assertGenParam(t, param, gp))
				}
			}
		}
		return false
	}
	return false
}

func (ctx *paramTestContext) assertGenParam(t testing.TB, param spec.Parameter, gp GenParameter) bool {
	// went with the verbose option here, easier to debug
	if !assert.Equal(t, param.In, gp.Location) {
		return false
	}
	if !assert.Equal(t, param.Name, gp.Name) {
		return false
	}
	if !assert.Equal(t, fmt.Sprintf("%q", param.Name), gp.Path) {
		return false
	}
	if !assert.Equal(t, "i", gp.IndexVar) {
		return false
	}
	if !assert.Equal(t, "a", gp.ReceiverName) {
		return false
	}
	if !assert.Equal(t, "a."+swag.ToGoName(param.Name), gp.ValueExpression) {
		return false
	}
	if !assert.Equal(t, ctx.Formatter, gp.Formatter) {
		return false
	}
	if !assert.Equal(t, ctx.Converter, gp.Converter) {
		return false
	}
	if !assert.Equal(t, param.Description, gp.Description) {
		return false
	}
	if !assert.Equal(t, param.CollectionFormat, gp.CollectionFormat) {
		return false
	}
	if !assert.Equal(t, param.Required, gp.Required) {
		return false
	}
	if !assert.Equal(t, param.Minimum, gp.Minimum) || !assert.Equal(t, param.ExclusiveMinimum, gp.ExclusiveMinimum) {
		return false
	}
	if !assert.Equal(t, param.Maximum, gp.Maximum) || !assert.Equal(t, param.ExclusiveMaximum, gp.ExclusiveMaximum) {
		return false
	}
	if !assert.Equal(t, param.MinLength, gp.MinLength) {
		return false
	}
	if !assert.Equal(t, param.MaxLength, gp.MaxLength) {
		return false
	}
	if !assert.Equal(t, param.Pattern, gp.Pattern) {
		return false
	}
	if !assert.Equal(t, param.MaxItems, gp.MaxItems) {
		return false
	}
	if !assert.Equal(t, param.MinItems, gp.MinItems) {
		return false
	}
	if !assert.Equal(t, param.UniqueItems, gp.UniqueItems) {
		return false
	}
	if !assert.Equal(t, param.MultipleOf, gp.MultipleOf) {
		return false
	}
	if !assert.EqualValues(t, param.Enum, gp.Enum) {
		return false
	}
	if !assert.Equal(t, param.Type, gp.SwaggerType) {
		return false
	}
	if !assert.Equal(t, param.Format, gp.SwaggerFormat) {
		return false
	}
	if _, ok := primitives[gp.GoType]; ok {
		if !assert.True(t, gp.IsPrimitive) {
			return false
		}
	} else {
		if !assert.False(t, gp.IsPrimitive) {
			return false
		}
	}
	// verify rendered template
	if param.In == "body" {
		if !assertBodyParam(t, param, gp) {
			return false
		}
		return true
	}

	if ctx.Items != nil {
		return ctx.Items.Assert(t, param.Items, gp.Child)
	}

	return true
}

func assertBodyParam(t testing.TB, param spec.Parameter, gp GenParameter) bool {
	if !assert.Equal(t, "body", param.In) || !assert.Equal(t, "body", gp.Location) {
		return false
	}
	if !assert.NotNil(t, gp.Schema) {
		return false
	}
	return true
}

func (ctx *paramItemsTestContext) Assert(t testing.TB, pItems *spec.Items, gpItems *GenItems) bool {
	if !assert.NotNil(t, pItems) || !assert.NotNil(t, gpItems) {
		return false
	}
	// went with the verbose option here, easier to debug
	if !assert.Equal(t, ctx.Formatter, gpItems.Formatter) {
		return false
	}
	if !assert.Equal(t, ctx.Converter, gpItems.Converter) {
		return false
	}
	if !assert.Equal(t, pItems.CollectionFormat, gpItems.CollectionFormat) {
		return false
	}
	if !assert.Equal(t, pItems.Minimum, gpItems.Minimum) || !assert.Equal(t, pItems.ExclusiveMinimum, gpItems.ExclusiveMinimum) {
		return false
	}
	if !assert.Equal(t, pItems.Maximum, gpItems.Maximum) || !assert.Equal(t, pItems.ExclusiveMaximum, gpItems.ExclusiveMaximum) {
		return false
	}
	if !assert.Equal(t, pItems.MinLength, gpItems.MinLength) {
		return false
	}
	if !assert.Equal(t, pItems.MaxLength, gpItems.MaxLength) {
		return false
	}
	if !assert.Equal(t, pItems.Pattern, gpItems.Pattern) {
		return false
	}
	if !assert.Equal(t, pItems.MaxItems, gpItems.MaxItems) {
		return false
	}
	if !assert.Equal(t, pItems.MinItems, gpItems.MinItems) {
		return false
	}
	if !assert.Equal(t, pItems.UniqueItems, gpItems.UniqueItems) {
		return false
	}
	if !assert.Equal(t, pItems.MultipleOf, gpItems.MultipleOf) {
		return false
	}
	if !assert.EqualValues(t, pItems.Enum, gpItems.Enum) {
		return false
	}
	if !assert.Equal(t, pItems.Type, gpItems.SwaggerType) {
		return false
	}
	if !assert.Equal(t, pItems.Format, gpItems.SwaggerFormat) {
		return false
	}
	if ctx.Items != nil {
		return ctx.Items.Assert(t, pItems.Items, gpItems.Child)
	}
	return true

}

var bug163Properties = []paramTestContext{
	{"stringTypeInQuery", "getSearch", "", "", codeGenOpBuilder{}, nil},
	{"numberTypeInQuery", "getSearch", "swag.FormatFloat64", "swag.ConvertFloat64", codeGenOpBuilder{}, nil},
	{"integerTypeInQuery", "getSearch", "swag.FormatInt64", "swag.ConvertInt64", codeGenOpBuilder{}, nil},
	{"booleanTypeInQuery", "getSearch", "swag.FormatBool", "swag.ConvertBool", codeGenOpBuilder{}, nil},
}

func TestGenParameters_Simple(t *testing.T) {
	b, err := opBuilder("getSearch", "../fixtures/bugs/163/swagger.yml")
	if !assert.NoError(t, err) {
		t.FailNow()
	}
	for _, v := range bug163Properties {
		v.B = b
		if !v.assertParameter(t) {
			t.FailNow()
		}
	}
}

func TestGenParameter_Issue163(t *testing.T) {
	b, err := opBuilder("getSearch", "../fixtures/bugs/163/swagger.yml")
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := parameterTemplate.Execute(buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("get_search_parameters.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "var stringTypeInQueryDefault string = string(\"qsValue\")", res)
					assertInCode(t, "o.StringTypeInQuery = &stringTypeInQueryDefault", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}

func TestGenParameter_Issue195(t *testing.T) {
	b, err := opBuilder("getTesting", "../fixtures/bugs/195/swagger.json")
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := clientParamTemplate.Execute(buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("get_testing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "TestingThis *int64", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}

func TestGenParameter_Issue196(t *testing.T) {
	b, err := opBuilder("postEvents", "../fixtures/bugs/196/swagger.yml")
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := parameterTemplate.Execute(buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("post_events.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "body.Validate", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}

func TestGenParameter_Issue217(t *testing.T) {
	// Check for string

	assertNoValidator(t, "postEcho", "../fixtures/bugs/217/string.yml")
	assertNoValidator(t, "postEcho", "../fixtures/bugs/217/interface.yml")
	assertNoValidator(t, "postEcho", "../fixtures/bugs/217/map.yml")
	assertNoValidator(t, "postEcho", "../fixtures/bugs/217/array.yml")
}

func assertNoValidator(t testing.TB, opName, path string) {
	b, err := opBuilder(opName, path)
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			var buf bytes.Buffer
			err := parameterTemplate.Execute(&buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("post_echo.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertNotInCode(t, "body.Validate", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}

func TestGenParameter_Issue249(t *testing.T) {
	b, err := opBuilder("putTesting", "../fixtures/bugs/249/swagger.json")
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := clientParamTemplate.Execute(buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("put_testing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertNotInCode(t, "valuesTestingThis := o.TestingThis", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}

func TestGenParameter_Issue248(t *testing.T) {
	b, err := opBuilder("CreateThing", "../fixtures/bugs/248/swagger.json")
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := parameterTemplate.Execute(buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("create_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, ", *o.OptionalQueryEnum", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}

func TestGenParameter_Issue350(t *testing.T) {
	b, err := opBuilder("withBoolDefault", "../fixtures/codegen/todolist.allparams.yml")
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := parameterTemplate.Execute(buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("with_bool_default.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "Verbose: &verboseDefault", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}

func TestGenParameter_Issue351(t *testing.T) {
	b, err := opBuilder("withArray", "../fixtures/codegen/todolist.allparams.yml")
	if assert.NoError(t, err) {
		op, err := b.MakeOperation()
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := parameterTemplate.Execute(buf, op)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("with_array.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "validate.MinLength(fmt.Sprintf(\"%s.%v\", \"sha256\", i), \"query\", string(sha256I), 64)", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}


text:
#ifndef ACUINAVDIALOG_H_
#define ACUINAVDIALOG_H_
#include "anav.h"

// Forward class declarations.
class CAcUiNavPreviewButton;

/////////////////////////////////////////////////////////////////////////////
// File Navigation dialog - this is the AutoCAD file navigation dialog.
class ACUI_PORT CAcUiNavDialog : public CNavDialog {
    DECLARE_DYNAMIC(CAcUiNavDialog)

    public:

        // Constructor and destructor.
        CAcUiNavDialog (
            CNavDataArray& dataArray,           // For results of the dialog.
            CNavFilterArray& filterArray,       // Files of type.
            UINT idd=0,                         // Template id, 0 means use the default template for AutoCAD dialog.
            CWnd *pParent=NULL,                 // Dialog parent. NULL means the desktop.
            HINSTANCE hDialogResource=NULL      // Resource ID where template is found. NULL means use the default.
        );
        virtual ~CAcUiNavDialog ();

        // Dialog initialization.
        virtual BOOL OnInitDialog ();

        // Get the "Recent" directory under the "Application Data"
        // directory of the OS for use with the "History" places item.
        virtual BOOL GetRecentDirectory(CString& strRecent);

        // Locate a file in a search path for use with the "Locate" tools menu item.
        virtual BOOL FindInSearchPath(LPCTSTR sBase, CString* pFullPath);

        // Get the default URL to use in the web browser when the web button is selected.
        virtual void GetDefaultBrowserStartURL(CString& strStartPage);

        // Launch a browser and get a URL. Called when the web button is selected.
        virtual BOOL LaunchBrowserDialog(CString& strSelectedURL, LPCTSTR strDialogCaption,
            LPCTSTR strOk, LPCTSTR strStartPage);

        // Display an error in trying to locate a file in the search path when the "Locate"
        // tools menu item is selected.
        virtual void DisplaySearchError(LPCTSTR sBase);

        // Called when the user choses "Locate" form tools menu.
        virtual void OnDoLocate();

        // Return the product name to be used when registering extensions.
        virtual BOOL GetProductName(CString& strProduct);

        // Called at the start of a remote file download operation.
        virtual BOOL BeginDownloadFiles(CStringArray& strURLs, CDWordArray& dwActionCodes);

        // Callback to get additional action code bits for a remote download.
        virtual DWORD GetDownloadActionCodes(CString& strURL);

        // Called when the preview needs painting after it has been erased.
        virtual void OnPaintPreview(LPCTSTR strFullPath, CWnd* previewWnd);

        // Called when the help button is selected.
        virtual void OnDialogHelp();
        virtual void OnDialogHelp(LPCTSTR pTag);

        BOOL GetPreviewPresent();              // Does the dialog have an AutoCAD preview window?
        void SetPreviewPresent(BOOL preview);  // Set the AutoCAD preview window as present.
        BOOL GetPreviewVisible();              // Is the AutoCAD preview window visible?
        void SetPreviewVisible(BOOL visible);  // Set the AutoCAD preview window visible.
        BOOL GetInitialViewButtonChecked();    // Is the initial view checkbox checked?
        void ConvertFlagsToState(int nFlags);  // Sets up dialog internal state. FOR INTERNAL USE ONLY.

    protected:
        virtual void OnFolderItemChange();     // Called when the selection changes.
        virtual void OnFilterChange();         // Called when the filter changes.
        virtual BOOL OnFileNameOK ();          // Called when the commit button is clicked.
        virtual void OnFileNameChange ();      // Called when thetext changes in the file name editbox.
        virtual void PrepareOkMenu(CMenu* pMenu);// Possibly alter the base ok menu.
        virtual void PrepareViewsMenu(CMenu* pMenu);// Possibly alter the base views menu.
        virtual void PrepareToolsMenu(CMenu* pMenu);// Possibly alter the base tools menu.
        virtual void OnURLDownloadSuccess(CString& strURL);// Called when checking for errors after downloading files.
        virtual BOOL GetOptionsState();        // Check for a tab in the options dialog for the current combination of filetype and get/put file..

        void DoDwfOptionsDialog();             // Display the save file as options dialog.
        void InitPreviewState();               // Initialize the preview control.

    protected:
    //{{AFX_MSG(CAcUiNavDialog)
        afx_msg void OnOpenMenuPartialOpen();  // Called when the partial open item is selected.
        afx_msg void OnOpenMenuPartialOpenReadOnly();// Called when the partial open read only item is selected.
        afx_msg void OnViewsMenuPreview();     // Called when the preview item is selected from the view menu.
        afx_msg void OnToolsMenuOptions();     // Called when the options item is selected from the view menu.
        afx_msg void OnDestroy();
    //}}AFX_MSG
        DECLARE_MESSAGE_MAP()

    private:

        // These members are used by AutoCAD's dialogs.
        short m_CmdInProgress;
        BOOL m_bIsOpen;                        // This is the AutoCAD file OPEN dialog.
        BOOL m_bIsSaveAs;                      // This is the AutoCAD file SAVEAS dialog.
        BOOL m_bIsRecover;                     // We are doing a RECOVER.
        BOOL m_bPartialOpenAlwaysDisabled;     // Set by OEM.
        BOOL m_bInitialViewButtonPresent;      // There is an initial view checkbox.
        BOOL m_bInitialViewButtonChecked;      // Initial view checkbox is checked.
        BOOL m_bPartialOpenPresent;            // There is a partial open button.
        BOOL m_bOptionsPresent;                // There is an OPTIONS menu item.
        BOOL m_bPreviewPresent;                // There is a preview.
        BOOL m_bPreviewVisible;                // Preview is visible.
        CAcUiNavPreviewButton* m_previewButton;

        BOOL CanPartiallyOpen(LPCTSTR szfullPath);// Can the file be partially opened?
};
#endif // ACUINAVDIALOG_H_