text:
LOG_SETUP(".searchlib.docsummary.positionsdfw");

namespace search::docsummary {

namespace {

double to_degrees(int32_t microDegrees) {
    double d = microDegrees / 1.0e6;
    return d;
}

}

using search::attribute::BasicType;
using search::attribute::IAttributeContext;
using search::attribute::IAttributeVector;
using search::attribute::IntegerContent;
using search::common::GeoGcd;
using search::common::Location;

LocationAttrDFW::AllLocations
LocationAttrDFW::getAllLocations(GetDocsumsState& state) const
{
    AllLocations retval;
    if (! state._args.locations_possible()) {
        return retval;
    }
    if (state._parsedLocations.empty()) {
        state.parse_locations();
    }
    for (const auto & loc : state._parsedLocations) {
        if (loc.location.valid()) {
            LOG(debug, "found location(field %s) for DFW(field %s)\n",
                loc.field_name.c_str(), getAttributeName().c_str());
            if (getAttributeName() == loc.field_name) {
                retval.matching.push_back(&loc.location);
            } else {
                retval.other.push_back(&loc.location);
            }
        }
    }
    if (retval.empty()) {
        // avoid doing things twice
        state._args.locations_possible(false);
    }
    return retval;
}

LocationAttrDFW::AllLocations::AllLocations() = default;
LocationAttrDFW::AllLocations::~AllLocations() = default;

AbsDistanceDFW::AbsDistanceDFW(const vespalib::string & attrName)
    : LocationAttrDFW(attrName)
{ }

uint64_t
AbsDistanceDFW::findMinDistance(uint32_t docid, GetDocsumsState& state,
                                const std::vector<const GeoLoc *> &locations) const
{
    // ensure result fits in Java "int"
    uint64_t absdist = std::numeric_limits<int32_t>::max();
    uint64_t sqdist = absdist*absdist;
    const auto& attribute = get_attribute(state);
    for (auto location : locations) {
        int32_t docx = 0;
        int32_t docy = 0;
        IntegerContent pos;
        pos.fill(attribute, docid);
        uint32_t numValues = pos.size();
        for (uint32_t i = 0; i < numValues; i++) {
            int64_t docxy(pos[i]);
            vespalib::geo::ZCurve::decode(docxy, &docx, &docy);
            uint64_t dist2 = location->sq_distance_to(GeoLoc::Point{docx, docy});
            if (dist2 < sqdist) {
                sqdist = dist2;
            }
        }
    }
    return (uint64_t) std::sqrt((double) sqdist);
}

void
AbsDistanceDFW::insertField(uint32_t docid, GetDocsumsState& state, vespalib::slime::Inserter &target) const
{
    const auto & all_locations = getAllLocations(state);
    if (all_locations.empty()) {
        return;
    }
    uint64_t absdist = findMinDistance(docid, state, all_locations.best());
    target.insertLong(absdist);
}

//--------------------------------------------------------------------------

PositionsDFW::PositionsDFW(const vespalib::string & attrName, bool useV8geoPositions) :
    AttrDFW(attrName),
    _useV8geoPositions(useV8geoPositions)
{
}

namespace {

void
insertPos(int64_t docxy, vespalib::slime::Inserter &target)
{

    int32_t docx = 0;
    int32_t docy = 0;
    vespalib::geo::ZCurve::decode(docxy, &docx, &docy);
    if (docx == 0 && docy == INT_MIN) {
        LOG(spam, "skipping empty zcurve value");
        return;
    }
    vespalib::slime::Cursor &obj = target.insertObject();
    obj.setLong("y", docy);
    obj.setLong("x", docx);

    double degrees_ns = to_degrees(docy);
    double degrees_ew = to_degrees(docx);

    vespalib::asciistream latlong;
    latlong << vespalib::FloatSpec::fixed;
    if (degrees_ns < 0) {
        latlong << "S" << (-degrees_ns);
    } else {
        latlong << "N" << degrees_ns;
    }
    latlong << ";";
    if (degrees_ew < 0) {
        latlong << "W" << (-degrees_ew);
    } else {
        latlong << "E" << degrees_ew;
    }
    obj.setString("latlong", vespalib::Memory(latlong.str()));
}

void
insertFromAttr(const attribute::IAttributeVector &attribute, uint32_t docid, vespalib::slime::Inserter &target)
{
    IntegerContent pos;
    pos.fill(attribute, docid);
    uint32_t numValues = pos.size();
    LOG(debug, "docid=%d, numValues=%d", docid, numValues);
    if (numValues > 0) {
        if (attribute.getCollectionType() == attribute::CollectionType::SINGLE) {
            insertPos(pos[0], target);
        } else {
            vespalib::slime::Cursor &arr = target.insertArray();
            for (uint32_t i = 0; i < numValues; i++) {
                vespalib::slime::ArrayInserter ai(arr);
                insertPos(pos[i], ai);
            }
        }
    }
}

void insertPosV8(int64_t docxy, vespalib::slime::Inserter &target) {
    int32_t docx = 0;
    int32_t docy = 0;
    vespalib::geo::ZCurve::decode(docxy, &docx, &docy);
    if (docx == 0 && docy == INT_MIN) {
        LOG(spam, "skipping empty zcurve value");
        return;
    }
    double degrees_ns = to_degrees(docy);
    double degrees_ew = to_degrees(docx);
    vespalib::slime::Cursor &obj = target.insertObject();
    obj.setDouble("lat", degrees_ns);
    obj.setDouble("lng", degrees_ew);
    vespalib::asciistream latlong;
    latlong << vespalib::FloatSpec::fixed;
    if (degrees_ns < 0) {
        latlong << "S" << (-degrees_ns);
    } else {
        latlong << "N" << degrees_ns;
    }
    latlong << ";";
    if (degrees_ew < 0) {
        latlong << "W" << (-degrees_ew);
    } else {
        latlong << "E" << degrees_ew;
    }
    obj.setString("latlong", vespalib::Memory(latlong.str()));
}

void insertV8FromAttr(const attribute::IAttributeVector &attribute, uint32_t docid, vespalib::slime::Inserter &target) {
    IntegerContent pos;
    pos.fill(attribute, docid);
    uint32_t numValues = pos.size();
    LOG(debug, "docid=%d, numValues=%d", docid, numValues);
    if (numValues > 0) {
        if (attribute.getCollectionType() == attribute::CollectionType::SINGLE) {
            insertPosV8(pos[0], target);
        } else {
            vespalib::slime::Cursor &arr = target.insertArray();
            for (uint32_t i = 0; i < numValues; i++) {
                vespalib::slime::ArrayInserter ai(arr);
                insertPosV8(pos[i], ai);
            }
        }
    }
}

} // namespace

void
PositionsDFW::insertField(uint32_t docid, GetDocsumsState& dsState, vespalib::slime::Inserter &target) const
{
    if (_useV8geoPositions) {
        insertV8FromAttr(get_attribute(dsState), docid, target);
    } else {
        insertFromAttr(get_attribute(dsState), docid, target);
    }
}

//--------------------------------------------------------------------------

PositionsDFW::UP PositionsDFW::create(const char *attribute_name, const IAttributeManager *attribute_manager, bool useV8geoPositions) {
    if (attribute_manager != nullptr) {
        if (!attribute_name) {
            LOG(debug, "createPositionsDFW: missing attribute name '%p'", attribute_name);
            return {};
        }
        IAttributeContext::UP context = attribute_manager->createContext();
        if (!context.get()) {
            LOG(debug, "createPositionsDFW: could not create context from attribute manager");
            return {};
        }
        const IAttributeVector *attribute = context->getAttribute(attribute_name);
        if (!attribute) {
            LOG(debug, "createPositionsDFW: could not get attribute '%s' from context", attribute_name);
            return {};
        }
    }
    return std::make_unique<PositionsDFW>(attribute_name, useV8geoPositions);
}

std::unique_ptr<DocsumFieldWriter>
AbsDistanceDFW::create(const char *attribute_name, const IAttributeManager *attribute_manager) {
    if (attribute_manager != nullptr) {
        if (!attribute_name) {
            LOG(debug, "createAbsDistanceDFW: missing attribute name '%p'", attribute_name);
            return {};
        }
        IAttributeContext::UP context = attribute_manager->createContext();
        if (!context.get()) {
            LOG(debug, "createAbsDistanceDFW: could not create context from attribute manager");
            return {};
        }
        const IAttributeVector *attribute = context->getAttribute(attribute_name);
        if (!attribute) {
            LOG(debug, "createAbsDistanceDFW: could not get attribute '%s' from context", attribute_name);
            return {};
        }
    }
    return std::make_unique<AbsDistanceDFW>(attribute_name);
}

}


text:
@interface Track : NSObject
@property (nonatomic, strong) NSMutableArray *fixes;
@property (nonatomic, strong) MKPolyline *path;
@property (nonatomic, strong) MKPolyline *shadowPath;

@property (nonatomic, assign) MKCoordinateRegion region;
@end

redpajama_set_name: RedPajamaGithub


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

namespace Cryptany.Core.Router.Data
{
    partial class Tariff
    {
        public string ServiceNumber
        {
            get
            {
                return DBCache.ServiceNumbers[ServiceNumberId].SN;
            }
        }
    }
}


text:
<?php

namespace Migrations;

use Doctrine\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20171016204024 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema): void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->addSql('ALTER TABLE solution_evaluation DROP evaluation_failed');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema): void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->addSql(
            'ALTER TABLE solution_evaluation ADD evaluation_failed TINYINT(1) DEFAULT 0 COMMENT \'(DC2Type:boolean)\''
        );
    }
}


text:
class LogEntry
  # # we store these objects in mongodb
  # include Mongoid::Document
  # include Mongoid::Timestamps
  # #
  # field :action, type: String
  # field :host, type: String
  # field :user_agent, type: String
  # field :referrer, type: String
  # field :user_id, type: Integer
  # field :params, type: Hash
  # #
  # index :created_at
  # index :user_id
  # index :action
  # index :host
  #
  # def user
  #   User.find(user_id)
  # end
  #
  # # return just the primary user agent part of the user agent string
  # # i.e. for the user agent:
  # # Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_4 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8K2 Safari/6533.18.5
  # # only Mozilla/5.0 will be returned
  # def user_agent_main
  #   user_agent.split(' ').first
  # end
  #
end


text:
module KnifeCookbookDoc
  class DefinitionsModel
    include KnifeCookbookDoc::BaseModel
    attr_reader :name

    def initialize(name, filename)
      @name = name
      @filename = filename
      load_descriptions
    end

    def params
      @params ||= {}
    end

    private

    def load_descriptions
      description = extract_description
      current_section = 'main'
      description.each_line do |line|
        if /^ *\@param *([^ ]*) (.*)$/ =~ line
          params[$1] = {}
          params[$1]['descr'] = $2.strip
        elsif /^ *\@section (.*)$/ =~ line
          current_section = $1.strip
        else
          lines = (top_level_descriptions[current_section] || [])
          lines << line.gsub("\n", '')
          top_level_descriptions[current_section] = lines
        end
      end
      load_properties
    end

    def load_properties
      code = IO.read(@filename)
      code.gsub(/^ *define (.*?) (?=do)/m) do
        all = $1.split(' ', 2)
        @name = all.shift.gsub(/:|,/, '')
        next if all.empty?
        all = eval("{#{all.last}}") rescue {}
        all.each do |k, v|
          p_name = k.to_s
          params[p_name] ||= {}
          params[p_name]['default'] = v.nil? ? 'nil' : v
        end
      end
    end
  end
end


text:
var config = require('./config');
try {
  var pkg = require('../../../package.json');
  var generators = config.get('generators') || [];
  if (generators.indexOf(pkg.name) < 0) generators.push(pkg.name);
  config.set('generators', generators);
} catch (e) {}


text:
@interface DiscoveryVCConfig ()

@property (nonatomic,weak) DiscoveryViewController *vc;

@end

@implementation DiscoveryVCConfig

- (void)setup:(DiscoveryViewController *)vc{

    _vc = vc;

    //_vc.view.backgroundColor = [UIColor redColor];

}

#pragma mark - <TJSNavigationConfig>

- (UIView *)tjs_titleView{

    NSString *firstSegment = NSLocalizedString(@"discovery_title_newsInformation", @"新闻资讯");
    NSString *secondSegment = NSLocalizedString(@"discovery_title_roadShowVedio", @"路演视频");
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[firstSegment,secondSegment]];
    [segment tjs_customTitleViewConfig];

    [segment addBlockForControlEvents:UIControlEventValueChanged
                                block:^(id  _Nonnull sender) {
        if([self.vc conformsToProtocol:@protocol(DiscoveryVCConfig)] &&
           [self.vc respondsToSelector:@selector(onTapSegmental:)]){
            [self.vc onTapSegmental:sender];
        }
    }];

    return segment;
}

@end


text:
using FrannHammer.Domain.Contracts;

namespace FrannHammer.WebScraping.Contracts.Moves
{
    public interface IMoveProvider
    {
        IMove Create();
    }
}


text:
using NSubstitute;
using Octokit;
using System;
using System.Threading.Tasks;
using Octokit.Tests;
using Xunit;

public class RepositoryInvitationsClientTests
{
    public class TheCtor
    {
        [Fact]
        public void EnsuresNonNullArguments()
        {
            Assert.Throws<ArgumentNullException>(() => new RepositoryInvitationsClient(null));
        }
    }

    public class TheGetAllForRepositoryMethod
    {
        [Fact]
        public async Task EnsuresNonNullArguments()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);

            await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllForRepository(1, null));
        }

        [Fact]
        public async Task RequestsCorrectUrl()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);

            await client.GetAllForRepository(1);

            connection.Received().GetAll<RepositoryInvitation>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/invitations"), null, "application/vnd.github.swamp-thing-preview+json", Args.ApiOptions);
        }
    }

    public class TheGetAllForCurrentMethod
    {
        [Fact]
        public async Task EnsuresNonNullArguments()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);

            await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllForCurrent(null));
        }

        [Fact]
        public async Task RequestsCorrectUrl()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);

            await client.GetAllForCurrent();

            connection.Received().GetAll<RepositoryInvitation>(Arg.Is<Uri>(u => u.ToString() == "user/repository_invitations"), null, "application/vnd.github.swamp-thing-preview+json", Args.ApiOptions);
        }
    }

    public class TheAcceptMethod
    {
        [Fact]
        public async Task RequestsCorrectUrl()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);

            await client.Accept(1);

            connection.Connection.Received().Patch(Arg.Is<Uri>(u => u.ToString() == "user/repository_invitations/1"), "application/vnd.github.swamp-thing-preview+json");
        }
    }

    public class TheDeclineMethod
    {
        [Fact]
        public async Task RequestsCorrectUrl()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);

            await client.Decline(1);

            connection.Connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "user/repository_invitations/1"), Arg.Any<object>(), "application/vnd.github.swamp-thing-preview+json");
        }
    }

    public class TheDeleteMethod
    {
        [Fact]
        public async Task RequestsCorrectUrl()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);

            await client.Delete(1, 2);

            connection.Connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/invitations/2"), Arg.Any<object>(), "application/vnd.github.swamp-thing-preview+json");
        }
    }

    public class TheEditMethod
    {
        [Fact]
        public async Task RequestsCorrectUrl()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new RepositoryInvitationsClient(connection);
            var updatedInvitation = new InvitationUpdate(InvitationPermissionType.Read);

            await client.Edit(1, 2, updatedInvitation);

            connection.Received().Patch<RepositoryInvitation>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/invitations/2"), Arg.Is<InvitationUpdate>(updatedInvitation), "application/vnd.github.swamp-thing-preview+json");
        }

        [Fact]
        public async Task EnsureNonNullArguments()
        {
            var client = new RepositoryInvitationsClient(Substitute.For<IApiConnection>());

            await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(1, 2, null));
        }
    }
}


text:
package chartutil

import (
	"bytes"
	"encoding/json"
	"fmt"
	"testing"
	"text/template"

	"github.com/golang/protobuf/ptypes/any"

	"k8s.io/helm/pkg/proto/hapi/chart"
	"k8s.io/helm/pkg/timeconv"
	"k8s.io/helm/pkg/version"
	kversion "k8s.io/kubernetes/pkg/version"
)

func TestReadValues(t *testing.T) {
	doc := `# Test YAML parse
poet: "Coleridge"
title: "Rime of the Ancient Mariner"
stanza:
  - "at"
  - "length"
  - "did"
  - cross
  - an
  - Albatross

mariner:
  with: "crossbow"
  shot: "ALBATROSS"

water:
  water:
    where: "everywhere"
    nor: "any drop to drink"
`

	data, err := ReadValues([]byte(doc))
	if err != nil {
		t.Fatalf("Error parsing bytes: %s", err)
	}
	matchValues(t, data)

	tests := []string{`poet: "Coleridge"`, "# Just a comment", ""}

	for _, tt := range tests {
		data, err = ReadValues([]byte(tt))
		if err != nil {
			t.Fatalf("Error parsing bytes (%s): %s", tt, err)
		}
		if data == nil {
			t.Errorf(`YAML string "%s" gave a nil map`, tt)
		}
	}
}

func TestToRenderValuesCaps(t *testing.T) {

	chartValues := `
name: al Rashid
where:
  city: Basrah
  title: caliph
`
	overideValues := `
name: Haroun
where:
  city: Baghdad
  date: 809 CE
`

	c := &chart.Chart{
		Metadata:  &chart.Metadata{Name: "test"},
		Templates: []*chart.Template{},
		Values:    &chart.Config{Raw: chartValues},
		Dependencies: []*chart.Chart{
			{
				Metadata: &chart.Metadata{Name: "where"},
				Values:   &chart.Config{Raw: ""},
			},
		},
		Files: []*any.Any{
			{TypeUrl: "scheherazade/shahryar.txt", Value: []byte("1,001 Nights")},
		},
	}
	v := &chart.Config{Raw: overideValues}

	o := ReleaseOptions{
		Name:      "Seven Voyages",
		Time:      timeconv.Now(),
		Namespace: "al Basrah",
		IsInstall: true,
		Revision:  5,
	}

	caps := &Capabilities{
		APIVersions:   DefaultVersionSet,
		TillerVersion: version.GetVersionProto(),
		KubeVersion:   &kversion.Info{Major: "1"},
	}

	res, err := ToRenderValuesCaps(c, v, o, caps)
	if err != nil {
		t.Fatal(err)
	}

	// Ensure that the top-level values are all set.
	if name := res["Chart"].(*chart.Metadata).Name; name != "test" {
		t.Errorf("Expected chart name 'test', got %q", name)
	}
	relmap := res["Release"].(map[string]interface{})
	if name := relmap["Name"]; name.(string) != "Seven Voyages" {
		t.Errorf("Expected release name 'Seven Voyages', got %q", name)
	}
	if rev := relmap["Revision"]; rev.(int) != 5 {
		t.Errorf("Expected release revision %d, got %q", 5, rev)
	}
	if relmap["IsUpgrade"].(bool) {
		t.Error("Expected upgrade to be false.")
	}
	if !relmap["IsInstall"].(bool) {
		t.Errorf("Expected install to be true.")
	}
	if data := res["Files"].(Files)["scheherazade/shahryar.txt"]; string(data) != "1,001 Nights" {
		t.Errorf("Expected file '1,001 Nights', got %q", string(data))
	}
	if !res["Capabilities"].(*Capabilities).APIVersions.Has("v1") {
		t.Error("Expected Capabilities to have v1 as an API")
	}
	if res["Capabilities"].(*Capabilities).TillerVersion.SemVer == "" {
		t.Error("Expected Capabilities to have a Tiller version")
	}
	if res["Capabilities"].(*Capabilities).KubeVersion.Major != "1" {
		t.Error("Expected Capabilities to have a Kube version")
	}

	var vals Values
	vals = res["Values"].(Values)

	if vals["name"] != "Haroun" {
		t.Errorf("Expected 'Haroun', got %q (%v)", vals["name"], vals)
	}
	where := vals["where"].(map[string]interface{})
	expects := map[string]string{
		"city":  "Baghdad",
		"date":  "809 CE",
		"title": "caliph",
	}
	for field, expect := range expects {
		if got := where[field]; got != expect {
			t.Errorf("Expected %q, got %q (%v)", expect, got, where)
		}
	}
}

func TestReadValuesFile(t *testing.T) {
	data, err := ReadValuesFile("./testdata/coleridge.yaml")
	if err != nil {
		t.Fatalf("Error reading YAML file: %s", err)
	}
	matchValues(t, data)
}

func ExampleValues() {
	doc := `
title: "Moby Dick"
chapter:
  one:
    title: "Loomings"
  two:
    title: "The Carpet-Bag"
  three:
    title: "The Spouter Inn"
`
	d, err := ReadValues([]byte(doc))
	if err != nil {
		panic(err)
	}
	ch1, err := d.Table("chapter.one")
	if err != nil {
		panic("could not find chapter one")
	}
	fmt.Print(ch1["title"])
	// Output:
	// Loomings
}

func TestTable(t *testing.T) {
	doc := `
title: "Moby Dick"
chapter:
  one:
    title: "Loomings"
  two:
    title: "The Carpet-Bag"
  three:
    title: "The Spouter Inn"
`
	d, err := ReadValues([]byte(doc))
	if err != nil {
		t.Fatalf("Failed to parse the White Whale: %s", err)
	}

	if _, err := d.Table("title"); err == nil {
		t.Fatalf("Title is not a table.")
	}

	if _, err := d.Table("chapter"); err != nil {
		t.Fatalf("Failed to get the chapter table: %s\n%v", err, d)
	}

	if v, err := d.Table("chapter.one"); err != nil {
		t.Errorf("Failed to get chapter.one: %s", err)
	} else if v["title"] != "Loomings" {
		t.Errorf("Unexpected title: %s", v["title"])
	}

	if _, err := d.Table("chapter.three"); err != nil {
		t.Errorf("Chapter three is missing: %s\n%v", err, d)
	}

	if _, err := d.Table("chapter.OneHundredThirtySix"); err == nil {
		t.Errorf("I think you mean 'Epilogue'")
	}
}

func matchValues(t *testing.T, data map[string]interface{}) {
	if data["poet"] != "Coleridge" {
		t.Errorf("Unexpected poet: %s", data["poet"])
	}

	if o, err := ttpl("{{len .stanza}}", data); err != nil {
		t.Errorf("len stanza: %s", err)
	} else if o != "6" {
		t.Errorf("Expected 6, got %s", o)
	}

	if o, err := ttpl("{{.mariner.shot}}", data); err != nil {
		t.Errorf(".mariner.shot: %s", err)
	} else if o != "ALBATROSS" {
		t.Errorf("Expected that mariner shot ALBATROSS")
	}

	if o, err := ttpl("{{.water.water.where}}", data); err != nil {
		t.Errorf(".water.water.where: %s", err)
	} else if o != "everywhere" {
		t.Errorf("Expected water water everywhere")
	}
}

func ttpl(tpl string, v map[string]interface{}) (string, error) {
	var b bytes.Buffer
	tt := template.Must(template.New("t").Parse(tpl))
	if err := tt.Execute(&b, v); err != nil {
		return "", err
	}
	return b.String(), nil
}

var testCoalesceValuesYaml = `
top: yup

global:
  name: Ishmael
  subject: Queequeg
  nested:
    boat: true

pequod:
  global:
    name: Stinky
    harpooner: Tashtego
    nested:
      boat: false
      sail: true
  ahab:
    scope: whale
`

func TestCoalesceValues(t *testing.T) {
	tchart := "testdata/moby"
	c, err := LoadDir(tchart)
	if err != nil {
		t.Fatal(err)
	}

	tvals := &chart.Config{Raw: testCoalesceValuesYaml}

	v, err := CoalesceValues(c, tvals)
	if err != nil {
		t.Fatal(err)
	}
	j, _ := json.MarshalIndent(v, "", "  ")
	t.Logf("Coalesced Values: %s", string(j))

	tests := []struct {
		tpl    string
		expect string
	}{
		{"{{.top}}", "yup"},
		{"{{.name}}", "moby"},
		{"{{.global.name}}", "Ishmael"},
		{"{{.global.subject}}", "Queequeg"},
		{"{{.global.harpooner}}", "<no value>"},
		{"{{.pequod.name}}", "pequod"},
		{"{{.pequod.ahab.name}}", "ahab"},
		{"{{.pequod.ahab.scope}}", "whale"},
		{"{{.pequod.ahab.global.name}}", "Ishmael"},
		{"{{.pequod.ahab.global.subject}}", "Queequeg"},
		{"{{.pequod.ahab.global.harpooner}}", "Tashtego"},
		{"{{.pequod.global.name}}", "Ishmael"},
		{"{{.pequod.global.subject}}", "Queequeg"},
		{"{{.spouter.global.name}}", "Ishmael"},
		{"{{.spouter.global.harpooner}}", "<no value>"},

		{"{{.global.nested.boat}}", "true"},
		{"{{.pequod.global.nested.boat}}", "true"},
		{"{{.spouter.global.nested.boat}}", "true"},
		{"{{.pequod.global.nested.sail}}", "true"},
		{"{{.spouter.global.nested.sail}}", "<no value>"},
	}

	for _, tt := range tests {
		if o, err := ttpl(tt.tpl, v); err != nil || o != tt.expect {
			t.Errorf("Expected %q to expand to %q, got %q", tt.tpl, tt.expect, o)
		}
	}
}

func TestCoalesceTables(t *testing.T) {
	dst := map[string]interface{}{
		"name": "Ishmael",
		"address": map[string]interface{}{
			"street": "123 Spouter Inn Ct.",
			"city":   "Nantucket",
		},
		"details": map[string]interface{}{
			"friends": []string{"Tashtego"},
		},
		"boat": "pequod",
	}
	src := map[string]interface{}{
		"occupation": "whaler",
		"address": map[string]interface{}{
			"state":  "MA",
			"street": "234 Spouter Inn Ct.",
		},
		"details": "empty",
		"boat": map[string]interface{}{
			"mast": true,
		},
	}

	// What we expect is that anything in dst overrides anything in src, but that
	// otherwise the values are coalesced.
	coalesceTables(dst, src)

	if dst["name"] != "Ishmael" {
		t.Errorf("Unexpected name: %s", dst["name"])
	}
	if dst["occupation"] != "whaler" {
		t.Errorf("Unexpected occupation: %s", dst["occupation"])
	}

	addr, ok := dst["address"].(map[string]interface{})
	if !ok {
		t.Fatal("Address went away.")
	}

	if addr["street"].(string) != "123 Spouter Inn Ct." {
		t.Errorf("Unexpected address: %v", addr["street"])
	}

	if addr["city"].(string) != "Nantucket" {
		t.Errorf("Unexpected city: %v", addr["city"])
	}

	if addr["state"].(string) != "MA" {
		t.Errorf("Unexpected state: %v", addr["state"])
	}

	if det, ok := dst["details"].(map[string]interface{}); !ok {
		t.Fatalf("Details is the wrong type: %v", dst["details"])
	} else if _, ok := det["friends"]; !ok {
		t.Error("Could not find your friends. Maybe you don't have any. :-(")
	}

	if dst["boat"].(string) != "pequod" {
		t.Errorf("Expected boat string, got %v", dst["boat"])
	}
}


text:
lab: OK Lab Bonn
name: OK Lab Bonn Treffen
date: 2015-05-21 #YYYY-MM-DD
time: 19-21 Uhr
location: Stadthaus Bonn, Berliner Platz 2, 53111 Bonn, Sitzungsraum 1/2
link-url: http://www.meetup.com/OKLab-Bonn/#upcoming
---


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
promise_test(async () => {
  history.replaceState("state1", "", "#1");
  assert_equals(history.state, "state1");

  appHistory.onnavigate = e => e.transitionWhile(Promise.resolve("r"));
  await appHistory.navigate("#2").committed;
  assert_equals(location.hash, "#2");
  assert_equals(history.state, null);
}, "history.story should be nulled by navigate() handled by transitionWhile()");
</script>


text:
package org.apache.hyracks.algebricks.core.algebra.operators.logical;

import java.util.Collection;
import java.util.List;

import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.IPhysicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractLogicalOperator.ExecutionMode;
import org.apache.hyracks.algebricks.core.algebra.visitors.ILogicalExpressionReferenceTransform;

/**
 * @author rico
 */
public interface IOperatorExtension {

    void setExecutionMode(ExecutionMode mode);

    boolean isMap();

    public IOperatorExtension newInstance();

    boolean acceptExpressionTransform(ILogicalExpressionReferenceTransform transform) throws AlgebricksException;

    void setSchema(List<LogicalVariable> schema);

    IPhysicalOperator getPhysicalOperator();

    void setPhysicalOperator(IPhysicalOperator physicalOperator);

    ExecutionMode getExecutionMode();

    public void getUsedVariables(Collection<LogicalVariable> usedVars);

    public void getProducedVariables(Collection<LogicalVariable> producedVars);
}


text:
<?php

class Mirasvit_MstCore_Block_Adminhtml_Logger_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('loggerGrid');
        $this->setDefaultSort('log_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
    }

    protected function _prepareCollection()
    {
        $collection = Mage::getModel('mstcore/logger')->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    protected function _prepareColumns()
    {
        $this->addColumn('log_id', array(
                'header' => Mage::helper('mstcore')->__('ID'),
                'index'  => 'log_id',
                'type'   => 'number',
            )
        );

        $this->addColumn('level', array(
                'header' => Mage::helper('mstcore')->__('Level'),
                'index'  => 'level',
                'type'   => 'number',
            )
        );

        $this->addColumn('message', array(
                'header' => Mage::helper('mstcore')->__('Message'),
                'index'  => 'message',
            )
        );

        $this->addColumn('content', array(
                'header'   => Mage::helper('mstcore')->__('Content'),
                'index'    => 'content',
                'width'    => '330px',
                'renderer' => 'Mirasvit_MstCore_Block_Adminhtml_Logger_Renderer_Content'
            )
        );

        $this->addColumn('module', array(
                'header' => Mage::helper('mstcore')->__('Module'),
                'index'  => 'module',
            )
        );

        $this->addColumn('class', array(
                'header' => Mage::helper('mstcore')->__('Class'),
                'index'  => 'class',
            )
        );

        $this->addColumn('created_at', array(
                'header' => Mage::helper('mstcore')->__('Created At'),
                'index'  => 'created_at',
                'align'  => 'right',
                'type'   => 'datetime',
            )
        );

        return parent::_prepareColumns();
    }

    public function getRowUrl($row)
    {
        return false;
    }
}


text:
package edu.drexel.goodwin.cpd.domain;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.mock.staticmock.MockStaticEntityMethods;

import edu.drexel.goodwin.cpd.domain.Researcher;

@RunWith(JUnit4.class)
@MockStaticEntityMethods
public class ResearcherTest {

    @Test
    public void testMethod() {
        int expectedCount = 13;
        Researcher.countResearchers();
        org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl.expectReturn(expectedCount);
        org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl.playback();
        org.junit.Assert.assertEquals(expectedCount, Researcher.countResearchers());
    }
}


text:
word = str(input("Enter a word: "))

wordLen = len(word)
subLen = 1
start = 0

for i in range(wordLen):
    start = 0
    while start + subLen <= wordLen:
        print(word[start:start+subLen])
        start += 1
    subLen += 1